]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/IniConfig.php
Include some action pages only if DEBUG is true
[SourceForge/phpwiki.git] / lib / IniConfig.php
1 <?php
2 rcs_id('$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 it's
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  *
18  * This file is part of PhpWiki.
19  *
20  * PhpWiki is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 2 of the License, or
23  * (at your option) any later version.
24  * 
25  * PhpWiki is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28  * GNU General Public License for more details.
29  * 
30  * You should have received a copy of the GNU General Public License
31  * along with PhpWiki; if not, write to the Free Software
32  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
33  */
34
35 /**
36  * DONE:
37  * - Convert the value lists to provide defaults, so that every "if
38  *      (defined())" and "if (!defined())" can fuck off to the dismal hole
39  *      it belongs in.
40  * - config.ini => config.php dumper for faster startup. (really faster? to time)
41  *
42  * TODO:
43  * - Old-style index.php => config/config.ini converter.
44  *
45  * - Don't use too much globals for easier integration into other projects
46  *   (namespace pollution). (gforge, phpnuke, postnuke, phpBB2, carolina, ...)
47  *   Use one global $phpwiki object instead which holds the cfg vars, constants 
48  *   and all other globals.
49  *     (global $FieldSeparator, $charset, $WikiNameRegexp, $KeywordLinkRegexp;
50  *      global $DisabledActions, $DBParams, $LANG, $AllActionPages)
51  *
52  * - Resurrect the larger "config object" code (in config/) so it'll aid the
53  *   GUI config writers, and allow us to do proper validation and default
54  *   value handling.
55  *
56  * - Get rid of WikiNameRegexp and KeywordLinkRegexp as globals by finding
57  *   everywhere that uses them as variables and modify the code to use
58  *   them as constants. Will involve hacking around
59  *   pcre_fix_posix_classes (probably with redefines()).
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",'RCS_IDS','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     // 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 sort_file_mtime($dump, $file) < 0) {
116         @include($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         include_once(dirname(__FILE__)."/install.php");
129         run_install("_part1");
130         if (!defined("_PHPWIKI_INSTALL_RUNNING"))
131             trigger_error("Datasource file '$file' does not exist", E_USER_ERROR);
132         exit();
133     }
134
135     // List of all valid config options to be define()d which take "values" (not
136     // booleans). Needs to be categorised, and generally made a lot tidier. 
137     $_IC_VALID_VALUE = array
138         ('WIKI_NAME', 'ADMIN_USER', 'ADMIN_PASSWD',
139          'DEFAULT_DUMP_DIR', 'HTML_DUMP_DIR',
140          'HTML_DUMP_SUFFIX', 'MAX_UPLOAD_SIZE', 'MINOR_EDIT_TIMEOUT',
141          'ACCESS_LOG', 'CACHE_CONTROL', 'CACHE_CONTROL_MAX_AGE',
142          'COOKIE_EXPIRATION_DAYS', 'COOKIE_DOMAIN',
143          'PASSWORD_LENGTH_MINIMUM', 'USER_AUTH_POLICY', 
144          'GROUP_METHOD',
145          'EDITING_POLICY', 'THEME', 'CHARSET',
146          'WIKI_PGSRC', 'DEFAULT_WIKI_PGSRC',
147          'ALLOWED_PROTOCOLS', 'INLINE_IMAGES', 'SUBPAGE_SEPARATOR', /*'KEYWORDS',*/
148          // extra logic:
149          //'DATABASE_PREFIX', 'DATABASE_DSN', 'DATABASE_TYPE', 'DATABASE_DBHANDLER',
150          'DATABASE_OPTIMISE_FREQUENCY',
151          'INTERWIKI_MAP_FILE', 'COPYRIGHTPAGE_TITLE', 'COPYRIGHTPAGE_URL',
152          'AUTHORPAGE_TITLE', 'AUTHORPAGE_URL', 
153          'WIKI_NAME_REGEXP',
154          'PLUGIN_CACHED_DATABASE', 'PLUGIN_CACHED_FILENAME_PREFIX',
155          'PLUGIN_CACHED_HIGHWATER', 'PLUGIN_CACHED_LOWWATER', 'PLUGIN_CACHED_MAXLIFETIME',
156          'PLUGIN_CACHED_MAXARGLEN', 'PLUGIN_CACHED_IMGTYPES',
157          'WYSIWYG_BACKEND', 'PLUGIN_MARKUP_MAP',
158          // extra logic:
159          'SERVER_NAME','SERVER_PORT','SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH',
160          'EXTERNAL_HTML2PDF_PAGELIST', 'PLUGIN_CACHED_CACHE_DIR'
161          );
162
163     // Optional values which need to be defined.
164     // These are not defined in config-default.ini and empty if not defined.
165     $_IC_OPTIONAL_VALUE = array
166         ( 
167          'DEBUG', 'TEMP_DIR', 'DEFAULT_LANGUAGE', 
168          'LDAP_AUTH_HOST','LDAP_SET_OPTION','LDAP_BASE_DN', 'LDAP_AUTH_USER',
169          'LDAP_AUTH_PASSWORD','LDAP_SEARCH_FIELD','LDAP_OU_GROUP','LDAP_OU_USERS',
170          'AUTH_USER_FILE','DBAUTH_AUTH_DSN',
171          'IMAP_AUTH_HOST', 'POP3_AUTH_HOST',
172          'AUTH_USER_FILE', 'AUTH_GROUP_FILE', 'AUTH_SESS_USER', 'AUTH_SESS_LEVEL',
173          'GOOGLE_LICENSE_KEY','FORTUNE_DIR',
174          'DISABLE_GETIMAGESIZE','DBADMIN_USER','DBADMIN_PASSWD',
175          'SESSION_SAVE_PATH', 
176          'TOOLBAR_PAGELINK_PULLDOWN', 'TOOLBAR_TEMPLATE_PULLDOWN', 'TOOLBAR_IMAGE_PULLDOWN',
177          'EXTERNAL_LINK_TARGET', 'ACCESS_LOG_SQL', 'USE_EXTERNAL_HTML2PDF',
178          'LOGIN_LOG','LDAP_SEARCH_FILTER'
179          );
180
181     // List of all valid config options to be define()d which take booleans.
182     $_IC_VALID_BOOL = array
183         ('ENABLE_USER_NEW', 'ENABLE_PAGEPERM', 'ENABLE_EDIT_TOOLBAR', 'JS_SEARCHREPLACE',
184          'ENABLE_XHTML_XML', 'ENABLE_DOUBLECLICKEDIT', 'ENABLE_LIVESEARCH',
185          'USECACHE', 'WIKIDB_NOCACHE_MARKUP',
186          'ENABLE_REVERSE_DNS', 'ENCRYPTED_PASSWD', 'ZIPDUMP_AUTH', 
187          'ENABLE_RAW_HTML', 'ENABLE_RAW_HTML_LOCKEDONLY', 'ENABLE_RAW_HTML_SAFE', 
188          'STRICT_MAILABLE_PAGEDUMPS', 'COMPRESS_OUTPUT',
189          'ALLOW_ANON_USER', 'ALLOW_ANON_EDIT',
190          'ALLOW_BOGO_LOGIN', 'ALLOW_USER_PASSWORDS',
191          'AUTH_USER_FILE_STORABLE', 'ALLOW_HTTP_AUTH_LOGIN',
192          'ALLOW_USER_LOGIN', 'ALLOW_LDAP_LOGIN', 'ALLOW_IMAP_LOGIN',
193          'WARN_NONPUBLIC_INTERWIKIMAP', 'USE_PATH_INFO',
194          'DISABLE_HTTP_REDIRECT',
195          'PLUGIN_CACHED_USECACHE', 'PLUGIN_CACHED_FORCE_SYNCMAP',
196          'BLOG_DEFAULT_EMPTY_PREFIX', 'DATABASE_PERSISTENT',
197          'ENABLE_DISCUSSION_LINK', 'ENABLE_CAPTCHA',
198          'ENABLE_WYSIWYG', 'WYSIWYG_DEFAULT_PAGETYPE_HTML',
199          'DISABLE_MARKUP_WIKIWORD', 'ENABLE_MARKUP_COLOR', 'ENABLE_MARKUP_TEMPLATE',
200          'ENABLE_MARKUP_MEDIAWIKI_TABLE',
201          'ENABLE_MARKUP_DIVSPAN', 'USE_BYTEA', 'UPLOAD_USERDIR', 'DISABLE_UNITS',
202          'ENABLE_SEARCHHIGHLIGHT', 'DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS',
203          'ENABLE_AUTH_OPENID', 'INSECURE_ACTIONS_LOCALHOST_ONLY',
204          'ENABLE_MAILNOTIFY', 'ENABLE_RECENTCHANGESBOX', 'ENABLE_PAGE_PUBLIC'
205          );
206
207     $rs = @parse_ini_file($file);
208     $rsdef = @parse_ini_file(dirname(__FILE__)."/../config/config-default.ini");
209     foreach ($rsdef as $k => $v) {
210         if (defined($k)) {
211             $rs[$k] = constant($k);
212         } elseif (!isset($rs[$k])) {
213             $rs[$k] = $v;
214         }
215     }
216     unset($k); unset($v); 
217     
218     foreach ($_IC_VALID_VALUE as $item) {
219         if (defined($item)) {
220             unset($rs[$item]);
221             continue;
222         }
223         if (array_key_exists($item, $rs)) {
224             _check_int_constant($rs[$item]);
225             define($item, $rs[$item]);
226             unset($rs[$item]);
227         //} elseif (array_key_exists($item, $rsdef)) {
228         //    define($item, $rsdef[$item]);
229         // calculate them later or not at all:
230         } elseif (in_array($item,
231                            array('DATABASE_PREFIX', 'SERVER_NAME', 'SERVER_PORT',
232                                  'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH',
233                                  'LDAP_AUTH_HOST','IMAP_AUTH_HOST','POP3_AUTH_HOST',
234                                  'PLUGIN_CACHED_CACHE_DIR','EXTERNAL_HTML2PDF_PAGELIST'))) 
235         {
236             ;
237         } elseif (!defined("_PHPWIKI_INSTALL_RUNNING")) {
238             trigger_error(sprintf("missing config setting for %s",$item));
239         }
240     }
241     unset($item);
242
243     // Boolean options are slightly special - if they're set to any of
244     // '', 'false', '0', or 'no' (all case-insensitive) then the value will
245     // be a boolean false, otherwise if there is anything set it'll
246     // be true.
247     foreach ($_IC_VALID_BOOL as $item) {
248         if (defined($item)) {
249             unset($rs[$item]);
250             continue;
251         }
252         if (array_key_exists($item, $rs)) {
253             $val = $rs[$item];
254         //} elseif (array_key_exists($item, $rsdef)) {
255         //    $val = $rsdef[$item];
256         } else {
257             $val = false; 
258             //trigger_error(sprintf("missing boolean config setting for %s",$item));
259         }
260         
261         // calculate them later: old or dynamic constants
262         if (!array_key_exists($item, $rs) and
263             in_array($item, array('USE_PATH_INFO', 'USE_DB_SESSION',
264                                   'ALLOW_HTTP_AUTH_LOGIN', 'ALLOW_LDAP_LOGIN',
265                                   'ALLOW_IMAP_LOGIN', 'ALLOW_USER_LOGIN',
266                                   'REQUIRE_SIGNIN_BEFORE_EDIT',
267                                   'WIKIDB_NOCACHE_MARKUP',
268                                   'COMPRESS_OUTPUT', 'USE_BYTEA'
269                                   )))
270         {
271             ;
272         }
273         elseif (!$val) {
274             define($item, false);
275         }
276         elseif (strtolower($val) == 'false' ||
277                 strtolower($val) == 'no' ||
278                 $val == '' ||
279                 $val == false ||
280                 $val == '0') {
281             define($item, false);
282         }
283         else {
284             define($item, true);
285         }
286         unset($rs[$item]);
287     }
288     unset($item);
289
290     // Database
291     global $DBParams;
292     foreach (array('DATABASE_TYPE'      => 'dbtype',
293                    'DATABASE_DSN'       => 'dsn',
294                    'DATABASE_SESSION_TABLE' => 'db_session_table',
295                    'DATABASE_DBA_HANDLER'   => 'dba_handler',
296                    'DATABASE_DIRECTORY' => 'directory',
297                    'DATABASE_TIMEOUT'   => 'timeout',
298                    'DATABASE_PREFIX'    => 'prefix')
299              as $item => $k)
300     {
301         if (defined($item)) {
302             $DBParams[$k] = constant($item);
303             unset($rs[$item]);
304         } elseif (array_key_exists($item, $rs)) {
305             $DBParams[$k] = $rs[$item];
306             define($item, $rs[$item]);
307             unset($rs[$item]);
308         } elseif (array_key_exists($item, $rsdef)) {
309             $DBParams[$k] = $rsdef[$item];
310             define($item, $rsdef[$item]);
311             unset($rsdef[$item]);
312         }
313     }
314     $valid_database_types = array('SQL','ADODB','PDO','dba','file','flatfile','cvs','cvsclient');
315     if (!in_array(DATABASE_TYPE, $valid_database_types))
316         trigger_error(sprintf("Invalid DATABASE_TYPE=%s. Choose one of %s", 
317                               DATABASE_TYPE, join(",", $valid_database_types)), 
318                       E_USER_ERROR);
319     unset($valid_database_types);                  
320     if (DATABASE_TYPE == 'PDO') {
321         if (!check_php_version(5))
322             trigger_error("Invalid DATABASE_TYPE=PDO. PDO requires at least php-5.0!", 
323                           E_USER_ERROR);
324         // try to load it dynamically (unix only)
325         if (!loadPhpExtension("pdo")) {
326             echo $GLOBALS['php_errormsg'], "<br>\n";
327             trigger_error(sprintf("dl() problem: Required extension '%s' could not be loaded!",
328                                   "pdo"),
329                           E_USER_ERROR);
330         }
331     }
332         
333     // USE_DB_SESSION default logic:
334     if (!defined('USE_DB_SESSION')) {
335         if ($DBParams['db_session_table']
336             and in_array($DBParams['dbtype'], array('SQL','ADODB','PDO'))) {
337             define('USE_DB_SESSION', true);
338         } elseif ($DBParams['dbtype'] == 'dba' and check_php_version(4,1,2)) {
339             define('USE_DB_SESSION', true); // Depends on db handler as well. 
340                                             // BerkeleyDB on older php has problems 
341                                             // with multiple db handles.
342         } else {
343             define('USE_DB_SESSION', false);
344         }
345     }
346     unset($item); unset($k); 
347
348     // Expiry stuff
349     global $ExpireParams;
350     foreach (array('major','minor','author') as $major) {
351         foreach (array('max_age','min_age','min_keep','keep','max_keep') as $max) {
352             $item = strtoupper($major) . '_'. strtoupper($max);
353             if (defined($item)) $val = constant($item);
354             elseif (array_key_exists($item, $rs))
355                 $val = $rs[$item];
356             elseif (array_key_exists($item, $rsdef))
357                 $val = $rsdef[$item];
358             if (!isset($ExpireParams[$major]))
359                 $ExpireParams[$major] = array();
360             $ExpireParams[$major][$max] = $val;
361             unset($rs[$item]);
362         }
363     }
364     unset($item); unset($major); unset($max); 
365     
366     // User authentication
367     if (!isset($GLOBALS['USER_AUTH_ORDER'])) {
368         if (isset($rs['USER_AUTH_ORDER']))
369             $GLOBALS['USER_AUTH_ORDER'] = preg_split('/\s*:\s*/', 
370                                                      $rs['USER_AUTH_ORDER']);
371         else 
372             $GLOBALS['USER_AUTH_ORDER'] = array("PersonalPage");
373     }
374
375     // Now it's the external DB authentication stuff's turn
376     if (in_array('Db', $GLOBALS['USER_AUTH_ORDER']) && empty($rs['DBAUTH_AUTH_DSN'])) {
377         $rs['DBAUTH_AUTH_DSN'] = $DBParams['dsn'];
378     }
379     
380     global $DBAuthParams;
381     $DBAP_MAP = array('DBAUTH_AUTH_DSN' => 'auth_dsn',
382                       'DBAUTH_AUTH_CHECK' => 'auth_check',
383                       'DBAUTH_AUTH_USER_EXISTS' => 'auth_user_exists',
384                       'DBAUTH_AUTH_CRYPT_METHOD' => 'auth_crypt_method',
385                       'DBAUTH_AUTH_UPDATE' => 'auth_update',
386                       'DBAUTH_AUTH_CREATE' => 'auth_create',
387                       'DBAUTH_PREF_SELECT' => 'pref_select',
388                       'DBAUTH_PREF_INSERT' => 'pref_insert',
389                       'DBAUTH_PREF_UPDATE' => 'pref_update',
390                       'DBAUTH_IS_MEMBER' => 'is_member',
391                       'DBAUTH_GROUP_MEMBERS' => 'group_members',
392                       'DBAUTH_USER_GROUPS' => 'user_groups'
393                       );
394     foreach ($DBAP_MAP as $rskey => $apkey) {
395         if (defined($rskey)) {
396             $DBAuthParams[$apkey] = constant($rskey);
397         } elseif (isset($rs[$rskey])) {
398             $DBAuthParams[$apkey] = $rs[$rskey];
399             define($rskey, $rs[$rskey]);
400         } elseif (isset($rsdef[$rskey])) {
401             $DBAuthParams[$apkey] = $rsdef[$rskey];
402             define($rskey, $rsdef[$rskey]);
403         }
404         unset($rs[$rskey]);
405     }
406     unset($rskey); unset($apkey);
407
408     // TODO: Currently unsupported on non-SQL. Nice to have for RhNavPlugin
409     // CHECKME: PDO
410     if (array_key_exists('ACCESS_LOG_SQL', $rs)) {
411         // WikiDB_backend::isSql() not yet loaded
412         if (!in_array(DATABASE_TYPE, array('SQL','ADODB','PDO')))
413             // override false config setting on no SQL WikiDB database.
414             define('ACCESS_LOG_SQL', 0);
415     }
416     // SQL defaults to ACCESS_LOG_SQL = 2
417     else {
418         define('ACCESS_LOG_SQL', 
419                in_array(DATABASE_TYPE, array('SQL','ADODB','PDO')) ? 2 : 0);
420     }
421
422     global $PLUGIN_MARKUP_MAP;
423     $PLUGIN_MARKUP_MAP = array();
424     if (defined('PLUGIN_MARKUP_MAP') and trim(PLUGIN_MARKUP_MAP) != "") {
425         $_map = preg_split('/\s+/', PLUGIN_MARKUP_MAP);
426         foreach ($_map as $v) {
427             list($xml,$plugin) = split(':', $v);
428             if (!empty($xml) and !empty($plugin))
429                 $PLUGIN_MARKUP_MAP[$xml] = $plugin;
430         }
431         unset($_map); unset($xml); unset($plugin); unset($v);
432     }
433
434     if (empty($rs['TEMP_DIR'])) {
435         $rs['TEMP_DIR'] = "/tmp";
436         if (getenv("TEMP"))
437             $rs['TEMP_DIR'] = getenv("TEMP");
438     }
439     // optional values will be set to '' to simplify the logic.
440     foreach ($_IC_OPTIONAL_VALUE as $item) {
441         if (defined($item)) {
442             unset($rs[$item]);
443             continue;
444         }
445         if (array_key_exists($item, $rs)) {
446             _check_int_constant($rs[$item]);
447             define($item, $rs[$item]);
448             unset($rs[$item]);
449         } else 
450             define($item, '');
451     }
452
453     if (USE_EXTERNAL_HTML2PDF) {
454         $item = 'EXTERNAL_HTML2PDF_PAGELIST';
455         if (defined($item)) {
456             unset($rs[$item]);
457         } elseif (array_key_exists($item, $rs)) {
458             define($item, $rs[$item]);
459             unset($rs[$item]);
460         } elseif (array_key_exists($item, $rsdef)) {
461             define($item, $rsdef[$item]);
462         }
463     }
464     unset($item); 
465         
466     // LDAP bind options
467     global $LDAP_SET_OPTION;
468     if (defined('LDAP_SET_OPTION') and LDAP_SET_OPTION) {
469         $optlist = preg_split('/\s*:\s*/', LDAP_SET_OPTION);
470         foreach ($optlist as $opt) {
471             $bits = preg_split('/\s*=\s*/', $opt, 2);
472             if (count($bits) == 2) {
473                 if (is_string($bits[0]) and defined($bits[0]))
474                     $bits[0] = constant($bits[0]);
475                 $LDAP_SET_OPTION[$bits[0]] = $bits[1];
476             }
477             else {
478                 // Possibly throw some sort of error?
479             }
480         }
481         unset($opt); unset($bits);
482     }
483
484     // Default Wiki pages to force loading from pgsrc
485     global $GenericPages;
486     $GenericPages = preg_split('/\s*:\s*/', @$rs['DEFAULT_WIKI_PAGES']);
487
488     // Wiki name regexp:  Should be a define(), but might needed to be changed at runtime
489     // (different LC_CHAR need different posix classes)
490     global $WikiNameRegexp;
491     $WikiNameRegexp = constant('WIKI_NAME_REGEXP');
492     if (!trim($WikiNameRegexp))
493        $WikiNameRegexp = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])';
494
495     // Got rid of global $KeywordLinkRegexp by using a TextSearchQuery instead 
496     // of "Category:Topic"
497     if (!isset($rs['KEYWORDS'])) $rs['KEYWORDS'] = @$rsdef['KEYWORDS'];
498     if (!isset($rs['KEYWORDS'])) $rs['KEYWORDS'] = "Category* OR Topic*";
499     if ($rs['KEYWORDS'] == 'Category:Topic') $rs['KEYWORDS'] = "Category* OR Topic*";
500     if (!defined('KEYWORDS')) define('KEYWORDS', $rs['KEYWORDS']);
501     //if (empty($keywords)) $keywords = array("Category","Topic");
502     //$KeywordLinkRegexp = '(?<=' . implode('|^', $keywords) . ')[[:upper:]].*$';
503
504     // TODO: can this be a constant?
505     global $DisabledActions;
506     if (!array_key_exists('DISABLED_ACTIONS', $rs) 
507         and array_key_exists('DISABLED_ACTIONS', $rsdef))
508         $rs['DISABLED_ACTIONS'] = @$rsdef['DISABLED_ACTIONS'];
509     if (array_key_exists('DISABLED_ACTIONS', $rs))
510         $DisabledActions = preg_split('/\s*:\s*/', $rs['DISABLED_ACTIONS']);
511
512     global $PLUGIN_CACHED_IMGTYPES;
513     $PLUGIN_CACHED_IMGTYPES = preg_split('/\s*[|:]\s*/', PLUGIN_CACHED_IMGTYPES);
514
515     if (!defined('PLUGIN_CACHED_CACHE_DIR')) {
516         if (empty($rs['PLUGIN_CACHED_CACHE_DIR']) and !empty($rsdef['PLUGIN_CACHED_CACHE_DIR']))
517             $rs['PLUGIN_CACHED_CACHE_DIR'] = $rsdef['PLUGIN_CACHED_CACHE_DIR'];
518         if (empty($rs['PLUGIN_CACHED_CACHE_DIR'])) {
519             if (!empty($rs['INCLUDE_PATH'])) {
520                 @ini_set('include_path', $rs['INCLUDE_PATH']);
521                 $GLOBALS['INCLUDE_PATH'] = $rs['INCLUDE_PATH'];
522             }
523             $rs['PLUGIN_CACHED_CACHE_DIR'] = TEMP_DIR . '/cache';
524             if (!FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], 1)) { // [29ms]
525                 FindFile(TEMP_DIR, false, 1);            // TEMP must exist!
526                 mkdir($rs['PLUGIN_CACHED_CACHE_DIR'], 777);
527             }
528             // will throw an error if not exists.
529             define('PLUGIN_CACHED_CACHE_DIR', FindFile($rs['PLUGIN_CACHED_CACHE_DIR'],false,1)); 
530         } else {
531             define('PLUGIN_CACHED_CACHE_DIR', $rs['PLUGIN_CACHED_CACHE_DIR']);
532             // will throw an error if not exists.
533             FindFile(PLUGIN_CACHED_CACHE_DIR);
534         }
535     }
536
537     // process the rest of the config.ini settings:
538     foreach ($rs as $item => $v) {
539         if (defined($item)) {
540             continue;
541         } else {
542             _check_int_constant($v);
543             define($item, $v);
544         }
545     }
546     unset($item); unset($v); 
547
548     unset($rs); 
549     unset($rsdef);
550     
551     fixup_static_configs($file); //[1ms]
552     // Dump all globals and constants
553     // The question is if reading this is faster then doing IniConfig() + fixup_static_configs()
554     if (is_writable($dump)) {
555         save_dump($dump);
556     }
557     // store locale[] in config.php? This is too problematic.
558     fixup_dynamic_configs($file); // [100ms]
559 }
560
561 function _ignore_unknown_charset_warning(&$error) {
562     //htmlspecialchars(): charset `iso-8859-2' not supported, assuming iso-8859-1
563     if (preg_match('/^htmlspecialchars\(\): charset \`.+\' not supported, assuming iso-8859-1/',
564                    $error->errstr)) {
565         $error->errno = 0;
566         return true;  // Ignore error
567     }
568     return false;
569 }
570
571 // moved from lib/config.php [1ms]
572 function fixup_static_configs($file) {
573     global $FieldSeparator, $charset, $WikiNameRegexp, $AllActionPages;
574     global $HTTP_SERVER_VARS, $DBParams, $LANG, $ErrorManager;
575     // init FileFinder to add proper include paths
576     FindFile("lib/interwiki.map",true);
577     
578     // "\x80"-"\x9f" (and "\x00" - "\x1f") are non-printing control
579     // chars in iso-8859-*
580     // $FieldSeparator = "\263"; // this is a superscript 3 in ISO-8859-1.
581     // $FieldSeparator = "\xFF"; // this byte should never appear in utf-8
582     // Get rid of constant. pref is dynamic and language specific
583     $charset = CHARSET;
584     // Disabled: Let the admin decide which charset.
585     //if (isset($LANG) and in_array($LANG,array('zh')))
586     //    $charset = 'utf-8';
587     if (strtolower($charset) == 'utf-8')
588         $FieldSeparator = "\xFF";
589     else
590         $FieldSeparator = "\x81";
591
592     // Some exotic charsets are not supported by htmlspecialchars, which just prints an E_WARNING.
593     // Even on simple 8bit charsets, where just <>& need to be replaced. For iso-8859-[2-4] e.g.
594     // See <php-src>/ext/standard/html.c
595     // For performance reasons we require a magic constant to ignore this warning.
596     if (defined('IGNORE_CHARSET_NOT_SUPPORTED_WARNING') and IGNORE_CHARSET_NOT_SUPPORTED_WARNING) {
597         $ErrorManager->pushErrorHandler(new WikiFunctionCb('_ignore_unknown_charset_warning'));
598     }
599     // Used by SetupWiki to pull in required pages, if not translated, then in english.
600     // Also used by _WikiTranslation. Really important are only those which return pagelists 
601     // or contain basic functionality.
602     /*
603       All pages containing plugins of the same name as the filename:
604      */
605     $AllActionPages = explode(':',
606       'AllPages:AllUsers:AppendText:AuthorHistory:'
607       .'BackLinks:BlogArchives:BlogJournal:'
608       .'CreatePage:'
609       .'FindPage:FullTextSearch:FuzzyPages:'
610       .'InterWikiSearch:'
611       .'LdapSearch:LikePages:LinkDatabase:LinkSearch:ListRelations:'
612       .'ModeratedPage:MostPopular:'
613       .'OrphanedPages:'
614       .'PageDump:PageHistory:PageInfo:PasswordReset:PluginManager:'
615       .'RateIt:RecentChanges:RecentComments:RelatedChanges:'
616       .'SearchHighlight:SemanticRelations:SemanticSearch:SystemInfo:'
617       .'TitleSearch:TranslateText:'
618       .'UpLoad:UriResolver:UserPreferences:'
619       .'WantedPages:WatchPage:WhoIsOnline:WikiAdminSelect:WikiBlog:'
620       // plus some derivations
621       .'AllPagesCreatedByMe:AllPagesLastEditedByMe:AllPagesOwnedByMe:AllUserPages:'
622       .'FullRecentChanges:'
623       .'LeastPopular:LockedPages:'
624       .'MyRecentEdits:MyRecentChanges:'
625       .'PhpWikiAdministration:'
626       .'PhpWikiAdministration/Chown:'
627       .'PhpWikiAdministration/Markup:'
628       .'PhpWikiAdministration/Purge:'
629       .'PhpWikiAdministration/Remove:'
630       .'PhpWikiAdministration/Rename:'
631       .'PhpWikiAdministration/SearchReplace:'
632       .'PhpWikiAdministration/SetAcl:'
633       .'RecentChangesMyPages:RecentEdits:RecentNewPages:'
634       .'UserContribs');
635
636     // Add some some action pages depending on configuration
637     if (defined('DEBUG') and DEBUG) {
638        $AllActionPages[] = 'DebugInfo';
639        $AllActionPages[] = 'EditMetaData';
640        $AllActionPages[] = 'RandomPage'; // RandomPage does not work
641        $AllActionPages[] = 'SpellCheck'; // SpellCheck does not work
642        $AllActionPages[] = 'PhpWikiAdministration/Chmod';
643     }
644
645     // If user has not defined PHPWIKI_DIR, and we need it
646     if (!defined('PHPWIKI_DIR') and !file_exists("themes/default")) {
647         $themes_dir = FindFile("themes");
648         define('PHPWIKI_DIR', dirname($themes_dir));
649     }
650         
651     // If user has not defined DATA_PATH, we want to use relative URLs.
652     if (!defined('DATA_PATH')) {
653         // fix similar to the one suggested by jkalmbach for 
654         // installations in the webrootdir, like "http://phpwiki.org/HomePage"
655         if (!defined('SCRIPT_NAME'))
656             define('SCRIPT_NAME', deduce_script_name());
657         $temp = dirname(SCRIPT_NAME);
658         if ( ($temp == '/') || ($temp == '\\') )
659             $temp = '';
660         define('DATA_PATH', $temp);
661         /*
662         if (USE_PATH_INFO)
663             define('DATA_PATH', '..');
664         */
665     }
666
667     //////////////////////////////////////////////////////////////////
668     // Select database
669     //
670     if (empty($DBParams['dbtype']))
671         $DBParams['dbtype'] = 'dba';
672
673     if (!defined('THEME'))
674         define('THEME', 'default');
675         
676     /*$configurator_link = HTML(HTML::br(), "=>", 
677                               HTML::a(array('href'=>DATA_PATH."/configurator.php"),
678                                                                   _("Configurator")));*/
679     // check whether the crypt() function is needed and present
680     if (defined('ENCRYPTED_PASSWD') && !function_exists('crypt')) {
681         $error = sprintf("Encrypted passwords cannot be used: %s.",
682                          "'function crypt()' not available in this version of php");
683         trigger_error($error, E_USER_WARNING);
684         if (!preg_match("/config\-dist\.ini$/", $file)) { // protect against recursion
685             include_once(dirname(__FILE__)."/install.php");
686             run_install("_part1");
687             exit();
688         }
689     }
690
691     // Basic configurator validation
692     if (!defined('ADMIN_USER') or ADMIN_USER == '') {
693         $error = sprintf("%s may not be empty. Please update your configuration.", 
694                          "ADMIN_USER");
695         // protect against recursion
696         if (!preg_match("/config\-(dist|default)\.ini$/", $file)
697             and !defined("_PHPWIKI_INSTALL_RUNNING"))
698         {
699             include_once(dirname(__FILE__)."/install.php");
700             run_install("_part1");
701             trigger_error($error, E_USER_ERROR);
702             exit();
703         } elseif ($HTTP_SERVER_VARS["REQUEST_METHOD"] == "POST") {
704             $GLOBALS['HTTP_GET_VARS']['show'] = '_part1';
705             trigger_error($error, E_USER_WARNING);
706         }
707     }
708     if (!defined('ADMIN_PASSWD') or ADMIN_PASSWD == '') {
709         $error = sprintf("%s may not be empty. Please update your configuration.", 
710                          "ADMIN_PASSWD");
711         // protect against recursion
712         if (!preg_match("/config\-(dist|default)\.ini$/", $file)
713            and !defined("_PHPWIKI_INSTALL_RUNNING")) 
714         { 
715             include_once(dirname(__FILE__)."/install.php");
716             run_install("_part1");
717             trigger_error($error, E_USER_ERROR);
718             exit();
719         } elseif ($HTTP_SERVER_VARS["REQUEST_METHOD"] == "POST") {
720             $GLOBALS['HTTP_GET_VARS']['show'] = '_part1';
721             trigger_error($error, E_USER_WARNING);
722         }
723     }
724
725     if (defined('USE_DB_SESSION') and USE_DB_SESSION) {
726         if (! $DBParams['db_session_table'] ) {
727             $DBParams['db_session_table'] = @$DBParams['prefix'] . 'session';
728             trigger_error(sprintf("DATABASE_SESSION_TABLE configuration set to %s.", 
729                                   $DBParams['db_session_table']),
730                           E_USER_ERROR);
731         }
732     }
733     // legacy:
734     if (!defined('ENABLE_USER_NEW')) define('ENABLE_USER_NEW',true);
735     if (!defined('ALLOW_USER_LOGIN'))
736         define('ALLOW_USER_LOGIN', defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
737     if (!defined('ALLOW_ANON_USER')) define('ALLOW_ANON_USER', true); 
738     if (!defined('ALLOW_ANON_EDIT')) define('ALLOW_ANON_EDIT', false); 
739     if (!defined('REQUIRE_SIGNIN_BEFORE_EDIT')) define('REQUIRE_SIGNIN_BEFORE_EDIT', ! ALLOW_ANON_EDIT);
740     if (!defined('ALLOW_BOGO_LOGIN')) define('ALLOW_BOGO_LOGIN', true);
741     if (!ENABLE_USER_NEW) {
742       if (!defined('ALLOW_HTTP_AUTH_LOGIN'))
743           define('ALLOW_HTTP_AUTH_LOGIN', false);
744       if (!defined('ALLOW_LDAP_LOGIN')) 
745           define('ALLOW_LDAP_LOGIN', function_exists('ldap_connect') and defined('LDAP_AUTH_HOST'));
746       if (!defined('ALLOW_IMAP_LOGIN')) 
747           define('ALLOW_IMAP_LOGIN', function_exists('imap_open') and defined('IMAP_AUTH_HOST'));
748     }
749
750     if (ALLOW_USER_LOGIN and !empty($DBAuthParams) and empty($DBAuthParams['auth_dsn'])) {
751         if (isset($DBParams['dsn']))
752             $DBAuthParams['auth_dsn'] = $DBParams['dsn'];
753     }
754 }
755
756 /** 
757  * Define constants which are client or request specific and should not be dumped statically.
758  * Such as the language, and the virtual and server paths, which might be overridden 
759  * by startup scripts for wiki farms.
760  */
761 function fixup_dynamic_configs($file) {
762     global $WikiNameRegexp;
763     global $HTTP_SERVER_VARS, $DBParams, $LANG;
764
765     if (defined('INCLUDE_PATH') and INCLUDE_PATH) {
766         @ini_set('include_path', INCLUDE_PATH);
767         $GLOBALS['INCLUDE_PATH'] = INCLUDE_PATH;
768     }
769     if (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH)
770         @ini_set('session.save_path', SESSION_SAVE_PATH);
771     if (!defined('DEFAULT_LANGUAGE'))   // not needed anymore
772         define('DEFAULT_LANGUAGE', ''); // detect from client
773
774     update_locale(isset($LANG) ? $LANG : DEFAULT_LANGUAGE);
775     if (empty($LANG)) {
776         if (!defined("DEFAULT_LANGUAGE") or !DEFAULT_LANGUAGE) {
777             // TODO: defer this to WikiRequest::initializeLang()
778             $LANG = guessing_lang(); 
779             guessing_setlocale (LC_ALL,$LANG);
780         }
781         else
782             $LANG = DEFAULT_LANGUAGE;
783     }
784  
785     // Set up (possibly fake) gettext()
786     // Todo: this could be moved to fixup_static_configs()
787     // Bug #1381464 with php-5.1.1
788     if (!function_exists ('bindtextdomain')
789         and !function_exists ('gettext')
790         and !function_exists ('_'))
791     {
792         $locale = array();
793
794         function gettext ($text) { 
795             global $locale;
796             if (!empty ($locale[$text]))
797                 return $locale[$text];
798             return $text;
799         }
800         function _ ($text) {
801             return gettext($text);
802         }
803     }
804     else {
805         // Working around really weird gettext problems: (4.3.2, 4.3.6 win)
806         // bindtextdomain() returns the current domain path.
807         // 1. If the script is not index.php but something like "de", on a different path
808         //    then bindtextdomain() fails, but after chdir to the correct path it will work okay.
809         // 2. But the weird error "Undefined variable: bindtextdomain" is generated then.
810         $bindtextdomain_path = FindFile("locale", false, true);
811         $chback = 0;
812         if (isWindows())
813             $bindtextdomain_path = str_replace("/", "\\", $bindtextdomain_path);
814         $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain_path);
815         if (realpath($bindtextdomain_real) != realpath($bindtextdomain_path)) {
816             // this will happen with virtual_paths. chdir and try again.
817             chdir($bindtextdomain_path);
818             $chback = 1;
819             $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain_path);
820         }
821         // tell gettext not to use unicode. PHP >= 4.2.0. Thanks to Kai Krakow.
822         if (defined('CHARSET') and function_exists('bind_textdomain_codeset'))
823             @bind_textdomain_codeset("phpwiki", CHARSET);
824         textdomain("phpwiki");
825         if ($chback) { // change back
826             chdir($bindtextdomain_real . (isWindows() ? "\\.." : "/.."));
827         }
828     }
829
830     // language dependent updates:
831     $WikiNameRegexp = pcre_fix_posix_classes($WikiNameRegexp);
832     //if ($KeywordLinkRegexp) $KeywordLinkRegexp = pcre_fix_posix_classes($KeywordLinkRegexp);
833     if (!defined('CATEGORY_GROUP_PAGE'))
834         define('CATEGORY_GROUP_PAGE',_("CategoryGroup"));
835     if (!defined('WIKI_NAME'))
836         define('WIKI_NAME', _("An unnamed PhpWiki"));
837     if (!defined('HOME_PAGE'))
838         define('HOME_PAGE', _("HomePage"));
839
840
841     //////////////////////////////////////////////////////////////////
842     // Autodetect URL settings:
843     //
844     foreach (array('SERVER_NAME','SERVER_PORT') as $var) {
845         //FIXME: for CGI without _SERVER
846         if (!defined($var) and !empty($HTTP_SERVER_VARS[$var]))
847             // IPV6 fix by matt brown, #1546571
848             // An IPv6 address must be surrounded by square brackets to form a valid server name.
849             if ($var == 'SERVER_NAME' &&
850                     strstr($HTTP_SERVER_VARS[$var], ':')) {
851                 define($var, '[' . $HTTP_SERVER_VARS[$var] . ']');
852             } else {
853                 define($var, $HTTP_SERVER_VARS[$var]);
854             }
855     }
856     if (!defined('SERVER_NAME')) define('SERVER_NAME', '127.0.0.1');
857     if (!defined('SERVER_PORT')) define('SERVER_PORT', 80);
858     if (!defined('SERVER_PROTOCOL')) {
859         if (empty($HTTP_SERVER_VARS['HTTPS']) || $HTTP_SERVER_VARS['HTTPS'] == 'off')
860             define('SERVER_PROTOCOL', 'http');
861         else
862             define('SERVER_PROTOCOL', 'https');
863     }
864
865     if (!defined('SCRIPT_NAME'))
866         define('SCRIPT_NAME', deduce_script_name());
867
868     if (!defined('USE_PATH_INFO')) {
869         if (isCGI())
870             define('USE_PATH_INFO', false);
871         else {
872             /*
873              * If SCRIPT_NAME does not look like php source file,
874              * or user cgi we assume that php is getting run by an
875              * action handler in /cgi-bin.  In this case,
876              * I think there is no way to get Apache to pass
877              * useful PATH_INFO to the php script (PATH_INFO
878              * is used to the the php interpreter where the
879              * php script is...)
880              */
881             switch (php_sapi_name()) {
882             case 'apache':
883             case 'apache2handler':
884                 define('USE_PATH_INFO', true);
885                 break;
886             case 'cgi':
887             case 'apache2filter':
888                 define('USE_PATH_INFO', false);
889                 break;
890             default:
891                 define('USE_PATH_INFO', ereg('\.(php3?|cgi)$', SCRIPT_NAME));
892                 break;
893             }
894         }
895     }
896      
897     if (SERVER_PORT
898         && SERVER_PORT != (SERVER_PROTOCOL == 'https' ? 443 : 80)) {
899         define('SERVER_URL',
900                SERVER_PROTOCOL . '://' . SERVER_NAME . ':' . SERVER_PORT);
901     }
902     else {
903         define('SERVER_URL',
904                SERVER_PROTOCOL . '://' . SERVER_NAME);
905     }
906
907     if (!defined('VIRTUAL_PATH')) {
908         // We'd like to auto-detect when the cases where apaches
909         // 'Action' directive (or similar means) is used to
910         // redirect page requests to a cgi-handler.
911         //
912         // In cases like this, requests for e.g. /wiki/HomePage
913         // get redirected to a cgi-script called, say,
914         // /path/to/wiki/index.php.  The script gets all
915         // of /wiki/HomePage as it's PATH_INFO.
916         //
917         // The problem is:
918         //   How to detect when this has happened reliably?
919         //   How to pick out the "virtual path" (in this case '/wiki')?
920         //
921         // (Another time an redirect might occur is to a DirectoryIndex
922         // -- the requested URI is '/wikidir/', the request gets
923         // passed to '/wikidir/index.php'.  In this case, the
924         // proper VIRTUAL_PATH is '/wikidir/index.php', since the
925         // pages will appear at e.g. '/wikidir/index.php/HomePage'.
926         //
927
928         $REDIRECT_URL = &$HTTP_SERVER_VARS['REDIRECT_URL'];
929         if (USE_PATH_INFO and isset($REDIRECT_URL)
930             and ! IsProbablyRedirectToIndex()) {
931             // FIXME: This is a hack, and won't work if the requested
932             // pagename has a slash in it.
933             $temp = strtr(dirname($REDIRECT_URL . 'x'),"\\",'/');
934             if ( ($temp == '/') || ($temp == '\\') )
935                 $temp = '';
936             define('VIRTUAL_PATH', $temp);
937         } else {
938             define('VIRTUAL_PATH', SCRIPT_NAME);
939         }
940     }
941
942     if (VIRTUAL_PATH != SCRIPT_NAME) {
943         // Apache action handlers are used.
944         define('PATH_INFO_PREFIX', VIRTUAL_PATH . '/');
945     }
946     else
947         define('PATH_INFO_PREFIX', '/');
948
949     define('PHPWIKI_BASE_URL',
950            SERVER_URL . (USE_PATH_INFO ? VIRTUAL_PATH . '/' : SCRIPT_NAME));
951
952     // Detect PrettyWiki setup (not loading index.php directly)
953     // $SCRIPT_FILENAME should be the same as __FILE__ in index.php
954     if (!isset($SCRIPT_FILENAME))
955         $SCRIPT_FILENAME = @$HTTP_SERVER_VARS['SCRIPT_FILENAME'];
956     if (!isset($SCRIPT_FILENAME))
957         $SCRIPT_FILENAME = @$HTTP_ENV_VARS['SCRIPT_FILENAME'];
958     if (!isset($SCRIPT_FILENAME))
959         $SCRIPT_FILENAME = dirname(__FILE__.'/../') . '/index.php';
960     if (isWindows())
961         $SCRIPT_FILENAME = str_replace('\\\\','\\',strtr($SCRIPT_FILENAME, '/', '\\'));
962     define('SCRIPT_FILENAME', $SCRIPT_FILENAME);
963
964     // Get remote host name, if apache hasn't done it for us
965     if (empty($HTTP_SERVER_VARS['REMOTE_HOST'])
966         and !empty($HTTP_SERVER_VARS['REMOTE_ADDR'])
967         and ENABLE_REVERSE_DNS)
968         $HTTP_SERVER_VARS['REMOTE_HOST'] = gethostbyaddr($HTTP_SERVER_VARS['REMOTE_ADDR']);
969
970 }
971
972 // (c-file-style: "gnu")
973 // Local Variables:
974 // mode: php
975 // tab-width: 8
976 // c-basic-offset: 4
977 // c-hanging-comment-ender-p: nil
978 // indent-tabs-mode: nil
979 // End:   
980 ?>