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