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