]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/IniConfig.php
Removed Pear_Config for parse_ini_file().
[SourceForge/phpwiki.git] / lib / IniConfig.php
1 <?php
2 rcs_id('$Id: IniConfig.php,v 1.7 2004-04-20 22:26:27 zorloc Exp $');
3
4 /**
5  * A configurator intended to read it's config from a PHP-style INI file,
6  * instead of a PHP file.
7  *
8  * Pass a filename to the IniConfig() function and it will read all it's
9  * definitions from there, all by itself, and proceed to do a mass-define
10  * of all valid PHPWiki config items.  In this way, we can hopefully be
11  * totally backwards-compatible with the old index.php method, while still
12  * providing a much tastier on-going experience.
13  *
14  * @author: Joby Walker, Reini Urban, Matthew Palmer
15  */
16 /*
17  * Copyright 2004 $ThePhpWikiProgrammingTeam
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 /** TODO
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  *
41  * - Resurrect the larger "config object" code (in config/) so it'll aid the
42  *      GUI config writers, and allow us to do proper validation and default
43  *      value handling.
44  *
45  * - Get rid of WikiNameRegexp and KeywordLinkRegexp as globals by finding
46  *      everywhere that uses them as variables and modify the code to use
47  *      them as constants.  Will involve hacking around
48  *      pcre_fix_posix_classes (probably with redefines()).
49  */
50
51 include_once "lib/config.php";
52  
53 function IniConfig($file)
54 {
55  
56     // List of all valid config options to be define()d which take "values" (not
57     // booleans). Needs to be categorised, and generally made a lot tidier.
58     $_IC_VALID_VALUE = array
59         ('WIKI_NAME', 'ADMIN_USER', 'ADMIN_PASSWD',
60          'HTML_DUMP_SUFFIX', 'MAX_UPLOAD_SIZE', 'MINOR_EDIT_TIMEOUT',
61          'ACCESS_LOG', 'CACHE_CONTROL', 'CACHE_CONTROL_MAX_AGE',
62          'PASSWORD_LENGTH_MINIMUM', 'USER_AUTH_POLICY', 'LDAP_AUTH_HOST',
63          'LDAP_BASE_DN', 'LDAP_AUTH_USER', 'LDAP_AUTH_PASSWORD',
64          'LDAP_SEARCH_FIELD', 'IMAP_AUTH_HOST', 'POP3_AUTH_HOST',
65          'POP3_AUTH_PORT', 'AUTH_USER_FILE', 'AUTH_SESS_USER', 
66          'AUTH_SESS_LEVEL', 'GROUP_METHOD',
67          'AUTH_GROUP_FILE', 'EDITING_POLICY', 'THEME', 'CHARSET',
68          'DEFAULT_LANGUAGE', 'WIKI_PGSRC', 'DEFAULT_WIKI_PGSRC',
69          'ALLOWED_PROTOCOLS', 'INLINE_IMAGES', 'SUBPAGE_SEPARATOR',
70          'INTERWIKI_MAP_FILE', 'COPYRIGHTPAGE_TITLE', 'COPYRIGHTPAGE_URL',
71          'AUTHORPAGE_TITLE', 'AUTHORPAGE_URL', 'SERVER_NAME', 'SERVER_PORT',
72          'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH');
73
74     // List of all valid config options to be define()d which take booleans.
75     $_IC_VALID_BOOL = array
76         ('DEBUG', 'ENABLE_USER_NEW', 'JS_SEARCHREPLACE',
77          'ENABLE_REVERSE_DNS', 'ENCRYPTED_PASSWD', 'ZIPDUMP_AUTH', 
78          'ENABLE_RAW_HTML', 'STRICT_MAILABLE_PAGEDUMPS', 'COMPRESS_OUTPUT',
79          'WIKIDB_NOCACHE_MARKUP', 'ALLOW_ANON_USER', 'ALLOW_ANON_EDIT',
80          'ALLOW_BOGO_LOGIN', 'ALLOW_USER_PASSWORDS',
81          'AUTH_USER_FILE_STORABLE', 'ALLOW_HTTP_AUTH_LOGIN',
82          'ALLOW_USER_LOGIN', 'ALLOW_LDAP_LOGIN', 'ALLOW_IMAP_LOGIN',
83          'WARN_NONPUBLIC_INTERWIKIMAP', 'USE_PATH_INFO',
84          'DISABLE_HTTP_REDIRECT');
85
86     if(!file_exists($file)){
87         trigger_error("Datasource file '$file' does not exist", E_USER_ERROR);
88         exit();
89     }
90          
91     $rs = @parse_ini_file($file);
92
93     foreach ($_IC_VALID_VALUE as $item) {
94         if (array_key_exists($item, $rs) and !defined($item)) {
95             define($item, $rs[$item]);
96         }
97     }
98
99     // Boolean options are slightly special - if they're set to any of
100     // 'false', '0', or 'no' (all case-insensitive) then the value will
101     // be a boolean false, otherwise if there is anything set it'll
102     // be true.
103     foreach ($_IC_VALID_BOOL as $item) {
104         if (array_key_exists($item, $rs)) {
105             $val = $rs[$item];
106             if (!$val and !defined($item)) {
107                 define($item, false);
108             }
109             else if (strtolower($val) == 'false' ||
110                      strtolower($val) == 'no' ||
111                      $val == '0') {
112                 if (!defined($item))
113                     define($item, false);
114             }
115             else {
116                 if (!defined($item))
117                     define($item, true);
118             }
119         }
120     }
121
122     // Special handling for some config options
123     if ($val = @$rs['INCLUDE_PATH']) {
124         ini_set('include_path', $val);
125     }
126
127     if ($val = @$rs['SESSION_SAVE_PATH']) {
128         ini_set('session.save_path', $val);
129     }
130
131     // Database
132     global $DBParams;
133     $DBParams['dbtype'] = @$rs['DATABASE_TYPE'];
134     $DBParams['prefix'] = @$rs['DATABASE_PREFIX'];
135     $DBParams['dsn'] = @$rs['DATABASE_DSN'];
136     $DBParams['db_session_table'] = @$rs['DATABASE_SESSION_TABLE'];
137     $DBParams['dba_handler'] = @$rs['DATABASE_DBA_HANDLER'];
138     $DBParams['directory'] = @$rs['DATABASE_DIRECTORY'];
139     $DBParams['timeout'] = @$rs['DATABASE_TIMEOUT'];
140     if (!defined('USE_DB_SESSION') and $DBParams['db_session_table']) {
141         define('USE_DB_SESSION', true);
142     }
143
144     // Expiry stuff
145     global $ExpiryParams;
146
147     $ExpiryParams['major'] = array(
148                                    'max_age' => @$rs['MAJOR_MAX_AGE'],
149                                    'min_age' => @$rs['MAJOR_MIN_AGE'],
150                                    'min_keep' => @$rs['MAJOR_MIN_KEEP'],
151                                    'keep' => @$rs['MAJOR_KEEP'],
152                                    'max_keep' => @$rs['MAJOR_MAX_KEEP']
153                                    );
154
155     $ExpiryParams['minor'] = array(
156                                    'max_age' => @$rs['MINOR_MAX_AGE'],
157                                    'min_age' => @$rs['MINOR_MIN_AGE'],
158                                    'min_keep' => @$rs['MINOR_MIN_KEEP'],
159                                    'keep' => @$rs['MINOR_KEEP'],
160                                    'max_keep' => @$rs['MINOR_MAX_KEEP']
161                                    );
162
163     $ExpiryParams['author'] = array(
164                                     'max_age' => @$rs['AUTHOR_MAX_AGE'],
165                                     'min_age' => @$rs['AUTHOR_MIN_AGE'],
166                                     'min_keep' => @$rs['AUTHOR_MIN_KEEP'],
167                                     'keep' => @$rs['AUTHOR_KEEP'],
168                                     'max_keep' => @$rs['AUTHOR_MAX_KEEP']
169                                     );
170
171     // User authentication
172     global $USER_AUTH_ORDER;
173     $USER_AUTH_ORDER = preg_split('/\s*:\s*/', @$rs['USER_AUTH_ORDER']);
174
175     // LDAP bind options
176     global $LDAP_SET_OPTION;
177     $optlist = preg_split('/\s*:\s*/', @$rs['LDAP_SET_OPTION']);
178     foreach ($optlist as $opt) {
179         $bits = preg_split('/\s*=\s*/', $opt, 2);
180         if (count($bits) == 2) {
181             $LDAP_SET_OPTION[$bits[0]] = $bits[1];
182         }
183         else {
184             // Possibly throw some sort of error?
185         }
186     }
187
188     // Now it's the external DB authentication stuff's turn
189     global $DBAuthParams;
190     $DBAP_MAP = array('DBAUTH_AUTH_DSN' => 'auth_dsn',
191                       'DBAUTH_AUTH_CHECK' => 'auth_check',
192                       'DBAUTH_AUTH_USER_EXISTS' => 'auth_user_exists',
193                       'DBAUTH_AUTH_CRYPT_METHOD' => 'auth_crypt_method',
194                       'DBAUTH_AUTH_UPDATE' => 'auth_update',
195                       'DBAUTH_AUTH_CREATE' => 'auth_create',
196                       'DBAUTH_PREF_SELECT' => 'pref_select',
197                       'DBAUTH_PREF_UPDATE' => 'pref_update',
198                       'DBAUTH_IS_MEMBER' => 'is_member',
199                       'DBAUTH_GROUP_MEMBERS' => 'group_members',
200                       'DBAUTH_USER_GROUPS' => 'user_groups'
201                       );
202
203     foreach ($DBAP_MAP as $rskey => $apkey) {
204         $val = @$rs[$rskey];
205         if ($val) {
206             $DBAuthParams[$apkey] = $val;
207         }
208     }
209
210     // Default Wiki pages
211     global $GenericPages;
212     $GenericPages = preg_split('/\s*:\s*/', @$rs['DEFAULT_WIKI_PAGES']);
213
214     // Wiki name regexp.  Should be a define(), but too many places want
215     // to use it as a variable for me to be bothered changing them all.
216     // Major TODO item, there.
217     global $WikiNameRegexp;
218     $WikiNameRegexp = @$rs['WIKI_NAME_REGEXP'];
219
220     // Another "too-tricky" redefine
221     global $KeywordLinkRegexp;
222     $keywords = preg_split('/\s*:\s*/', @$rs['KEYWORDS']);
223     $KeywordLinkRegexp = '(?<=' . implode('|^', $keywords) . ')[[:upper:]].*$';
224         
225     global $DisabledActions;
226     $DisabledActions = preg_split('/\s*:\s*/', @$rs['DISABLED_ACTIONS']);
227
228     fix_configs();
229 }
230
231 // moved from lib/config.php
232 function fix_configs() {
233     global $FieldSeparator, $charset, $WikiNameRegexp, $KeywordLinkRegexp;
234     global $DisabledActions, $HTTP_SERVER_VARS, $DBParams, $LANG;
235
236     // "\x80"-"\x9f" (and "\x00" - "\x1f") are non-printing control
237     // chars in iso-8859-*
238     // $FieldSeparator = "\263"; //this is a superscript 3 in ISO-8859-1.
239     // $FieldSeparator = "\xFF"; // this byte should never appear in utf-8
240     // FIXME: get rid of constant. pref is dynamic and language specific
241     $charset = CHARSET;
242     if (isset($GLOBALS['LANG']) and in_array($GLOBALS['LANG'],array('ja','zh')))
243         $charset = 'utf-8';
244     if (strtolower($charset) == 'utf-8')
245         $FieldSeparator = "\xFF";
246     else
247         $FieldSeparator = "\x81";
248
249     if (!defined('DEFAULT_LANGUAGE'))
250         define('DEFAULT_LANGUAGE', 'en');
251
252     //
253     // Set up (possibly fake) gettext()
254     //
255     if (!function_exists ('bindtextdomain')) {
256         $locale = array();
257
258         function gettext ($text) { 
259             global $locale;
260             if (!empty ($locale[$text]))
261                 return $locale[$text];
262             return $text;
263         }
264
265         function _ ($text) {
266             return gettext($text);
267         }
268     }
269     else {
270         // Working around really weird gettext problems: (4.3.2, 4.3.6 win)
271         // bindtextdomain() returns the current domain path.
272         // 1. If the script is not index.php but something like "de", on a different path
273         //    then bindtextdomain() fails, but after chdir to the correct path it will work okay.
274         // 2. But the weird error "Undefined variable: bindtextdomain" is generated then.
275         $bindtextdomain_path = FindFile("locale", false, true);
276         if (isWindows())
277             $bindtextdomain_path = str_replace("/","\\",$bindtextdomain_path);
278         $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain);
279         if ($bindtextdomain_real != $bindtextdomain_path) {
280             // this will happen with virtual_paths. chdir and try again.
281             chdir($bindtextdomain_path);
282             $bindtextdomain_real = @bindtextdomain("phpwiki", $bindtextdomain);
283         }
284         textdomain("phpwiki");
285         if ($bindtextdomain_real != $bindtextdomain_path) { // change back
286             chdir($bindtextdomain_real . (isWindows() ? "\\.." : "/.."));
287         }
288     }
289
290     $WikiNameRegexp = pcre_fix_posix_classes($WikiNameRegexp);
291     $KeywordLinkRegexp = pcre_fix_posix_classes($KeywordLinkRegexp);
292
293     //////////////////////////////////////////////////////////////////
294     // Autodetect URL settings:
295     //
296     if (!defined('SERVER_NAME')) define('SERVER_NAME', $HTTP_SERVER_VARS['SERVER_NAME']);
297     if (!defined('SERVER_PORT')) define('SERVER_PORT', $HTTP_SERVER_VARS['SERVER_PORT']);
298     if (!defined('SERVER_PROTOCOL')) {
299         if (empty($HTTP_SERVER_VARS['HTTPS']) || $HTTP_SERVER_VARS['HTTPS'] == 'off')
300             define('SERVER_PROTOCOL', 'http');
301         else
302             define('SERVER_PROTOCOL', 'https');
303     }
304
305     if (!defined('SCRIPT_NAME'))
306         define('SCRIPT_NAME', deduce_script_name());
307
308     if (!defined('USE_PATH_INFO')) {
309             /*
310              * If SCRIPT_NAME does not look like php source file,
311              * or user cgi we assume that php is getting run by an
312              * action handler in /cgi-bin.  In this case,
313              * I think there is no way to get Apache to pass
314              * useful PATH_INFO to the php script (PATH_INFO
315              * is used to the the php interpreter where the
316              * php script is...)
317              */
318             switch (php_sapi_name()) {
319             case 'apache':
320             case 'apache2handler':
321                 define('USE_PATH_INFO', true);
322                 break;
323             case 'cgi':
324             case 'apache2filter':
325                 define('USE_PATH_INFO', false);
326                 break;
327             default:
328                 define('USE_PATH_INFO', ereg('\.(php3?|cgi)$', SCRIPT_NAME));
329                 break;
330             }
331         }
332      
333     // If user has not defined DATA_PATH, we want to use relative URLs.
334     if (!defined('DATA_PATH') && USE_PATH_INFO)
335         define('DATA_PATH', '..');
336
337     // If user has not defined PHPWIKI_DIR, and we need it
338     if (!defined('PHPWIKI_DIR') and !file_exists("themes/default")) {
339         $themes_dir = FindFile("themes");
340         define('PHPWIKI_DIR', dirname($themes_dir));
341     }
342         
343     if (!defined('VIRTUAL_PATH')) {
344         // We'd like to auto-detect when the cases where apaches
345         // 'Action' directive (or similar means) is used to
346         // redirect page requests to a cgi-handler.
347         //
348         // In cases like this, requests for e.g. /wiki/HomePage
349         // get redirected to a cgi-script called, say,
350         // /path/to/wiki/index.php.  The script gets all
351         // of /wiki/HomePage as it's PATH_INFO.
352         //
353         // The problem is:
354         //   How to detect when this has happened reliably?
355         //   How to pick out the "virtual path" (in this case '/wiki')?
356         //
357         // (Another time an redirect might occur is to a DirectoryIndex
358         // -- the requested URI is '/wikidir/', the request gets
359         // passed to '/wikidir/index.php'.  In this case, the
360         // proper VIRTUAL_PATH is '/wikidir/index.php', since the
361         // pages will appear at e.g. '/wikidir/index.php/HomePage'.
362         //
363
364         $REDIRECT_URL = &$HTTP_SERVER_VARS['REDIRECT_URL'];
365         if (USE_PATH_INFO and isset($REDIRECT_URL)
366             and ! IsProbablyRedirectToIndex()) {
367             // FIXME: This is a hack, and won't work if the requested
368             // pagename has a slash in it.
369             define('VIRTUAL_PATH', dirname($REDIRECT_URL . 'x'));
370         } else {
371             define('VIRTUAL_PATH', SCRIPT_NAME);
372         }
373     }
374
375     if (SERVER_PORT
376         && SERVER_PORT != (SERVER_PROTOCOL == 'https' ? 443 : 80)) {
377         define('SERVER_URL',
378                SERVER_PROTOCOL . '://' . SERVER_NAME . ':' . SERVER_PORT);
379     }
380     else {
381         define('SERVER_URL',
382                SERVER_PROTOCOL . '://' . SERVER_NAME);
383     }
384
385     if (VIRTUAL_PATH != SCRIPT_NAME) {
386         // Apache action handlers are used.
387         define('PATH_INFO_PREFIX', VIRTUAL_PATH . '/');
388     }
389     else
390         define('PATH_INFO_PREFIX', '/');
391
392
393     define('PHPWIKI_BASE_URL',
394            SERVER_URL . (USE_PATH_INFO ? VIRTUAL_PATH . '/' : SCRIPT_NAME));
395
396     //////////////////////////////////////////////////////////////////
397     // Select database
398     //
399     if (empty($DBParams['dbtype']))
400         $DBParams['dbtype'] = 'dba';
401
402     if (!defined('THEME'))
403         define('THEME', 'default');
404
405     update_locale(isset($LANG) ? $LANG : DEFAULT_LANGUAGE);
406
407     if (!defined('WIKI_NAME'))
408         define('WIKI_NAME', _("An unnamed PhpWiki"));
409
410     if (!defined('HOME_PAGE'))
411         define('HOME_PAGE', _("HomePage"));
412
413     // FIXME: delete
414     // Access log
415     if (!defined('ACCESS_LOG'))
416         define('ACCESS_LOG', '');
417
418     // FIXME: delete
419     // Get remote host name, if apache hasn't done it for us
420     if (empty($HTTP_SERVER_VARS['REMOTE_HOST']) && ENABLE_REVERSE_DNS)
421         $HTTP_SERVER_VARS['REMOTE_HOST'] = gethostbyaddr($HTTP_SERVER_VARS['REMOTE_ADDR']);
422
423     // check whether the crypt() function is needed and present
424     if (defined('ENCRYPTED_PASSWD') && !function_exists('crypt')) {
425         $error = sprintf(_("Encrypted passwords cannot be used: %s."),
426                          "'function crypt()' not available in this version of php");
427         trigger_error($error);
428     }
429
430     if (!defined('ADMIN_PASSWD') or ADMIN_PASSWD == '')
431         trigger_error(_("The admin password cannot be empty. Please update your /index.php"));
432
433     if (defined('USE_DB_SESSION') and USE_DB_SESSION) {
434         if (! $DBParams['db_session_table'] ) {
435             trigger_error(_("Empty db_session_table. Turn USE_DB_SESSION off or define the table name."), 
436                           E_USER_ERROR);
437             // this is flawed. constants cannot be changed.
438             define('USE_DB_SESSION',false);
439         }
440     } else {
441         // default: true (since v1.3.8)
442         if (!defined('USE_DB_SESSION'))
443             define('USE_DB_SESSION',true);
444     }
445     // legacy:
446     if (!defined('ENABLE_USER_NEW')) define('ENABLE_USER_NEW',true);
447     if (!defined('ALLOW_USER_LOGIN'))
448         define('ALLOW_USER_LOGIN', defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
449     if (!defined('ALLOW_ANON_USER')) define('ALLOW_ANON_USER', true); 
450     if (!defined('ALLOW_ANON_EDIT')) define('ALLOW_ANON_EDIT', false); 
451     if (!defined('REQUIRE_SIGNIN_BEFORE_EDIT')) define('REQUIRE_SIGNIN_BEFORE_EDIT', ! ALLOW_ANON_EDIT);
452     if (!defined('ALLOW_BOGO_LOGIN')) define('ALLOW_BOGO_LOGIN', true);
453
454     if (ALLOW_USER_LOGIN and !empty($DBAuthParams) and empty($DBAuthParams['auth_dsn'])) {
455         if (isset($DBParams['dsn']))
456             $DBAuthParams['auth_dsn'] = $DBParams['dsn'];
457     }
458
459 }
460
461
462 // $Log: not supported by cvs2svn $
463 // Revision 1.6  2004/04/20 18:10:27  rurban
464 // config refactoring:
465 //   FileFinder is needed for WikiFarm scripts calling index.php
466 //   config run-time calls moved to lib/IniConfig.php:fix_configs()
467 //   added PHPWIKI_DIR smart-detection code (Theme finder)
468 //   moved FileFind to lib/FileFinder.php
469 //   cleaned lib/config.php
470 //
471 // Revision 1.5  2004/04/20 17:21:57  rurban
472 // WikiFarm code: honor predefined constants
473 //
474 // Revision 1.4  2004/04/20 17:08:19  rurban
475 // Some IniConfig fixes: prepend our private lib/pear dir
476 //   switch from " to ' in the auth statements
477 //   use error handling.
478 // WikiUserNew changes for the new "'$variable'" syntax
479 //   in the statements
480 // TODO: optimization to put config vars into the session.
481 //
482
483 // (c-file-style: "gnu")
484 // Local Variables:
485 // mode: php
486 // tab-width: 8
487 // c-basic-offset: 4
488 // c-hanging-comment-ender-p: nil
489 // indent-tabs-mode: nil
490 // End:   
491 ?>