]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/IniConfig.php
Reformat code
[SourceForge/phpwiki.git] / lib / IniConfig.php
1 <?php
2
3 /**
4  * A configurator intended to read its config from a PHP-style INI file,
5  * instead of a PHP file.
6  *
7  * Pass a filename to the IniConfig() function and it will read all its
8  * definitions from there, all by itself, and proceed to do a mass-define
9  * of all valid PHPWiki config items.  In this way, we can hopefully be
10  * totally backwards-compatible with the old index.php method, while still
11  * providing a much tastier on-going experience.
12  *
13  * @author: Joby Walker, Reini Urban, Matthew Palmer
14  */
15 /*
16  * Copyright 2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
17  * Copyright 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
18  *
19  * This file is part of PhpWiki.
20  *
21  * PhpWiki is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 2 of the License, or
24  * (at your option) any later version.
25  *
26  * PhpWiki is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License along
32  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
33  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
34  */
35
36 /**
37  * DONE:
38  * - Convert the value lists to provide defaults, so that every "if
39  *      (defined())" and "if (!defined())" can fuck off to the dismal hole
40  *      it belongs in.
41  * - config.ini => config.php dumper for faster startup. (really faster? to time)
42  *
43  * TODO:
44  * - Old-style index.php => config/config.ini converter.
45  *
46  * - Don't use too much globals for easier integration into other projects
47  *   (namespace pollution). (FusionForge, phpnuke, postnuke, phpBB2, carolina, ...)
48  *   Use one global $phpwiki object instead which holds the cfg vars, constants
49  *   and all other globals.
50  *     (global $FieldSeparator, $charset, $WikiNameRegexp, $KeywordLinkRegexp;
51  *      global $DisabledActions, $DBParams, $LANG, $AllActionPages)
52  *
53  * - Resurrect the larger "config object" code (in config/) so it'll aid the
54  *   GUI config writers, and allow us to do proper validation and default
55  *   value handling.
56  *
57  * - Get rid of WikiNameRegexp and KeywordLinkRegexp as globals by finding
58  *   everywhere that uses them as variables and modify the code to use
59  *   them as constants.
60  */
61
62 include_once (dirname(__FILE__) . "/config.php");
63 include_once (dirname(__FILE__) . "/FileFinder.php");
64
65 /**
66  * Speed-up iniconfig loading.
67  *
68  * Dump the static parts of the parsed config/config.ini settings to a fast-loadable config.php file.
69  * The dynamic parts are then evaluated as before.
70  * Requires write-permissions to config/config.php
71  */
72 function save_dump($file)
73 {
74     $vars =& $GLOBALS; // copy + unset not possible
75     $ignore = array();
76     foreach (array("SERVER", "ENV", "GET", "POST", "REQUEST", "COOKIE", "FILES") as $key) {
77         $ignore["HTTP_" . $key . "_VARS"]++;
78         $ignore["_" . $key]++;
79     }
80     foreach (array("HTTP_POST_FILES", "GLOBALS", "RUNTIMER", "ErrorManager", 'LANG',
81                  'HOME_PAGE', 'request', 'SCRIPT_NAME', 'VIRTUAL_PATH', 'SCRIPT_FILENAME') as $key)
82         $ignore[$key]++;
83     $fp = fopen($file, "wb");
84     fwrite($fp, "<?php\n");
85     fwrite($fp, "function wiki_configrestore(){\n");
86     //TODO: optimize this by removing ignore, big serialized array and merge into existing GLOBALS
87     foreach ($vars as $var => $val) {
88         if (!$ignore[$var])
89             fwrite($fp, "\$GLOBALS['" . $var . "']=unserialize(\""
90                 . addslashes(serialize($val)) . "\");\n");
91     }
92     // cannot be optimized, maybe leave away predefined consts somehow
93     foreach (get_defined_constants() as $var => $val) {
94         if (substr($var, 0, 4) != "PHP_" and substr($var, 0, 2) != "E_"
95             and substr($var, 0, 2) != "T_"  and substr($var, 0, 2) != "M_"
96         )
97             fwrite($fp, "if(!defined('" . $var . "')) define('" . $var . "',unserialize(\""
98                 . addslashes(serialize($val)) . "\"));\n");
99     }
100     fwrite($fp, "return 'noerr';}");
101     fwrite($fp, "?>");
102     fclose($fp);
103 }
104
105 function _check_int_constant(&$c)
106 {
107     // if int value == string value, force int type
108     if (sprintf("%d", (int)$c) === $c) { // DEBUG & _DEBUG_bla
109         $c = (int)$c;
110     }
111 }
112
113 function IniConfig($file)
114 {
115
116     // Optionally check config/config.php dump for faster startup
117     $dump = substr($file, 0, -3) . "php";
118     if (isWindows($dump)) $dump = str_replace("/", "\\", $dump);
119     if (file_exists($dump) and is_readable($dump) and filesize($dump) > 0 and sort_file_mtime($dump, $file) < 0) {
120         @include($dump) or die("Error including " . $dump);
121         if (function_exists('wiki_configrestore') and (wiki_configrestore() === 'noerr')) {
122             fixup_dynamic_configs();
123             return;
124         }
125     }
126
127     // First-time installer detection here...
128     // Similar to SetupWiki()
129     if (!file_exists($file)) {
130         // We need to DATA_PATH for configurator, or pass the posted values
131         // somewhow to the script
132         $GLOBALS['charset'] = 'utf-8';
133         include_once(dirname(__FILE__) . "/install.php");
134         run_install("_part1");
135         if (!defined("_PHPWIKI_INSTALL_RUNNING"))
136             trigger_error("Datasource file '$file' does not exist", E_USER_ERROR);
137         exit();
138     }
139
140     // List of all valid config options to be define()d which take "values" (not
141     // booleans). Needs to be categorised, and generally made a lot tidier.
142     $_IC_VALID_VALUE = array
143     ('WIKI_NAME', 'ADMIN_USER', 'ADMIN_PASSWD',
144         'DEFAULT_DUMP_DIR', 'HTML_DUMP_DIR',
145         'HTML_DUMP_SUFFIX', 'MAX_UPLOAD_SIZE', 'MINOR_EDIT_TIMEOUT',
146         'ACCESS_LOG', 'CACHE_CONTROL', 'CACHE_CONTROL_MAX_AGE',
147         'COOKIE_EXPIRATION_DAYS', 'COOKIE_DOMAIN',
148         'PASSWORD_LENGTH_MINIMUM', 'USER_AUTH_POLICY',
149         'GROUP_METHOD',
150         'EDITING_POLICY', 'THEME', 'CHARSET',
151         'WIKI_PGSRC', 'DEFAULT_WIKI_PGSRC',
152         'ALLOWED_PROTOCOLS', 'INLINE_IMAGES', 'SUBPAGE_SEPARATOR', /*'KEYWORDS',*/
153         // extra logic:
154         //'DATABASE_PREFIX', 'DATABASE_DSN', 'DATABASE_TYPE', 'DATABASE_DBHANDLER',
155         'DATABASE_OPTIMISE_FREQUENCY',
156         'INTERWIKI_MAP_FILE', 'COPYRIGHTPAGE_TITLE', 'COPYRIGHTPAGE_URL',
157         'AUTHORPAGE_TITLE', 'AUTHORPAGE_URL',
158         'WIKI_NAME_REGEXP',
159         'PLUGIN_CACHED_DATABASE', 'PLUGIN_CACHED_FILENAME_PREFIX',
160         'PLUGIN_CACHED_HIGHWATER', 'PLUGIN_CACHED_LOWWATER', 'PLUGIN_CACHED_MAXLIFETIME',
161         'PLUGIN_CACHED_MAXARGLEN', 'PLUGIN_CACHED_IMGTYPES',
162         'WYSIWYG_BACKEND', 'PLUGIN_MARKUP_MAP',
163         // extra logic:
164         'SERVER_NAME', 'SERVER_PORT', 'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH',
165         'EXTERNAL_HTML2PDF_PAGELIST', 'PLUGIN_CACHED_CACHE_DIR'
166     );
167
168     // Optional values which need to be defined.
169     // These are not defined in config-default.ini and empty if not defined.
170     $_IC_OPTIONAL_VALUE = array
171     (
172         'DEBUG', 'TEMP_DIR', 'DEFAULT_LANGUAGE',
173         'LDAP_AUTH_HOST', 'LDAP_SET_OPTION', 'LDAP_BASE_DN', 'LDAP_AUTH_USER',
174         'LDAP_AUTH_PASSWORD', 'LDAP_SEARCH_FIELD', 'LDAP_OU_GROUP', 'LDAP_OU_USERS',
175         'AUTH_USER_FILE', 'DBAUTH_AUTH_DSN',
176         'IMAP_AUTH_HOST', 'POP3_AUTH_HOST',
177         'AUTH_USER_FILE', 'AUTH_GROUP_FILE', 'AUTH_SESS_USER', 'AUTH_SESS_LEVEL',
178         'GOOGLE_LICENSE_KEY', 'FORTUNE_DIR',
179         'DISABLE_GETIMAGESIZE', 'DBADMIN_USER', 'DBADMIN_PASSWD',
180         'SESSION_SAVE_PATH',
181         'TOOLBAR_PAGELINK_PULLDOWN', 'TOOLBAR_TEMPLATE_PULLDOWN', 'TOOLBAR_IMAGE_PULLDOWN',
182         'EXTERNAL_LINK_TARGET', 'ACCESS_LOG_SQL', 'USE_EXTERNAL_HTML2PDF',
183         'LOGIN_LOG', 'LDAP_SEARCH_FILTER'
184     );
185
186     // List of all valid config options to be define()d which take booleans.
187     $_IC_VALID_BOOL = array
188     ('ENABLE_USER_NEW', 'ENABLE_PAGEPERM', 'ENABLE_EDIT_TOOLBAR', 'JS_SEARCHREPLACE',
189         'ENABLE_XHTML_XML', 'ENABLE_DOUBLECLICKEDIT', 'ENABLE_LIVESEARCH', 'ENABLE_ACDROPDOWN',
190         'USECACHE', 'WIKIDB_NOCACHE_MARKUP',
191         'ENABLE_REVERSE_DNS', 'ENCRYPTED_PASSWD', 'ZIPDUMP_AUTH',
192         'ENABLE_RAW_HTML', 'ENABLE_RAW_HTML_LOCKEDONLY', 'ENABLE_RAW_HTML_SAFE',
193         'STRICT_MAILABLE_PAGEDUMPS', 'COMPRESS_OUTPUT',
194         'ALLOW_ANON_USER', 'ALLOW_ANON_EDIT',
195         'ALLOW_BOGO_LOGIN', 'ALLOW_USER_PASSWORDS',
196         'AUTH_USER_FILE_STORABLE', 'ALLOW_HTTP_AUTH_LOGIN',
197         'ALLOW_USER_LOGIN', 'ALLOW_LDAP_LOGIN', 'ALLOW_IMAP_LOGIN',
198         'WARN_NONPUBLIC_INTERWIKIMAP', 'USE_PATH_INFO',
199         'DISABLE_HTTP_REDIRECT',
200         'PLUGIN_CACHED_USECACHE', 'PLUGIN_CACHED_FORCE_SYNCMAP',
201         'BLOG_DEFAULT_EMPTY_PREFIX', 'DATABASE_PERSISTENT',
202         'FUSIONFORGE',
203         'ENABLE_DISCUSSION_LINK', 'ENABLE_CAPTCHA',
204         'ENABLE_WYSIWYG', 'WYSIWYG_DEFAULT_PAGETYPE_HTML',
205         'DISABLE_MARKUP_WIKIWORD', 'ENABLE_MARKUP_COLOR', 'ENABLE_MARKUP_TEMPLATE',
206         'ENABLE_MARKUP_MEDIAWIKI_TABLE',
207         'ENABLE_MARKUP_DIVSPAN', 'USE_BYTEA', 'UPLOAD_USERDIR', 'DISABLE_UNITS',
208         'ENABLE_SEARCHHIGHLIGHT', 'DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS',
209         'ENABLE_AUTH_OPENID', 'INSECURE_ACTIONS_LOCALHOST_ONLY',
210         'ENABLE_MAILNOTIFY', 'ENABLE_RECENTCHANGESBOX', 'ENABLE_PAGE_PUBLIC',
211         'ENABLE_AJAX', 'ENABLE_EXTERNAL_PAGES',
212         'READONLY'
213     );
214
215     $rs = @parse_ini_file($file);
216     $rsdef = @parse_ini_file(dirname(__FILE__) . "/../config/config-default.ini");
217     foreach ($rsdef as $k => $v) {
218         if (defined($k)) {
219             $rs[$k] = constant($k);
220         } elseif (!isset($rs[$k])) {
221             $rs[$k] = $v;
222         }
223     }
224     unset($k);
225     unset($v);
226
227     foreach ($_IC_VALID_VALUE as $item) {
228         if (defined($item)) {
229             unset($rs[$item]);
230             continue;
231         }
232         if (array_key_exists($item, $rs)) {
233             _check_int_constant($rs[$item]);
234             define($item, $rs[$item]);
235             unset($rs[$item]);
236             //} elseif (array_key_exists($item, $rsdef)) {
237             //    define($item, $rsdef[$item]);
238             // calculate them later or not at all:
239         } elseif (in_array($item,
240             array('DATABASE_PREFIX', 'SERVER_NAME', 'SERVER_PORT',
241                 'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH',
242                 'LDAP_AUTH_HOST', 'IMAP_AUTH_HOST', 'POP3_AUTH_HOST',
243                 'PLUGIN_CACHED_CACHE_DIR', 'EXTERNAL_HTML2PDF_PAGELIST'))
244         ) {
245             ;
246         } elseif (!defined("_PHPWIKI_INSTALL_RUNNING")) {
247             trigger_error(sprintf("missing config setting for %s", $item));
248         }
249     }
250     unset($item);
251
252     // Boolean options are slightly special - if they're set to any of
253     // '', 'false', '0', or 'no' (all case-insensitive) then the value will
254     // be a boolean false, otherwise if there is anything set it'll
255     // be true.
256     foreach ($_IC_VALID_BOOL as $item) {
257         if (defined($item)) {
258             unset($rs[$item]);
259             continue;
260         }
261         if (array_key_exists($item, $rs)) {
262             $val = $rs[$item];
263             //} elseif (array_key_exists($item, $rsdef)) {
264             //    $val = $rsdef[$item];
265         } else {
266             $val = false;
267             //trigger_error(sprintf("missing boolean config setting for %s",$item));
268         }
269
270         // calculate them later: old or dynamic constants
271         if (!array_key_exists($item, $rs) and
272             in_array($item, array('USE_PATH_INFO', 'USE_DB_SESSION',
273                 'ALLOW_HTTP_AUTH_LOGIN', 'ALLOW_LDAP_LOGIN',
274                 'ALLOW_IMAP_LOGIN', 'ALLOW_USER_LOGIN',
275                 'REQUIRE_SIGNIN_BEFORE_EDIT',
276                 'WIKIDB_NOCACHE_MARKUP',
277                 'COMPRESS_OUTPUT', 'USE_BYTEA', 'READONLY',
278             ))
279         ) {
280             ;
281         } elseif (!$val) {
282             define($item, false);
283         } elseif (strtolower($val) == 'false' ||
284             strtolower($val) == 'no' ||
285             $val == '' ||
286             $val == false ||
287             $val == '0'
288         ) {
289             define($item, false);
290         } else {
291             define($item, true);
292         }
293         unset($rs[$item]);
294     }
295     unset($item);
296
297     // Database
298     global $DBParams;
299     foreach (array('DATABASE_TYPE' => 'dbtype',
300                  'DATABASE_DSN' => 'dsn',
301                  'DATABASE_SESSION_TABLE' => 'db_session_table',
302                  'DATABASE_DBA_HANDLER' => 'dba_handler',
303                  'DATABASE_DIRECTORY' => 'directory',
304                  'DATABASE_TIMEOUT' => 'timeout',
305                  'DATABASE_PREFIX' => 'prefix')
306              as $item => $k) {
307         if (defined($item)) {
308             $DBParams[$k] = constant($item);
309             unset($rs[$item]);
310         } elseif (array_key_exists($item, $rs)) {
311             $DBParams[$k] = $rs[$item];
312             define($item, $rs[$item]);
313             unset($rs[$item]);
314         } elseif (array_key_exists($item, $rsdef)) {
315             $DBParams[$k] = $rsdef[$item];
316             define($item, $rsdef[$item]);
317             unset($rsdef[$item]);
318         }
319     }
320     $valid_database_types = array('SQL', 'ADODB', 'PDO', 'dba', 'file', 'flatfile', 'cvs', 'cvsclient');
321     if (!in_array(DATABASE_TYPE, $valid_database_types))
322         trigger_error(sprintf("Invalid DATABASE_TYPE=%s. Choose one of %s",
323                 DATABASE_TYPE, join(",", $valid_database_types)),
324             E_USER_ERROR);
325     unset($valid_database_types);
326     if (DATABASE_TYPE == 'PDO') {
327         if (!check_php_version(5))
328             trigger_error("Invalid DATABASE_TYPE=PDO. PDO requires at least php-5.0!",
329                 E_USER_ERROR);
330         // try to load it dynamically (unix only)
331         if (!loadPhpExtension("pdo")) {
332             echo $GLOBALS['php_errormsg'], "<br>\n";
333             trigger_error(sprintf("dl() problem: Required extension '%s' could not be loaded!",
334                     "pdo"),
335                 E_USER_ERROR);
336         }
337     }
338     // Detect readonly database, e.g. system mounted read-only for maintenance
339     // via dbh->readonly later. Unfortunately not possible as constant.
340
341     // USE_DB_SESSION default logic:
342     if (!defined('USE_DB_SESSION')) {
343         if ($DBParams['db_session_table']
344             and in_array($DBParams['dbtype'], array('SQL', 'ADODB', 'PDO', 'dba'))
345         ) {
346             define('USE_DB_SESSION', true);
347         } else {
348             define('USE_DB_SESSION', false);
349         }
350     }
351     unset($item);
352     unset($k);
353
354     // Expiry stuff
355     global $ExpireParams;
356     foreach (array('major', 'minor', 'author') as $major) {
357         foreach (array('max_age', 'min_age', 'min_keep', 'keep', 'max_keep') as $max) {
358             $item = strtoupper($major) . '_' . strtoupper($max);
359             if (defined($item)) $val = constant($item);
360             elseif (array_key_exists($item, $rs))
361                 $val = $rs[$item]; elseif (array_key_exists($item, $rsdef))
362                 $val = $rsdef[$item];
363             if (!isset($ExpireParams[$major]))
364                 $ExpireParams[$major] = array();
365             $ExpireParams[$major][$max] = $val;
366             unset($rs[$item]);
367         }
368     }
369     unset($item);
370     unset($major);
371     unset($max);
372
373     // User authentication
374     if (!isset($GLOBALS['USER_AUTH_ORDER'])) {
375         if (isset($rs['USER_AUTH_ORDER']))
376             $GLOBALS['USER_AUTH_ORDER'] = preg_split('/\s*:\s*/',
377                 $rs['USER_AUTH_ORDER']);
378         else
379             $GLOBALS['USER_AUTH_ORDER'] = array("PersonalPage");
380     }
381
382     // Now it's the external DB authentication stuff's turn
383     if (in_array('Db', $GLOBALS['USER_AUTH_ORDER']) && empty($rs['DBAUTH_AUTH_DSN'])) {
384         $rs['DBAUTH_AUTH_DSN'] = $DBParams['dsn'];
385     }
386
387     global $DBAuthParams;
388     $DBAP_MAP = array('DBAUTH_AUTH_DSN' => 'auth_dsn',
389         'DBAUTH_AUTH_CHECK' => 'auth_check',
390         'DBAUTH_AUTH_USER_EXISTS' => 'auth_user_exists',
391         'DBAUTH_AUTH_CRYPT_METHOD' => 'auth_crypt_method',
392         'DBAUTH_AUTH_UPDATE' => 'auth_update',
393         'DBAUTH_AUTH_CREATE' => 'auth_create',
394         'DBAUTH_PREF_SELECT' => 'pref_select',
395         'DBAUTH_PREF_INSERT' => 'pref_insert',
396         'DBAUTH_PREF_UPDATE' => 'pref_update',
397         'DBAUTH_IS_MEMBER' => 'is_member',
398         'DBAUTH_GROUP_MEMBERS' => 'group_members',
399         'DBAUTH_USER_GROUPS' => 'user_groups'
400     );
401     foreach ($DBAP_MAP as $rskey => $apkey) {
402         if (defined($rskey)) {
403             $DBAuthParams[$apkey] = constant($rskey);
404         } elseif (isset($rs[$rskey])) {
405             $DBAuthParams[$apkey] = $rs[$rskey];
406             define($rskey, $rs[$rskey]);
407         } elseif (isset($rsdef[$rskey])) {
408             $DBAuthParams[$apkey] = $rsdef[$rskey];
409             define($rskey, $rsdef[$rskey]);
410         }
411         unset($rs[$rskey]);
412     }
413     unset($rskey);
414     unset($apkey);
415
416     // TODO: Currently unsupported on non-SQL. Nice to have for RhNavPlugin
417     // CHECKME: PDO
418     if (!defined('ACCESS_LOG_SQL')) {
419         if (array_key_exists('ACCESS_LOG_SQL', $rs)) {
420             // WikiDB_backend::isSql() not yet loaded
421             if (!in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO'))) {
422                 // override false config setting on no SQL WikiDB database.
423                 define('ACCESS_LOG_SQL', 0);
424             }
425             // SQL defaults to ACCESS_LOG_SQL = 2
426         } else {
427             define('ACCESS_LOG_SQL',
428             in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO')) ? 2 : 0);
429         }
430     }
431
432     global $PLUGIN_MARKUP_MAP;
433     $PLUGIN_MARKUP_MAP = array();
434     if (defined('PLUGIN_MARKUP_MAP') and trim(PLUGIN_MARKUP_MAP) != "") {
435         $_map = preg_split('/\s+/', PLUGIN_MARKUP_MAP);
436         foreach ($_map as $v) {
437             list($xml, $plugin) = explode(':', $v);
438             if (!empty($xml) and !empty($plugin))
439                 $PLUGIN_MARKUP_MAP[$xml] = $plugin;
440         }
441         unset($_map);
442         unset($xml);
443         unset($plugin);
444         unset($v);
445     }
446
447     if (empty($rs['TEMP_DIR'])) {
448         $rs['TEMP_DIR'] = "/tmp";
449         if (getenv("TEMP"))
450             $rs['TEMP_DIR'] = getenv("TEMP");
451     }
452     // optional values will be set to '' to simplify the logic.
453     foreach ($_IC_OPTIONAL_VALUE as $item) {
454         if (defined($item)) {
455             unset($rs[$item]);
456             continue;
457         }
458         if (array_key_exists($item, $rs)) {
459             _check_int_constant($rs[$item]);
460             define($item, $rs[$item]);
461             unset($rs[$item]);
462         } else
463             define($item, '');
464     }
465
466     if (USE_EXTERNAL_HTML2PDF) {
467         $item = 'EXTERNAL_HTML2PDF_PAGELIST';
468         if (defined($item)) {
469             unset($rs[$item]);
470         } elseif (array_key_exists($item, $rs)) {
471             define($item, $rs[$item]);
472             unset($rs[$item]);
473         } elseif (array_key_exists($item, $rsdef)) {
474             define($item, $rsdef[$item]);
475         }
476     }
477     unset($item);
478
479     // LDAP bind options
480     global $LDAP_SET_OPTION;
481     if (defined('LDAP_SET_OPTION') and LDAP_SET_OPTION) {
482         $optlist = preg_split('/\s*:\s*/', LDAP_SET_OPTION);
483         foreach ($optlist as $opt) {
484             $bits = preg_split('/\s*=\s*/', $opt, 2);
485             if (count($bits) == 2) {
486                 if (is_string($bits[0]) and defined($bits[0]))
487                     $bits[0] = constant($bits[0]);
488                 $LDAP_SET_OPTION[$bits[0]] = $bits[1];
489             } else {
490                 // Possibly throw some sort of error?
491             }
492         }
493         unset($opt);
494         unset($bits);
495     }
496
497     // Default Wiki pages to force loading from pgsrc
498     global $GenericPages;
499     $GenericPages = preg_split('/\s*:\s*/', @$rs['DEFAULT_WIKI_PAGES']);
500
501     // Wiki name regexp:  Should be a define(), but might needed to be changed at runtime
502     // (different LC_CHAR need different posix classes)
503     global $WikiNameRegexp;
504     $WikiNameRegexp = constant('WIKI_NAME_REGEXP');
505     if (!trim($WikiNameRegexp))
506         $WikiNameRegexp = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])';
507
508     // Got rid of global $KeywordLinkRegexp by using a TextSearchQuery instead
509     // of "Category:Topic"
510     if (!isset($rs['KEYWORDS'])) $rs['KEYWORDS'] = @$rsdef['KEYWORDS'];
511     if (!isset($rs['KEYWORDS'])) $rs['KEYWORDS'] = "Category* OR Topic*";
512     if ($rs['KEYWORDS'] == 'Category:Topic') $rs['KEYWORDS'] = "Category* OR Topic*";
513     if (!defined('KEYWORDS')) define('KEYWORDS', $rs['KEYWORDS']);
514     //if (empty($keywords)) $keywords = array("Category","Topic");
515     //$KeywordLinkRegexp = '(?<=' . implode('|^', $keywords) . ')[[:upper:]].*$';
516
517     // TODO: can this be a constant?
518     global $DisabledActions;
519     if (!array_key_exists('DISABLED_ACTIONS', $rs)
520         and array_key_exists('DISABLED_ACTIONS', $rsdef)
521     )
522         $rs['DISABLED_ACTIONS'] = @$rsdef['DISABLED_ACTIONS'];
523     if (array_key_exists('DISABLED_ACTIONS', $rs))
524         $DisabledActions = preg_split('/\s*:\s*/', $rs['DISABLED_ACTIONS']);
525
526     global $PLUGIN_CACHED_IMGTYPES;
527     $PLUGIN_CACHED_IMGTYPES = preg_split('/\s*[|:]\s*/', PLUGIN_CACHED_IMGTYPES);
528
529     if (!defined('PLUGIN_CACHED_CACHE_DIR')) {
530         if (empty($rs['PLUGIN_CACHED_CACHE_DIR']) and !empty($rsdef['PLUGIN_CACHED_CACHE_DIR']))
531             $rs['PLUGIN_CACHED_CACHE_DIR'] = $rsdef['PLUGIN_CACHED_CACHE_DIR'];
532         if (empty($rs['PLUGIN_CACHED_CACHE_DIR'])) {
533             if (!empty($rs['INCLUDE_PATH'])) {
534                 @ini_set('include_path', $rs['INCLUDE_PATH']);
535                 $GLOBALS['INCLUDE_PATH'] = $rs['INCLUDE_PATH'];
536             }
537             $rs['PLUGIN_CACHED_CACHE_DIR'] = TEMP_DIR . '/cache';
538             if (!FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], 1)) { // [29ms]
539                 FindFile(TEMP_DIR, false, 1); // TEMP must exist!
540                 mkdir($rs['PLUGIN_CACHED_CACHE_DIR'], 0777);
541             }
542             // will throw an error if not exists.
543             define('PLUGIN_CACHED_CACHE_DIR', FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], false, 1));
544         } else {
545             define('PLUGIN_CACHED_CACHE_DIR', $rs['PLUGIN_CACHED_CACHE_DIR']);
546             // will throw an error if not exists.
547             FindFile(PLUGIN_CACHED_CACHE_DIR);
548         }
549     }
550
551     // process the rest of the config.ini settings:
552     foreach ($rs as $item => $v) {
553         if (defined($item)) {
554             continue;
555         } else {
556             _check_int_constant($v);
557             define($item, $v);
558         }
559     }
560     unset($item);
561     unset($v);
562
563     unset($rs);
564     unset($rsdef);
565
566     fixup_static_configs($file); //[1ms]
567     // Dump all globals and constants
568     // The question is if reading this is faster then doing IniConfig() + fixup_static_configs()
569     if (is_writable($dump)) {
570         save_dump($dump);
571     }
572     // store locale[] in config.php? This is too problematic.
573     fixup_dynamic_configs($file); // [100ms]
574 }
575
576 function _ignore_unknown_charset_warning(&$error)
577 {
578     //htmlspecialchars(): charset `iso-8859-2' not supported, assuming iso-8859-1
579     if (preg_match('/^htmlspecialchars\(\): charset \`.+\' not supported, assuming iso-8859-1/',
580         $error->errstr)
581     ) {
582         $error->errno = 0;
583         return true; // Ignore error
584     }
585     return false;
586 }
587
588 // moved from lib/config.php [1ms]
589 function fixup_static_configs($file)
590 {
591     global $FieldSeparator, $charset, $WikiNameRegexp, $AllActionPages;
592     global $HTTP_SERVER_VARS, $DBParams, $LANG, $ErrorManager;
593     // init FileFinder to add proper include paths
594     FindFile("lib/interwiki.map", true);
595
596     // "\x80"-"\x9f" (and "\x00" - "\x1f") are non-printing control
597     // chars in iso-8859-*
598     // $FieldSeparator = "\263"; // this is a superscript 3 in ISO-8859-1.
599     // $FieldSeparator = "\xFF"; // this byte should never appear in utf-8
600     // Get rid of constant. pref is dynamic and language specific
601     $charset = CHARSET;
602     // Disabled: Let the admin decide which charset.
603     //if (isset($LANG) and in_array($LANG,array('zh')))
604     //    $charset = 'utf-8';
605     if (strtolower($charset) == 'utf-8')
606         $FieldSeparator = "\xFF";
607     else
608         $FieldSeparator = "\x81";
609
610     // Some exotic charsets are not supported by htmlspecialchars, which just prints an E_WARNING.
611     // Even on simple 8bit charsets, where just <>& need to be replaced. For iso-8859-[2-4] e.g.
612     // See <php-src>/ext/standard/html.c
613     // For performance reasons we require a magic constant to ignore this warning.
614     if (defined('IGNORE_CHARSET_NOT_SUPPORTED_WARNING')
615         and IGNORE_CHARSET_NOT_SUPPORTED_WARNING
616     ) {
617         $ErrorManager->pushErrorHandler
618         (new WikiFunctionCb('_ignore_unknown_charset_warning'));
619     }
620
621     // All pages containing plugins of the same name as the filename
622     $ActionPages = explode(':',
623         'AllPages:AllUsers:AppendText:AuthorHistory:'
624             . 'BackLinks:'
625             . 'CreatePage:'
626             . 'FullTextSearch:FuzzyPages:'
627             . 'LikePages:LinkDatabase:LinkSearch:ListRelations:'
628             . 'ModeratedPage:MostPopular:'
629             . 'NewPagesPerUser:'
630             . 'OrphanedPages:'
631             . 'PageDump:PageHistory:PageInfo:PluginManager:'
632             . 'RateIt:' // RateIt works only in wikilens derived themes
633             . 'RandomPage:RecentChanges:RelatedChanges:RecentEdits:'
634             . 'SearchHighlight:SemanticRelations:SemanticSearch:SystemInfo:'
635             . 'TitleSearch:'
636             . 'UpLoad:UserPreferences:'
637             . 'UserRatings:' // UserRatings works only in wikilens derived themes
638             . 'WantedPages:WatchPage:WhoIsOnline:WikiAdminSelect');
639
640     // The FUSIONFORGE theme omits them
641     if (!FUSIONFORGE) {
642         // Add some some action pages depending on configuration
643         if (DEBUG) {
644             $ActionPages[] = 'DebugInfo';
645             $ActionPages[] = 'EditMetaData';
646             $ActionPages[] = 'SpellCheck'; // SpellCheck does not work
647         }
648         $ActionPages[] = 'BlogArchives';
649         $ActionPages[] = 'BlogJournal';
650         $ActionPages[] = 'InterWikiSearch';
651         $ActionPages[] = 'LdapSearch';
652         $ActionPages[] = 'PasswordReset';
653         $ActionPages[] = 'RecentComments';
654         $ActionPages[] = 'TranslateText';
655         $ActionPages[] = 'UriResolver';
656         $ActionPages[] = 'WikiBlog';
657     }
658
659     global $AllAllowedPlugins;
660     $AllAllowedPlugins = $ActionPages;
661     // Add plugins that have no corresponding action page
662     $AllAllowedPlugins[] = 'AsciiSVG';
663     $AllAllowedPlugins[] = 'AtomFeed';
664     $AllAllowedPlugins[] = 'BoxRight';
665     $AllAllowedPlugins[] = 'CalendarList';
666     $AllAllowedPlugins[] = 'Calendar';
667     $AllAllowedPlugins[] = 'CategoryPage';
668     $AllAllowedPlugins[] = 'Chart';
669     $AllAllowedPlugins[] = 'Comment';
670     $AllAllowedPlugins[] = 'CreateBib';
671     $AllAllowedPlugins[] = 'CreateToc';
672     $AllAllowedPlugins[] = 'CurrentTime';
673     $AllAllowedPlugins[] = 'DeadEndPages';
674     $AllAllowedPlugins[] = 'Diff';
675     $AllAllowedPlugins[] = 'DynamicIncludePage';
676     $AllAllowedPlugins[] = 'ExternalSearch';
677     $AllAllowedPlugins[] = 'FacebookLike';
678     $AllAllowedPlugins[] = 'FileInfo';
679     $AllAllowedPlugins[] = 'GoogleMaps';
680     $AllAllowedPlugins[] = 'GooglePlugin';
681     $AllAllowedPlugins[] = 'GoTo';
682     $AllAllowedPlugins[] = 'HelloWorld';
683     $AllAllowedPlugins[] = 'IncludePage';
684     $AllAllowedPlugins[] = 'IncludePages';
685     $AllAllowedPlugins[] = 'IncludeSiteMap';
686     $AllAllowedPlugins[] = 'IncludeTree';
687     $AllAllowedPlugins[] = 'ListPages';
688     $AllAllowedPlugins[] = 'ListSubpages';
689     $AllAllowedPlugins[] = 'MediawikiTable';
690     $AllAllowedPlugins[] = 'NoCache';
691     $AllAllowedPlugins[] = 'OldStyleTable';
692     $AllAllowedPlugins[] = 'PageGroup';
693     $AllAllowedPlugins[] = 'PageTrail';
694     $AllAllowedPlugins[] = 'PhotoAlbum';
695     $AllAllowedPlugins[] = 'PhpHighlight';
696     $AllAllowedPlugins[] = 'PopularTags';
697     $AllAllowedPlugins[] = 'PopUp';
698     $AllAllowedPlugins[] = 'PrevNext';
699     $AllAllowedPlugins[] = 'Processing';
700     $AllAllowedPlugins[] = 'RawHtml';
701     $AllAllowedPlugins[] = 'RecentChangesCached';
702     $AllAllowedPlugins[] = 'RecentReferrers';
703     $AllAllowedPlugins[] = 'RedirectTo';
704     $AllAllowedPlugins[] = 'RichTable';
705     $AllAllowedPlugins[] = 'RssFeed';
706     $AllAllowedPlugins[] = 'SemanticSearchAdvanced';
707     $AllAllowedPlugins[] = 'SiteMap';
708     $AllAllowedPlugins[] = 'SyncWiki';
709     $AllAllowedPlugins[] = 'SyntaxHighlighter';
710     $AllAllowedPlugins[] = 'Template';
711     $AllAllowedPlugins[] = 'Transclude';
712     $AllAllowedPlugins[] = 'UnfoldSubpages';
713     $AllAllowedPlugins[] = 'Video';
714     $AllAllowedPlugins[] = 'WikiAdminChown';
715     $AllAllowedPlugins[] = 'WikiAdminPurge';
716     $AllAllowedPlugins[] = 'WikiAdminRemove';
717     $AllAllowedPlugins[] = 'WikiAdminRename';
718     $AllAllowedPlugins[] = 'WikiAdminSearchReplace';
719     $AllAllowedPlugins[] = 'WikiAdminSetAcl';
720     $AllAllowedPlugins[] = 'WikiAdminSetAclSimple';
721     $AllAllowedPlugins[] = 'WikiAdminUtils';
722     $AllAllowedPlugins[] = 'WikicreoleTable';
723     $AllAllowedPlugins[] = 'WikiForm';
724     $AllAllowedPlugins[] = 'WikiFormRich';
725     $AllAllowedPlugins[] = 'WikiPoll';
726     $AllAllowedPlugins[] = 'YouTube';
727
728     // The FUSIONFORGE theme omits them
729     if (!FUSIONFORGE) {
730         $AllAllowedPlugins[] = 'AddComment';
731         $AllAllowedPlugins[] = 'AnalyseAccessLogSql';
732         $AllAllowedPlugins[] = 'AsciiMath';
733         $AllAllowedPlugins[] = '_AuthInfo';
734         $AllAllowedPlugins[] = '_BackendInfo';
735         $AllAllowedPlugins[] = 'CacheTest';
736         $AllAllowedPlugins[] = 'CategoryPage';
737         $AllAllowedPlugins[] = 'FoafViewer';
738         $AllAllowedPlugins[] = 'FrameInclude';
739         $AllAllowedPlugins[] = 'GraphViz';
740         $AllAllowedPlugins[] = '_GroupInfo';
741         $AllAllowedPlugins[] = 'HtmlConverter';
742         $AllAllowedPlugins[] = 'Imdb';
743         $AllAllowedPlugins[] = 'JabberPresence';
744         $AllAllowedPlugins[] = 'ListPages';
745         $AllAllowedPlugins[] = 'PhpWeather';
746         $AllAllowedPlugins[] = 'Ploticus';
747         $AllAllowedPlugins[] = 'PopularNearby';
748         $AllAllowedPlugins[] = 'PreferenceApp';
749         $AllAllowedPlugins[] = '_PreferencesInfo';
750         $AllAllowedPlugins[] = '_Retransform';
751         $AllAllowedPlugins[] = 'SqlResult';
752         $AllAllowedPlugins[] = 'TeX2png';
753         $AllAllowedPlugins[] = 'text2png';
754         $AllAllowedPlugins[] = 'TexToPng';
755         $AllAllowedPlugins[] = 'VisualWiki';
756         $AllAllowedPlugins[] = 'WantedPagesOld';
757         $AllAllowedPlugins[] = 'WikiAdminChmod';
758         $AllAllowedPlugins[] = 'WikiAdminMarkup';
759         $AllAllowedPlugins[] = 'WikiForum';
760         $AllAllowedPlugins[] = '_WikiTranslation';
761     }
762
763     // Used by SetupWiki to pull in required pages, if not translated, then in English.
764     // Also used by _WikiTranslation. Really important are only those which return pagelists
765     // or contain basic functionality.
766     $AllActionPages = $ActionPages;
767     $AllActionPages[] = 'AllPagesCreatedByMe';
768     $AllActionPages[] = 'AllPagesLastEditedByMe';
769     $AllActionPages[] = 'AllPagesOwnedByMe';
770     $AllActionPages[] = 'AllPagesByAcl';
771     $AllActionPages[] = 'AllUserPages';
772     $AllActionPages[] = 'FullRecentChanges';
773     $AllActionPages[] = 'LeastPopular';
774     $AllActionPages[] = 'LockedPages';
775     $AllActionPages[] = 'MyRatings'; // MyRatings works only in wikilens-derived themes
776     $AllActionPages[] = 'MyRecentEdits';
777     $AllActionPages[] = 'MyRecentChanges';
778     $AllActionPages[] = 'PhpWikiAdministration';
779     $AllActionPages[] = 'PhpWikiAdministration/Chown';
780     $AllActionPages[] = 'PhpWikiAdministration/Purge';
781     $AllActionPages[] = 'PhpWikiAdministration/Remove';
782     $AllActionPages[] = 'PhpWikiAdministration/Rename';
783     $AllActionPages[] = 'PhpWikiAdministration/SearchReplace';
784     $AllActionPages[] = 'PhpWikiAdministration/SetAcl';
785     $AllActionPages[] = 'PhpWikiAdministration/SetAclSimple';
786     $AllActionPages[] = 'RecentChangesMyPages';
787     $AllActionPages[] = 'RecentEdits';
788     $AllActionPages[] = 'RecentNewPages';
789     $AllActionPages[] = 'SetGlobalAccessRights';
790     $AllActionPages[] = 'SetGlobalAccessRightsSimple';
791     $AllActionPages[] = 'UserContribs';
792
793     // The FUSIONFORGE theme omits them
794     if (!FUSIONFORGE) {
795         // Add some some action pages depending on configuration
796         if (DEBUG) {
797             $AllActionPages[] = 'PhpWikiAdministration/Chmod';
798         }
799         $AllActionPages[] = 'PhpWikiAdministration/Markup';
800     }
801
802     if (FUSIONFORGE) {
803         if (ENABLE_EXTERNAL_PAGES) {
804             $AllAllowedPlugins[] = 'WikiAdminSetExternal';
805             $AllActionPages[] = 'PhpWikiAdministration/SetExternal';
806             $AllActionPages[] = 'ExternalPages';
807         }
808     }
809
810     // If user has not defined PHPWIKI_DIR, and we need it
811     if (!defined('PHPWIKI_DIR') and !file_exists("themes/default")) {
812         $themes_dir = FindFile("themes");
813         define('PHPWIKI_DIR', dirname($themes_dir));
814     }
815
816     // If user has not defined DATA_PATH, we want to use relative URLs.
817     if (!defined('DATA_PATH')) {
818         // fix similar to the one suggested by jkalmbach for
819         // installations in the webrootdir, like "http://phpwiki.org/HomePage"
820         if (!defined('SCRIPT_NAME'))
821             define('SCRIPT_NAME', deduce_script_name());
822         $temp = dirname(SCRIPT_NAME);
823         if (($temp == '/') || ($temp == '\\'))
824             $temp = '';
825         define('DATA_PATH', $temp);
826         /*
827         if (USE_PATH_INFO)
828             define('DATA_PATH', '..');
829         */
830     }
831
832     //////////////////////////////////////////////////////////////////
833     // Select database
834     //
835     if (empty($DBParams['dbtype']))
836         $DBParams['dbtype'] = 'dba';
837
838     if (!defined('THEME'))
839         define('THEME', 'default');
840
841     /*$configurator_link = HTML(HTML::br(), "=>",
842                               HTML::a(array('href'=>DATA_PATH."/configurator.php"),
843                                       _("Configurator")));*/
844     // check whether the crypt() function is needed and present
845     if (defined('ENCRYPTED_PASSWD') && !function_exists('crypt')) {
846         $error = sprintf("Encrypted passwords cannot be used: %s.",
847             "'function crypt()' not available in this version of php");
848         trigger_error($error, E_USER_WARNING);
849         if (!preg_match("/config\-dist\.ini$/", $file)) { // protect against recursion
850             include_once(dirname(__FILE__) . "/install.php");
851             run_install("_part1");
852             exit();
853         }
854     }
855
856     // Basic configurator validation
857     if (!defined('ADMIN_USER') or ADMIN_USER == '') {
858         $error = sprintf("%s may not be empty. Please update your configuration.",
859             "ADMIN_USER");
860         // protect against recursion
861         if (!preg_match("/config\-(dist|default)\.ini$/", $file)
862             and !defined("_PHPWIKI_INSTALL_RUNNING")
863         ) {
864             include_once(dirname(__FILE__) . "/install.php");
865             run_install("_part1");
866             trigger_error($error, E_USER_ERROR);
867             exit();
868         } elseif ($HTTP_SERVER_VARS["REQUEST_METHOD"] == "POST") {
869             $GLOBALS['HTTP_GET_VARS']['show'] = '_part1';
870             trigger_error($error, E_USER_WARNING);
871         }
872     }
873     if (!defined('ADMIN_PASSWD') or ADMIN_PASSWD == '') {
874         $error = sprintf("%s may not be empty. Please update your configuration.",
875             "ADMIN_PASSWD");
876         // protect against recursion
877         if (!preg_match("/config\-(dist|default)\.ini$/", $file)
878             and !defined("_PHPWIKI_INSTALL_RUNNING")
879         ) {
880             include_once(dirname(__FILE__) . "/install.php");
881             run_install("_part1");
882             trigger_error($error, E_USER_ERROR);
883             exit();
884         } elseif ($HTTP_SERVER_VARS["REQUEST_METHOD"] == "POST") {
885             $GLOBALS['HTTP_GET_VARS']['show'] = '_part1';
886             trigger_error($error, E_USER_WARNING);
887         }
888     }
889
890     if (defined('USE_DB_SESSION') and USE_DB_SESSION) {
891         if (!$DBParams['db_session_table']) {
892             $DBParams['db_session_table'] = @$DBParams['prefix'] . 'session';
893             trigger_error(sprintf("DATABASE_SESSION_TABLE configuration set to %s.",
894                     $DBParams['db_session_table']),
895                 E_USER_ERROR);
896         }
897     }
898     // legacy:
899     if (!defined('ENABLE_USER_NEW')) define('ENABLE_USER_NEW', true);
900     if (!defined('ALLOW_USER_LOGIN'))
901         define('ALLOW_USER_LOGIN', defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
902     if (!defined('ALLOW_ANON_USER')) define('ALLOW_ANON_USER', true);
903     if (!defined('ALLOW_ANON_EDIT')) define('ALLOW_ANON_EDIT', false);
904     if (!defined('REQUIRE_SIGNIN_BEFORE_EDIT')) define('REQUIRE_SIGNIN_BEFORE_EDIT', !ALLOW_ANON_EDIT);
905     if (!defined('ALLOW_BOGO_LOGIN')) define('ALLOW_BOGO_LOGIN', true);
906     if (!ENABLE_USER_NEW) {
907         if (!defined('ALLOW_HTTP_AUTH_LOGIN'))
908             define('ALLOW_HTTP_AUTH_LOGIN', false);
909         if (!defined('ALLOW_LDAP_LOGIN'))
910             define('ALLOW_LDAP_LOGIN', function_exists('ldap_connect') and defined('LDAP_AUTH_HOST'));
911         if (!defined('ALLOW_IMAP_LOGIN'))
912             define('ALLOW_IMAP_LOGIN', function_exists('imap_open') and defined('IMAP_AUTH_HOST'));
913     }
914
915     if (ALLOW_USER_LOGIN and !empty($DBAuthParams) and empty($DBAuthParams['auth_dsn'])) {
916         if (isset($DBParams['dsn']))
917             $DBAuthParams['auth_dsn'] = $DBParams['dsn'];
918     }
919 }
920
921 /**
922  * Define constants which are client or request specific and should not be dumped statically.
923  * Such as the language, and the virtual and server paths, which might be overridden
924  * by startup scripts for wiki farms.
925  */
926 function fixup_dynamic_configs($file)
927 {
928     global $WikiNameRegexp;
929     global $HTTP_SERVER_VARS, $DBParams, $LANG;
930
931     if (defined('INCLUDE_PATH') and INCLUDE_PATH) {
932         @ini_set('include_path', INCLUDE_PATH);
933         $GLOBALS['INCLUDE_PATH'] = INCLUDE_PATH;
934     }
935     if (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH)
936         @ini_set('session.save_path', SESSION_SAVE_PATH);
937     if (!defined('DEFAULT_LANGUAGE')) // not needed anymore
938         define('DEFAULT_LANGUAGE', ''); // detect from client
939
940     // FusionForge hack
941     if (!FUSIONFORGE) {
942         // Disable update_locale because Zend Debugger crash
943         if (!extension_loaded('Zend Debugger')) {
944             update_locale(isset($LANG) ? $LANG : DEFAULT_LANGUAGE);
945         }
946     }
947
948     if (empty($LANG)) {
949         if (!defined("DEFAULT_LANGUAGE") or !DEFAULT_LANGUAGE) {
950             // TODO: defer this to WikiRequest::initializeLang()
951             $LANG = guessing_lang();
952             guessing_setlocale(LC_ALL, $LANG);
953         } else
954             $LANG = DEFAULT_LANGUAGE;
955     }
956
957     // Set up (possibly fake) gettext()
958     // Todo: this could be moved to fixup_static_configs()
959     // Bug #1381464 with php-5.1.1
960     if (!function_exists('bindtextdomain')
961         and !function_exists('gettext')
962             and !function_exists('_')
963     ) {
964         $locale = array();
965
966         function gettext($text)
967         {
968             global $locale;
969             if (!empty ($locale[$text]))
970                 return $locale[$text];
971             return $text;
972         }
973
974         function _($text)
975         {
976             return gettext($text);
977         }
978     } else {
979         $chback = 0;
980         if ($LANG != 'en') {
981
982             // Working around really weird gettext problems: (4.3.2, 4.3.6 win)
983             // bindtextdomain() in returns the current domain path.
984             // 1. If the script is not index.php but something like "de", on a different path
985             //    then bindtextdomain() fails, but after chdir to the correct path it will work okay.
986             // 2. But the weird error "Undefined variable: bindtextdomain" is generated then.
987             $bindtextdomain_path = FindFile("locale", false, true);
988             if (isWindows())
989                 $bindtextdomain_path = str_replace("/", "\\", $bindtextdomain_path);
990             $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain_path);
991             if (realpath($bindtextdomain_real) != realpath($bindtextdomain_path)) {
992                 // this will happen with virtual_paths. chdir and try again.
993                 chdir($bindtextdomain_path);
994                 $chback = 1;
995                 $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain_path);
996             }
997         }
998         // tell gettext not to use unicode. PHP >= 4.2.0. Thanks to Kai Krakow.
999         if (defined('CHARSET') and function_exists('bind_textdomain_codeset'))
1000             @bind_textdomain_codeset("phpwiki", CHARSET);
1001         if ($LANG != 'en')
1002             textdomain("phpwiki");
1003         if ($chback) { // change back
1004             chdir($bindtextdomain_real . (isWindows() ? "\\.." : "/.."));
1005         }
1006     }
1007
1008     // language dependent updates:
1009     if (!defined('CATEGORY_GROUP_PAGE'))
1010         define('CATEGORY_GROUP_PAGE', _("CategoryGroup"));
1011     if (!defined('WIKI_NAME'))
1012         define('WIKI_NAME', _("An unnamed PhpWiki"));
1013     if (!defined('HOME_PAGE'))
1014         define('HOME_PAGE', _("HomePage"));
1015
1016     //////////////////////////////////////////////////////////////////
1017     // Autodetect URL settings:
1018     //
1019     foreach (array('SERVER_NAME', 'SERVER_PORT') as $var) {
1020         //FIXME: for CGI without _SERVER
1021         if (!defined($var) and !empty($HTTP_SERVER_VARS[$var]))
1022             // IPV6 fix by matt brown, #1546571
1023             // An IPv6 address must be surrounded by square brackets to form a valid server name.
1024             if ($var == 'SERVER_NAME' &&
1025                 strstr($HTTP_SERVER_VARS[$var], ':')
1026             ) {
1027                 define($var, '[' . $HTTP_SERVER_VARS[$var] . ']');
1028             } else {
1029                 define($var, $HTTP_SERVER_VARS[$var]);
1030             }
1031     }
1032     if (!defined('SERVER_NAME')) define('SERVER_NAME', '127.0.0.1');
1033     if (!defined('SERVER_PORT')) define('SERVER_PORT', 80);
1034     if (!defined('SERVER_PROTOCOL')) {
1035         if (empty($HTTP_SERVER_VARS['HTTPS']) || $HTTP_SERVER_VARS['HTTPS'] == 'off')
1036             define('SERVER_PROTOCOL', 'http');
1037         else
1038             define('SERVER_PROTOCOL', 'https');
1039     }
1040
1041     if (!defined('SCRIPT_NAME'))
1042         define('SCRIPT_NAME', deduce_script_name());
1043
1044     if (!defined('USE_PATH_INFO')) {
1045         if (isCGI())
1046             define('USE_PATH_INFO', false);
1047         else {
1048             /*
1049              * If SCRIPT_NAME does not look like php source file,
1050              * or user cgi we assume that php is getting run by an
1051              * action handler in /cgi-bin.  In this case,
1052              * I think there is no way to get Apache to pass
1053              * useful PATH_INFO to the php script (PATH_INFO
1054              * is used to the the php interpreter where the
1055              * php script is...)
1056              */
1057             switch (php_sapi_name()) {
1058                 case 'apache':
1059                 case 'apache2handler':
1060                     define('USE_PATH_INFO', true);
1061                     break;
1062                 case 'cgi':
1063                 case 'apache2filter':
1064                     define('USE_PATH_INFO', false);
1065                     break;
1066                 default:
1067                     define('USE_PATH_INFO', ereg('\.(php3?|cgi)$', SCRIPT_NAME));
1068                     break;
1069             }
1070         }
1071     }
1072
1073     if (SERVER_PORT
1074         && SERVER_PORT != (SERVER_PROTOCOL == 'https' ? 443 : 80)
1075     ) {
1076         define('SERVER_URL',
1077             SERVER_PROTOCOL . '://' . SERVER_NAME . ':' . SERVER_PORT);
1078     } else {
1079         define('SERVER_URL',
1080             SERVER_PROTOCOL . '://' . SERVER_NAME);
1081     }
1082
1083     if (!defined('VIRTUAL_PATH')) {
1084         // We'd like to auto-detect when the cases where apaches
1085         // 'Action' directive (or similar means) is used to
1086         // redirect page requests to a cgi-handler.
1087         //
1088         // In cases like this, requests for e.g. /wiki/HomePage
1089         // get redirected to a cgi-script called, say,
1090         // /path/to/wiki/index.php.  The script gets all
1091         // of /wiki/HomePage as it's PATH_INFO.
1092         //
1093         // The problem is:
1094         //   How to detect when this has happened reliably?
1095         //   How to pick out the "virtual path" (in this case '/wiki')?
1096         //
1097         // (Another time an redirect might occur is to a DirectoryIndex
1098         // -- the requested URI is '/wikidir/', the request gets
1099         // passed to '/wikidir/index.php'.  In this case, the
1100         // proper VIRTUAL_PATH is '/wikidir/index.php', since the
1101         // pages will appear at e.g. '/wikidir/index.php/HomePage'.
1102         //
1103
1104         $REDIRECT_URL = &$HTTP_SERVER_VARS['REDIRECT_URL'];
1105         if (USE_PATH_INFO and isset($REDIRECT_URL)
1106             and !IsProbablyRedirectToIndex()
1107         ) {
1108             // FIXME: This is a hack, and won't work if the requested
1109             // pagename has a slash in it.
1110             $temp = strtr(dirname($REDIRECT_URL . 'x'), "\\", '/');
1111             if (($temp == '/') || ($temp == '\\'))
1112                 $temp = '';
1113             define('VIRTUAL_PATH', $temp);
1114         } else {
1115             define('VIRTUAL_PATH', SCRIPT_NAME);
1116         }
1117     }
1118
1119     if (!defined('PATH_INFO_PREFIX')) {
1120         if (VIRTUAL_PATH != SCRIPT_NAME) {
1121             // Apache action handlers are used.
1122             define('PATH_INFO_PREFIX', VIRTUAL_PATH . '/');
1123         } else {
1124             define('PATH_INFO_PREFIX', '/');
1125         }
1126     }
1127
1128     define('PHPWIKI_BASE_URL',
1129         SERVER_URL . (USE_PATH_INFO ? VIRTUAL_PATH . '/' : SCRIPT_NAME));
1130
1131     // Detect PrettyWiki setup (not loading index.php directly)
1132     // $SCRIPT_FILENAME should be the same as __FILE__ in index.php
1133     if (!isset($SCRIPT_FILENAME))
1134         $SCRIPT_FILENAME = @$HTTP_SERVER_VARS['SCRIPT_FILENAME'];
1135     if (!isset($SCRIPT_FILENAME))
1136         $SCRIPT_FILENAME = @$HTTP_ENV_VARS['SCRIPT_FILENAME'];
1137     if (!isset($SCRIPT_FILENAME))
1138         $SCRIPT_FILENAME = dirname(__FILE__ . '/../') . '/index.php';
1139     if (isWindows())
1140         $SCRIPT_FILENAME = str_replace('\\\\', '\\', strtr($SCRIPT_FILENAME, '/', '\\'));
1141     define('SCRIPT_FILENAME', $SCRIPT_FILENAME);
1142
1143     // Get remote host name, if Apache hasn't done it for us
1144     if (empty($HTTP_SERVER_VARS['REMOTE_HOST'])
1145         and !empty($HTTP_SERVER_VARS['REMOTE_ADDR'])
1146             and ENABLE_REVERSE_DNS
1147     )
1148         $HTTP_SERVER_VARS['REMOTE_HOST'] = gethostbyaddr($HTTP_SERVER_VARS['REMOTE_ADDR']);
1149
1150 }
1151
1152 // Local Variables:
1153 // mode: php
1154 // tab-width: 8
1155 // c-basic-offset: 4
1156 // c-hanging-comment-ender-p: nil
1157 // indent-tabs-mode: nil
1158 // End: