]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/IniConfig.php
Wiki page --> wiki page
[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         // try to load it dynamically (unix only)
328         if (!loadPhpExtension("pdo")) {
329             echo $GLOBALS['php_errormsg'], "<br>\n";
330             trigger_error(sprintf("dl() problem: Required extension “%s” could not be loaded!",
331                     "pdo"),
332                 E_USER_ERROR);
333         }
334     }
335     // Detect readonly database, e.g. system mounted read-only for maintenance
336     // via dbh->readonly later. Unfortunately not possible as constant.
337
338     // USE_DB_SESSION default logic:
339     if (!defined('USE_DB_SESSION')) {
340         if ($DBParams['db_session_table']
341             and in_array($DBParams['dbtype'], array('SQL', 'ADODB', 'PDO', 'dba'))
342         ) {
343             define('USE_DB_SESSION', true);
344         } else {
345             define('USE_DB_SESSION', false);
346         }
347     }
348     unset($item);
349     unset($k);
350
351     // Expiry stuff
352     global $ExpireParams;
353     foreach (array('major', 'minor', 'author') as $major) {
354         foreach (array('max_age', 'min_age', 'min_keep', 'keep', 'max_keep') as $max) {
355             $item = strtoupper($major) . '_' . strtoupper($max);
356             if (defined($item)) $val = constant($item);
357             elseif (array_key_exists($item, $rs))
358                 $val = $rs[$item]; elseif (array_key_exists($item, $rsdef))
359                 $val = $rsdef[$item];
360             if (!isset($ExpireParams[$major]))
361                 $ExpireParams[$major] = array();
362             $ExpireParams[$major][$max] = $val;
363             unset($rs[$item]);
364         }
365     }
366     unset($item);
367     unset($major);
368     unset($max);
369
370     // User authentication
371     if (!isset($GLOBALS['USER_AUTH_ORDER'])) {
372         if (isset($rs['USER_AUTH_ORDER']))
373             $GLOBALS['USER_AUTH_ORDER'] = preg_split('/\s*:\s*/',
374                 $rs['USER_AUTH_ORDER']);
375         else
376             $GLOBALS['USER_AUTH_ORDER'] = array("PersonalPage");
377     }
378
379     // Now it's the external DB authentication stuff's turn
380     if (in_array('Db', $GLOBALS['USER_AUTH_ORDER']) && empty($rs['DBAUTH_AUTH_DSN'])) {
381         $rs['DBAUTH_AUTH_DSN'] = $DBParams['dsn'];
382     }
383
384     global $DBAuthParams;
385     $DBAP_MAP = array('DBAUTH_AUTH_DSN' => 'auth_dsn',
386         'DBAUTH_AUTH_CHECK' => 'auth_check',
387         'DBAUTH_AUTH_USER_EXISTS' => 'auth_user_exists',
388         'DBAUTH_AUTH_CRYPT_METHOD' => 'auth_crypt_method',
389         'DBAUTH_AUTH_UPDATE' => 'auth_update',
390         'DBAUTH_AUTH_CREATE' => 'auth_create',
391         'DBAUTH_PREF_SELECT' => 'pref_select',
392         'DBAUTH_PREF_INSERT' => 'pref_insert',
393         'DBAUTH_PREF_UPDATE' => 'pref_update',
394         'DBAUTH_IS_MEMBER' => 'is_member',
395         'DBAUTH_GROUP_MEMBERS' => 'group_members',
396         'DBAUTH_USER_GROUPS' => 'user_groups'
397     );
398     foreach ($DBAP_MAP as $rskey => $apkey) {
399         if (defined($rskey)) {
400             $DBAuthParams[$apkey] = constant($rskey);
401         } elseif (isset($rs[$rskey])) {
402             $DBAuthParams[$apkey] = $rs[$rskey];
403             define($rskey, $rs[$rskey]);
404         } elseif (isset($rsdef[$rskey])) {
405             $DBAuthParams[$apkey] = $rsdef[$rskey];
406             define($rskey, $rsdef[$rskey]);
407         }
408         unset($rs[$rskey]);
409     }
410     unset($rskey);
411     unset($apkey);
412
413     // TODO: Currently unsupported on non-SQL. Nice to have for RhNavPlugin
414     // CHECKME: PDO
415     if (!defined('ACCESS_LOG_SQL')) {
416         if (array_key_exists('ACCESS_LOG_SQL', $rs)) {
417             // WikiDB_backend::isSql() not yet loaded
418             if (!in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO'))) {
419                 // override false config setting on no SQL WikiDB database.
420                 define('ACCESS_LOG_SQL', 0);
421             }
422             // SQL defaults to ACCESS_LOG_SQL = 2
423         } else {
424             define('ACCESS_LOG_SQL',
425             in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO')) ? 2 : 0);
426         }
427     }
428
429     global $PLUGIN_MARKUP_MAP;
430     $PLUGIN_MARKUP_MAP = array();
431     if (defined('PLUGIN_MARKUP_MAP') and trim(PLUGIN_MARKUP_MAP) != "") {
432         $_map = preg_split('/\s+/', PLUGIN_MARKUP_MAP);
433         foreach ($_map as $v) {
434             list($xml, $plugin) = explode(':', $v);
435             if (!empty($xml) and !empty($plugin))
436                 $PLUGIN_MARKUP_MAP[$xml] = $plugin;
437         }
438         unset($_map);
439         unset($xml);
440         unset($plugin);
441         unset($v);
442     }
443
444     if (empty($rs['TEMP_DIR'])) {
445         $rs['TEMP_DIR'] = "/tmp";
446         if (getenv("TEMP"))
447             $rs['TEMP_DIR'] = getenv("TEMP");
448     }
449     // optional values will be set to '' to simplify the logic.
450     foreach ($_IC_OPTIONAL_VALUE as $item) {
451         if (defined($item)) {
452             unset($rs[$item]);
453             continue;
454         }
455         if (array_key_exists($item, $rs)) {
456             _check_int_constant($rs[$item]);
457             define($item, $rs[$item]);
458             unset($rs[$item]);
459         } else
460             define($item, '');
461     }
462
463     if (USE_EXTERNAL_HTML2PDF) {
464         $item = 'EXTERNAL_HTML2PDF_PAGELIST';
465         if (defined($item)) {
466             unset($rs[$item]);
467         } elseif (array_key_exists($item, $rs)) {
468             define($item, $rs[$item]);
469             unset($rs[$item]);
470         } elseif (array_key_exists($item, $rsdef)) {
471             define($item, $rsdef[$item]);
472         }
473     }
474     unset($item);
475
476     // LDAP bind options
477     global $LDAP_SET_OPTION;
478     if (defined('LDAP_SET_OPTION') and LDAP_SET_OPTION) {
479         $optlist = preg_split('/\s*:\s*/', LDAP_SET_OPTION);
480         foreach ($optlist as $opt) {
481             $bits = preg_split('/\s*=\s*/', $opt, 2);
482             if (count($bits) == 2) {
483                 if (is_string($bits[0]) and defined($bits[0]))
484                     $bits[0] = constant($bits[0]);
485                 $LDAP_SET_OPTION[$bits[0]] = $bits[1];
486             } else {
487                 // Possibly throw some sort of error?
488             }
489         }
490         unset($opt);
491         unset($bits);
492     }
493
494     // Default Wiki pages to force loading from pgsrc
495     global $GenericPages;
496     $GenericPages = preg_split('/\s*:\s*/', @$rs['DEFAULT_WIKI_PAGES']);
497
498     // Wiki name regexp:  Should be a define(), but might needed to be changed at runtime
499     // (different LC_CHAR need different posix classes)
500     global $WikiNameRegexp;
501     $WikiNameRegexp = constant('WIKI_NAME_REGEXP');
502     if (!trim($WikiNameRegexp))
503         $WikiNameRegexp = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])';
504
505     // Got rid of global $KeywordLinkRegexp by using a TextSearchQuery instead
506     // of "Category:Topic"
507     if (!isset($rs['KEYWORDS'])) $rs['KEYWORDS'] = @$rsdef['KEYWORDS'];
508     if (!isset($rs['KEYWORDS'])) $rs['KEYWORDS'] = "Category* OR Topic*";
509     if ($rs['KEYWORDS'] == 'Category:Topic') $rs['KEYWORDS'] = "Category* OR Topic*";
510     if (!defined('KEYWORDS')) define('KEYWORDS', $rs['KEYWORDS']);
511     //if (empty($keywords)) $keywords = array("Category","Topic");
512     //$KeywordLinkRegexp = '(?<=' . implode('|^', $keywords) . ')[[:upper:]].*$';
513
514     // TODO: can this be a constant?
515     global $DisabledActions;
516     if (!array_key_exists('DISABLED_ACTIONS', $rs)
517         and array_key_exists('DISABLED_ACTIONS', $rsdef)
518     )
519         $rs['DISABLED_ACTIONS'] = @$rsdef['DISABLED_ACTIONS'];
520     if (array_key_exists('DISABLED_ACTIONS', $rs))
521         $DisabledActions = preg_split('/\s*:\s*/', $rs['DISABLED_ACTIONS']);
522
523     global $PLUGIN_CACHED_IMGTYPES;
524     $PLUGIN_CACHED_IMGTYPES = preg_split('/\s*[|:]\s*/', PLUGIN_CACHED_IMGTYPES);
525
526     if (!defined('PLUGIN_CACHED_CACHE_DIR')) {
527         if (empty($rs['PLUGIN_CACHED_CACHE_DIR']) and !empty($rsdef['PLUGIN_CACHED_CACHE_DIR']))
528             $rs['PLUGIN_CACHED_CACHE_DIR'] = $rsdef['PLUGIN_CACHED_CACHE_DIR'];
529         if (empty($rs['PLUGIN_CACHED_CACHE_DIR'])) {
530             if (!empty($rs['INCLUDE_PATH'])) {
531                 @ini_set('include_path', $rs['INCLUDE_PATH']);
532                 $GLOBALS['INCLUDE_PATH'] = $rs['INCLUDE_PATH'];
533             }
534             $rs['PLUGIN_CACHED_CACHE_DIR'] = TEMP_DIR . '/cache';
535             if (!FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], 1)) { // [29ms]
536                 FindFile(TEMP_DIR, false, 1); // TEMP must exist!
537                 mkdir($rs['PLUGIN_CACHED_CACHE_DIR'], 0777);
538             }
539             // will throw an error if not exists.
540             define('PLUGIN_CACHED_CACHE_DIR', FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], false, 1));
541         } else {
542             define('PLUGIN_CACHED_CACHE_DIR', $rs['PLUGIN_CACHED_CACHE_DIR']);
543             // will throw an error if not exists.
544             FindFile(PLUGIN_CACHED_CACHE_DIR);
545         }
546     }
547
548     // process the rest of the config.ini settings:
549     foreach ($rs as $item => $v) {
550         if (defined($item)) {
551             continue;
552         } else {
553             _check_int_constant($v);
554             define($item, $v);
555         }
556     }
557     unset($item);
558     unset($v);
559
560     unset($rs);
561     unset($rsdef);
562
563     fixup_static_configs($file); //[1ms]
564     // Dump all globals and constants
565     // The question is if reading this is faster then doing IniConfig() + fixup_static_configs()
566     if (is_writable($dump)) {
567         save_dump($dump);
568     }
569     // store locale[] in config.php? This is too problematic.
570     fixup_dynamic_configs(); // [100ms]
571 }
572
573 function _ignore_unknown_charset_warning(&$error)
574 {
575     //htmlspecialchars(): charset `iso-8859-2' not supported, assuming iso-8859-1
576     if (preg_match('/^htmlspecialchars\(\): charset \`.+\' not supported, assuming iso-8859-1/',
577         $error->errstr)
578     ) {
579         $error->errno = 0;
580         return true; // Ignore error
581     }
582     return false;
583 }
584
585 // moved from lib/config.php [1ms]
586 function fixup_static_configs($file)
587 {
588     global $FieldSeparator, $charset, $WikiNameRegexp, $AllActionPages;
589     global $DBParams, $LANG, $ErrorManager;
590     // init FileFinder to add proper include paths
591     FindFile("lib/interwiki.map", true);
592
593     // "\x80"-"\x9f" (and "\x00" - "\x1f") are non-printing control
594     // chars in iso-8859-*
595     // $FieldSeparator = "\263"; // this is a superscript 3 in ISO-8859-1.
596     // $FieldSeparator = "\xFF"; // this byte should never appear in utf-8
597     // Get rid of constant. pref is dynamic and language specific
598     $charset = CHARSET;
599     // Disabled: Let the admin decide which charset.
600     //if (isset($LANG) and in_array($LANG,array('zh')))
601     //    $charset = 'utf-8';
602     if (strtolower($charset) == 'utf-8')
603         $FieldSeparator = "\xFF";
604     else
605         $FieldSeparator = "\x81";
606
607     // Some exotic charsets are not supported by htmlspecialchars, which just prints an E_WARNING.
608     // Even on simple 8bit charsets, where just <>& need to be replaced. For iso-8859-[2-4] e.g.
609     // See <php-src>/ext/standard/html.c
610     // For performance reasons we require a magic constant to ignore this warning.
611     if (defined('IGNORE_CHARSET_NOT_SUPPORTED_WARNING')
612         and IGNORE_CHARSET_NOT_SUPPORTED_WARNING
613     ) {
614         $ErrorManager->pushErrorHandler
615         (new WikiFunctionCb('_ignore_unknown_charset_warning'));
616     }
617
618     // All pages containing plugins of the same name as the filename
619     $ActionPages = explode(':',
620         'AllPages:AllUsers:AppendText:AuthorHistory:'
621             . 'BackLinks:'
622             . 'CreatePage:'
623             . 'FullTextSearch:FuzzyPages:'
624             . 'LikePages:LinkDatabase:LinkSearch:ListRelations:'
625             . 'ModeratedPage:MostPopular:'
626             . 'NewPagesPerUser:'
627             . 'OrphanedPages:'
628             . 'PageDump:PageHistory:PageInfo:PluginManager:'
629             . 'RateIt:' // RateIt works only in wikilens derived themes
630             . 'RandomPage:RecentChanges:RelatedChanges:RecentEdits:'
631             . 'SearchHighlight:SemanticRelations:SemanticSearch:SystemInfo:'
632             . 'TitleSearch:'
633             . 'UpLoad:UserPreferences:'
634             . 'UserRatings:' // UserRatings works only in wikilens derived themes
635             . 'WantedPages:WatchPage:WhoIsOnline:WikiAdminSelect');
636
637     // The FUSIONFORGE theme omits them
638     if (!(defined('FUSIONFORGE') and FUSIONFORGE)) {
639         // Add some some action pages depending on configuration
640         if (DEBUG) {
641             $ActionPages[] = 'DebugInfo';
642             $ActionPages[] = 'SpellCheck'; // SpellCheck does not work
643         }
644         $ActionPages[] = 'BlogArchives';
645         $ActionPages[] = 'BlogJournal';
646         $ActionPages[] = 'EditMetaData';
647         $ActionPages[] = 'InterWikiSearch';
648         $ActionPages[] = 'LdapSearch';
649         $ActionPages[] = 'PasswordReset';
650         $ActionPages[] = 'RecentComments';
651         $ActionPages[] = 'TranslateText';
652         $ActionPages[] = 'UriResolver';
653         $ActionPages[] = 'WikiBlog';
654     }
655
656     global $AllAllowedPlugins;
657     $AllAllowedPlugins = $ActionPages;
658     // Add plugins that have no corresponding action page
659     $AllAllowedPlugins[] = 'AddComment';
660     $AllAllowedPlugins[] = 'AsciiMath';
661     $AllAllowedPlugins[] = 'AsciiSVG';
662     $AllAllowedPlugins[] = 'AtomFeed';
663     $AllAllowedPlugins[] = 'BoxRight';
664     $AllAllowedPlugins[] = 'CalendarList';
665     $AllAllowedPlugins[] = 'Calendar';
666     $AllAllowedPlugins[] = 'CategoryPage';
667     $AllAllowedPlugins[] = 'Chart';
668     $AllAllowedPlugins[] = 'Comment';
669     $AllAllowedPlugins[] = 'CreateBib';
670     $AllAllowedPlugins[] = 'CreateToc';
671     $AllAllowedPlugins[] = 'CurrentTime';
672     $AllAllowedPlugins[] = 'DeadEndPages';
673     $AllAllowedPlugins[] = 'Diff';
674     $AllAllowedPlugins[] = 'DynamicIncludePage';
675     $AllAllowedPlugins[] = 'ExternalSearch';
676     $AllAllowedPlugins[] = 'FacebookLike';
677     $AllAllowedPlugins[] = 'FileInfo';
678     $AllAllowedPlugins[] = 'GoogleMaps';
679     $AllAllowedPlugins[] = 'GooglePlugin';
680     $AllAllowedPlugins[] = 'GoTo';
681     $AllAllowedPlugins[] = 'HelloWorld';
682     $AllAllowedPlugins[] = 'IncludePage';
683     $AllAllowedPlugins[] = 'IncludePages';
684     $AllAllowedPlugins[] = 'IncludeSiteMap';
685     $AllAllowedPlugins[] = 'IncludeTree';
686     $AllAllowedPlugins[] = 'ListPages';
687     $AllAllowedPlugins[] = 'ListSubpages';
688     $AllAllowedPlugins[] = 'MediawikiTable';
689     $AllAllowedPlugins[] = 'NoCache';
690     $AllAllowedPlugins[] = 'OldStyleTable';
691     $AllAllowedPlugins[] = 'PageGroup';
692     $AllAllowedPlugins[] = 'PageTrail';
693     $AllAllowedPlugins[] = 'PhotoAlbum';
694     $AllAllowedPlugins[] = 'PhpHighlight';
695     $AllAllowedPlugins[] = 'PopularTags';
696     $AllAllowedPlugins[] = 'PopUp';
697     $AllAllowedPlugins[] = 'PrevNext';
698     $AllAllowedPlugins[] = 'Processing';
699     $AllAllowedPlugins[] = 'RawHtml';
700     $AllAllowedPlugins[] = 'RecentChangesCached';
701     $AllAllowedPlugins[] = 'RecentReferrers';
702     $AllAllowedPlugins[] = 'RedirectTo';
703     $AllAllowedPlugins[] = 'RichTable';
704     $AllAllowedPlugins[] = 'RssFeed';
705     $AllAllowedPlugins[] = 'SemanticSearchAdvanced';
706     $AllAllowedPlugins[] = 'SiteMap';
707     $AllAllowedPlugins[] = 'SyncWiki';
708     $AllAllowedPlugins[] = 'SyntaxHighlighter';
709     $AllAllowedPlugins[] = 'Template';
710     $AllAllowedPlugins[] = 'Transclude';
711     $AllAllowedPlugins[] = 'UnfoldSubpages';
712     $AllAllowedPlugins[] = 'Video';
713     $AllAllowedPlugins[] = 'WikiAdminChown';
714     $AllAllowedPlugins[] = 'WikiAdminPurge';
715     $AllAllowedPlugins[] = 'WikiAdminRemove';
716     $AllAllowedPlugins[] = 'WikiAdminRename';
717     $AllAllowedPlugins[] = 'WikiAdminSearchReplace';
718     $AllAllowedPlugins[] = 'WikiAdminDeleteAcl';
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 (!(defined('FUSIONFORGE') and FUSIONFORGE)) {
730         $AllAllowedPlugins[] = 'AnalyseAccessLogSql';
731         $AllAllowedPlugins[] = '_AuthInfo';
732         $AllAllowedPlugins[] = '_BackendInfo';
733         $AllAllowedPlugins[] = 'CacheTest';
734         $AllAllowedPlugins[] = 'CategoryPage';
735         $AllAllowedPlugins[] = 'FoafViewer';
736         $AllAllowedPlugins[] = 'FrameInclude';
737         $AllAllowedPlugins[] = 'GraphViz';
738         $AllAllowedPlugins[] = '_GroupInfo';
739         $AllAllowedPlugins[] = 'HtmlConverter';
740         $AllAllowedPlugins[] = 'Imdb';
741         $AllAllowedPlugins[] = 'JabberPresence';
742         $AllAllowedPlugins[] = 'ListPages';
743         $AllAllowedPlugins[] = 'PhpWeather';
744         $AllAllowedPlugins[] = 'Ploticus';
745         $AllAllowedPlugins[] = 'PopularNearby';
746         $AllAllowedPlugins[] = 'PreferenceApp';
747         $AllAllowedPlugins[] = '_PreferencesInfo';
748         $AllAllowedPlugins[] = '_Retransform';
749         $AllAllowedPlugins[] = 'SqlResult';
750         $AllAllowedPlugins[] = 'TeX2png';
751         $AllAllowedPlugins[] = 'text2png';
752         $AllAllowedPlugins[] = 'TexToPng';
753         $AllAllowedPlugins[] = 'VisualWiki';
754         $AllAllowedPlugins[] = 'WantedPagesOld';
755         $AllAllowedPlugins[] = 'WikiAdminChmod';
756         $AllAllowedPlugins[] = 'WikiAdminMarkup';
757         $AllAllowedPlugins[] = 'WikiForum';
758         $AllAllowedPlugins[] = '_WikiTranslation';
759     }
760
761     // Used by SetupWiki to pull in required pages, if not translated, then in English.
762     // Also used by _WikiTranslation. Really important are only those which return pagelists
763     // or contain basic functionality.
764     $AllActionPages = $ActionPages;
765     $AllActionPages[] = 'AllPagesCreatedByMe';
766     $AllActionPages[] = 'AllPagesLastEditedByMe';
767     $AllActionPages[] = 'AllPagesOwnedByMe';
768     $AllActionPages[] = 'AllPagesByAcl';
769     $AllActionPages[] = 'AllUserPages';
770     $AllActionPages[] = 'FullRecentChanges';
771     $AllActionPages[] = 'LeastPopular';
772     $AllActionPages[] = 'LockedPages';
773     $AllActionPages[] = 'MyRatings'; // MyRatings works only in wikilens-derived themes
774     $AllActionPages[] = 'MyRecentEdits';
775     $AllActionPages[] = 'MyRecentChanges';
776     $AllActionPages[] = 'PhpWikiAdministration';
777     $AllActionPages[] = 'PhpWikiAdministration/Chown';
778     $AllActionPages[] = 'PhpWikiAdministration/Purge';
779     $AllActionPages[] = 'PhpWikiAdministration/Remove';
780     $AllActionPages[] = 'PhpWikiAdministration/Rename';
781     $AllActionPages[] = 'PhpWikiAdministration/SearchReplace';
782     $AllActionPages[] = 'PhpWikiAdministration/DeleteAcl';
783     $AllActionPages[] = 'PhpWikiAdministration/SetAcl';
784     $AllActionPages[] = 'PhpWikiAdministration/SetAclSimple';
785     $AllActionPages[] = 'RecentChangesMyPages';
786     $AllActionPages[] = 'RecentEdits';
787     $AllActionPages[] = 'RecentNewPages';
788     $AllActionPages[] = 'SetGlobalAccessRights';
789     $AllActionPages[] = 'SetGlobalAccessRightsSimple';
790     $AllActionPages[] = 'UserContribs';
791
792     // The FUSIONFORGE theme omits them
793     if (!(defined('FUSIONFORGE') and FUSIONFORGE)) {
794         // Add some some action pages depending on configuration
795         if (DEBUG) {
796             $AllActionPages[] = 'PhpWikiAdministration/Chmod';
797         }
798         $AllActionPages[] = 'PhpWikiAdministration/Markup';
799     }
800
801     if ((defined('FUSIONFORGE') and FUSIONFORGE)) {
802         if (ENABLE_EXTERNAL_PAGES) {
803             $AllAllowedPlugins[] = 'WikiAdminSetExternal';
804             $AllActionPages[] = 'PhpWikiAdministration/SetExternal';
805             $AllActionPages[] = 'ExternalPages';
806         }
807     }
808
809     // If user has not defined PHPWIKI_DIR, and we need it
810     if (!defined('PHPWIKI_DIR') and !file_exists("themes/default")) {
811         $themes_dir = FindFile("themes");
812         define('PHPWIKI_DIR', dirname($themes_dir));
813     }
814
815     // If user has not defined DATA_PATH, we want to use relative URLs.
816     if (!defined('DATA_PATH')) {
817         // fix similar to the one suggested by jkalmbach for
818         // installations in the webrootdir, like "http://phpwiki.org/HomePage"
819         if (!defined('SCRIPT_NAME'))
820             define('SCRIPT_NAME', deduce_script_name());
821         $temp = dirname(SCRIPT_NAME);
822         if (($temp == '/') || ($temp == '\\'))
823             $temp = '';
824         define('DATA_PATH', $temp);
825         /*
826         if (USE_PATH_INFO)
827             define('DATA_PATH', '..');
828         */
829     }
830
831     //////////////////////////////////////////////////////////////////
832     // Select database
833     //
834     if (empty($DBParams['dbtype']))
835         $DBParams['dbtype'] = 'dba';
836
837     if (!defined('THEME'))
838         define('THEME', 'default');
839
840     /*$configurator_link = HTML(HTML::br(), "=>",
841                               HTML::a(array('href'=>DATA_PATH."/configurator.php"),
842                                       _("Configurator")));*/
843     // check whether the crypt() function is needed and present
844     if (defined('ENCRYPTED_PASSWD') && !function_exists('crypt')) {
845         $error = sprintf("Encrypted passwords cannot be used: %s.",
846             "'function crypt()' not available in this version of php");
847         trigger_error($error, E_USER_WARNING);
848         if (!preg_match("/config\-dist\.ini$/", $file)) { // protect against recursion
849             include_once(dirname(__FILE__) . "/install.php");
850             run_install("_part1");
851             exit();
852         }
853     }
854
855     // Basic configurator validation
856     if (!defined('ADMIN_USER') or ADMIN_USER == '') {
857         $error = sprintf("%s may not be empty. Please update your configuration.",
858             "ADMIN_USER");
859         // protect against recursion
860         if (!preg_match("/config\-(dist|default)\.ini$/", $file)
861             and !defined("_PHPWIKI_INSTALL_RUNNING")
862         ) {
863             include_once(dirname(__FILE__) . "/install.php");
864             run_install("_part1");
865             trigger_error($error, E_USER_ERROR);
866             exit();
867         } elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
868             $GLOBALS['HTTP_GET_VARS']['show'] = '_part1';
869             trigger_error($error, E_USER_WARNING);
870         }
871     }
872     if (!defined('ADMIN_PASSWD') or ADMIN_PASSWD == '') {
873         $error = sprintf("%s may not be empty. Please update your configuration.",
874             "ADMIN_PASSWD");
875         // protect against recursion
876         if (!preg_match("/config\-(dist|default)\.ini$/", $file)
877             and !defined("_PHPWIKI_INSTALL_RUNNING")
878         ) {
879             include_once(dirname(__FILE__) . "/install.php");
880             run_install("_part1");
881             trigger_error($error, E_USER_ERROR);
882             exit();
883         } elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
884             $GLOBALS['HTTP_GET_VARS']['show'] = '_part1';
885             trigger_error($error, E_USER_WARNING);
886         }
887     }
888
889     if (defined('USE_DB_SESSION') and USE_DB_SESSION) {
890         if (!$DBParams['db_session_table']) {
891             $DBParams['db_session_table'] = @$DBParams['prefix'] . 'session';
892             trigger_error(sprintf("DATABASE_SESSION_TABLE configuration set to %s.",
893                     $DBParams['db_session_table']),
894                 E_USER_ERROR);
895         }
896     }
897     // legacy:
898     if (!defined('ENABLE_USER_NEW')) define('ENABLE_USER_NEW', true);
899     if (!defined('ALLOW_USER_LOGIN'))
900         define('ALLOW_USER_LOGIN', defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
901     if (!defined('ALLOW_ANON_USER')) define('ALLOW_ANON_USER', true);
902     if (!defined('ALLOW_ANON_EDIT')) define('ALLOW_ANON_EDIT', false);
903     if (!defined('REQUIRE_SIGNIN_BEFORE_EDIT')) define('REQUIRE_SIGNIN_BEFORE_EDIT', !ALLOW_ANON_EDIT);
904     if (!defined('ALLOW_BOGO_LOGIN')) define('ALLOW_BOGO_LOGIN', true);
905     if (!ENABLE_USER_NEW) {
906         if (!defined('ALLOW_HTTP_AUTH_LOGIN'))
907             define('ALLOW_HTTP_AUTH_LOGIN', false);
908         if (!defined('ALLOW_LDAP_LOGIN'))
909             define('ALLOW_LDAP_LOGIN', function_exists('ldap_connect') and defined('LDAP_AUTH_HOST'));
910         if (!defined('ALLOW_IMAP_LOGIN'))
911             define('ALLOW_IMAP_LOGIN', function_exists('imap_open') and defined('IMAP_AUTH_HOST'));
912     }
913
914     if (ALLOW_USER_LOGIN and !empty($DBAuthParams) and empty($DBAuthParams['auth_dsn'])) {
915         if (isset($DBParams['dsn']))
916             $DBAuthParams['auth_dsn'] = $DBParams['dsn'];
917     }
918 }
919
920 /**
921  * Define constants which are client or request specific and should not be dumped statically.
922  * Such as the language, and the virtual and server paths, which might be overridden
923  * by startup scripts for wiki farms.
924  */
925 function fixup_dynamic_configs()
926 {
927     global $WikiNameRegexp;
928     global $DBParams, $LANG;
929
930     if (defined('INCLUDE_PATH') and INCLUDE_PATH) {
931         @ini_set('include_path', INCLUDE_PATH);
932         $GLOBALS['INCLUDE_PATH'] = INCLUDE_PATH;
933     }
934     if (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH)
935         @ini_set('session.save_path', SESSION_SAVE_PATH);
936     if (!defined('DEFAULT_LANGUAGE')) // not needed anymore
937         define('DEFAULT_LANGUAGE', ''); // detect from client
938
939     // FusionForge hack
940     if (!(defined('FUSIONFORGE') and FUSIONFORGE)) {
941         // Disable update_locale because Zend Debugger crash
942         if (!extension_loaded('Zend Debugger')) {
943             update_locale(isset($LANG) ? $LANG : DEFAULT_LANGUAGE);
944         }
945     }
946
947     if (empty($LANG)) {
948         if (!defined("DEFAULT_LANGUAGE") or !DEFAULT_LANGUAGE) {
949             // TODO: defer this to WikiRequest::initializeLang()
950             $LANG = guessing_lang();
951             guessing_setlocale(LC_ALL, $LANG);
952         } else
953             $LANG = DEFAULT_LANGUAGE;
954     }
955
956     // Set up (possibly fake) gettext()
957     // Todo: this could be moved to fixup_static_configs()
958     // Bug #1381464 with php-5.1.1
959     if (!function_exists('bindtextdomain')
960         and !function_exists('gettext')
961             and !function_exists('_')
962     ) {
963         $locale = array();
964
965         function gettext($text)
966         {
967             global $locale;
968             if (!empty ($locale[$text]))
969                 return $locale[$text];
970             return $text;
971         }
972
973         function _($text)
974         {
975             return gettext($text);
976         }
977     } else {
978         $chback = 0;
979         if ($LANG != 'en') {
980
981             // Working around really weird gettext problems: (4.3.2, 4.3.6 win)
982             // bindtextdomain() in returns the current domain path.
983             // 1. If the script is not index.php but something like "de", on a different path
984             //    then bindtextdomain() fails, but after chdir to the correct path it will work okay.
985             // 2. But the weird error "Undefined variable: bindtextdomain" is generated then.
986             $bindtextdomain_path = FindFile("locale", false, true);
987             if (isWindows())
988                 $bindtextdomain_path = str_replace("/", "\\", $bindtextdomain_path);
989             $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain_path);
990             if (realpath($bindtextdomain_real) != realpath($bindtextdomain_path)) {
991                 // this will happen with virtual_paths. chdir and try again.
992                 chdir($bindtextdomain_path);
993                 $chback = 1;
994                 $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain_path);
995             }
996         }
997         // tell gettext not to use unicode. PHP >= 4.2.0. Thanks to Kai Krakow.
998         if (defined('CHARSET') and function_exists('bind_textdomain_codeset'))
999             @bind_textdomain_codeset("phpwiki", CHARSET);
1000         if ($LANG != 'en')
1001             textdomain("phpwiki");
1002         if ($chback) { // change back
1003             chdir($bindtextdomain_real . (isWindows() ? "\\.." : "/.."));
1004         }
1005     }
1006
1007     // language dependent updates:
1008     if (!defined('CATEGORY_GROUP_PAGE'))
1009         define('CATEGORY_GROUP_PAGE', _("CategoryGroup"));
1010     if (!defined('WIKI_NAME'))
1011         define('WIKI_NAME', _("An unnamed PhpWiki"));
1012     if (!defined('HOME_PAGE'))
1013         define('HOME_PAGE', __("HomePage"));
1014
1015     //////////////////////////////////////////////////////////////////
1016     // Autodetect URL settings:
1017     //
1018     foreach (array('SERVER_NAME', 'SERVER_PORT') as $var) {
1019         //FIXME: for CGI without _SERVER
1020         if (!defined($var) and !empty($_SERVER[$var]))
1021             // IPV6 fix by matt brown, #1546571
1022             // An IPv6 address must be surrounded by square brackets to form a valid server name.
1023             if ($var == 'SERVER_NAME' &&
1024                 strstr($_SERVER[$var], ':')
1025             ) {
1026                 define($var, '[' . $_SERVER[$var] . ']');
1027             } else {
1028                 define($var, $_SERVER[$var]);
1029             }
1030     }
1031     if (!defined('SERVER_NAME')) define('SERVER_NAME', '127.0.0.1');
1032     if (!defined('SERVER_PORT')) define('SERVER_PORT', 80);
1033     if (!defined('SERVER_PROTOCOL')) {
1034         if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off')
1035             define('SERVER_PROTOCOL', 'http');
1036         else
1037             define('SERVER_PROTOCOL', 'https');
1038     }
1039
1040     if (!defined('SCRIPT_NAME'))
1041         define('SCRIPT_NAME', deduce_script_name());
1042
1043     if (!defined('USE_PATH_INFO')) {
1044         if (isCGI())
1045             define('USE_PATH_INFO', false);
1046         else {
1047             /*
1048              * If SCRIPT_NAME does not look like php source file,
1049              * or user cgi we assume that php is getting run by an
1050              * action handler in /cgi-bin.  In this case,
1051              * I think there is no way to get Apache to pass
1052              * useful PATH_INFO to the php script (PATH_INFO
1053              * is used to the the php interpreter where the
1054              * php script is...)
1055              */
1056             switch (php_sapi_name()) {
1057                 case 'apache':
1058                 case 'apache2handler':
1059                     define('USE_PATH_INFO', true);
1060                     break;
1061                 case 'cgi':
1062                 case 'apache2filter':
1063                     define('USE_PATH_INFO', false);
1064                     break;
1065                 default:
1066                     define('USE_PATH_INFO', ereg('\.(php3?|cgi)$', SCRIPT_NAME));
1067                     break;
1068             }
1069         }
1070     }
1071
1072     if (SERVER_PORT
1073         && SERVER_PORT != (SERVER_PROTOCOL == 'https' ? 443 : 80)
1074     ) {
1075         define('SERVER_URL',
1076             SERVER_PROTOCOL . '://' . SERVER_NAME . ':' . SERVER_PORT);
1077     } else {
1078         define('SERVER_URL',
1079             SERVER_PROTOCOL . '://' . SERVER_NAME);
1080     }
1081
1082     if (!defined('VIRTUAL_PATH')) {
1083         // We'd like to auto-detect when the cases where apaches
1084         // 'Action' directive (or similar means) is used to
1085         // redirect page requests to a cgi-handler.
1086         //
1087         // In cases like this, requests for e.g. /wiki/HomePage
1088         // get redirected to a cgi-script called, say,
1089         // /path/to/wiki/index.php.  The script gets all
1090         // of /wiki/HomePage as it's PATH_INFO.
1091         //
1092         // The problem is:
1093         //   How to detect when this has happened reliably?
1094         //   How to pick out the "virtual path" (in this case '/wiki')?
1095         //
1096         // (Another time an redirect might occur is to a DirectoryIndex
1097         // -- the requested URI is '/wikidir/', the request gets
1098         // passed to '/wikidir/index.php'.  In this case, the
1099         // proper VIRTUAL_PATH is '/wikidir/index.php', since the
1100         // pages will appear at e.g. '/wikidir/index.php/HomePage'.
1101         //
1102
1103         $REDIRECT_URL = &$_SERVER['REDIRECT_URL'];
1104         if (USE_PATH_INFO and isset($REDIRECT_URL)
1105             and !IsProbablyRedirectToIndex()
1106         ) {
1107             // FIXME: This is a hack, and won't work if the requested
1108             // pagename has a slash in it.
1109             $temp = strtr(dirname($REDIRECT_URL . 'x'), "\\", '/');
1110             if (($temp == '/') || ($temp == '\\'))
1111                 $temp = '';
1112             define('VIRTUAL_PATH', $temp);
1113         } else {
1114             define('VIRTUAL_PATH', SCRIPT_NAME);
1115         }
1116     }
1117
1118     if (!defined('PATH_INFO_PREFIX')) {
1119         if (VIRTUAL_PATH != SCRIPT_NAME) {
1120             // Apache action handlers are used.
1121             define('PATH_INFO_PREFIX', VIRTUAL_PATH . '/');
1122         } else {
1123             define('PATH_INFO_PREFIX', '/');
1124         }
1125     }
1126
1127     define('PHPWIKI_BASE_URL',
1128         SERVER_URL . (USE_PATH_INFO ? VIRTUAL_PATH . '/' : SCRIPT_NAME));
1129
1130     // Detect PrettyWiki setup (not loading index.php directly)
1131     // $SCRIPT_FILENAME should be the same as __FILE__ in index.php
1132     if (!isset($SCRIPT_FILENAME))
1133         $SCRIPT_FILENAME = @$_SERVER['SCRIPT_FILENAME'];
1134     if (!isset($SCRIPT_FILENAME))
1135         $SCRIPT_FILENAME = @$_ENV['SCRIPT_FILENAME'];
1136     if (!isset($SCRIPT_FILENAME))
1137         $SCRIPT_FILENAME = dirname(__FILE__ . '/../') . '/index.php';
1138     if (isWindows())
1139         $SCRIPT_FILENAME = str_replace('\\\\', '\\', strtr($SCRIPT_FILENAME, '/', '\\'));
1140     define('SCRIPT_FILENAME', $SCRIPT_FILENAME);
1141
1142     // Get remote host name, if Apache hasn't done it for us
1143     if (empty($_SERVER['REMOTE_HOST'])
1144         and !empty($_SERVER['REMOTE_ADDR'])
1145             and ENABLE_REVERSE_DNS
1146     )
1147         $_SERVER['REMOTE_HOST'] = gethostbyaddr($_SERVER['REMOTE_ADDR']);
1148
1149 }
1150
1151 /*
1152  * We have to handle three languages:
1153  * 1) English, the language of the source code
1154  * 2) The language in which the wiki was created (DEFAULT_LANGUAGE)
1155  * 3) The language selected by the user, in which the wiki is displayed (LANG)
1156  *
1157  * The function "_" translates from English to LANG.
1158  * The function "__" translates from English to DEFAULT_LANGUAGE.
1159  */
1160
1161 function __($text)
1162 {
1163     return $text;
1164 }
1165
1166 // Local Variables:
1167 // mode: php
1168 // tab-width: 8
1169 // c-basic-offset: 4
1170 // c-hanging-comment-ender-p: nil
1171 // indent-tabs-mode: nil
1172 // End: