d7c27d8171a65696ae5ae151aca6efafe120b31c
[mailer.git] / inc / config-functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 02/28/2009 *
4  * ===============                              Last change: 02/28/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : config-functions.php                             *
8  * -------------------------------------------------------------------- *
9  * Short description : Many non-MySQL functions (also file access)      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // Init the config array
45 function initConfig () {
46         // Init not if already found
47         if (isConfigLoaded()) {
48                 // Already initialized
49                 debug_report_bug(sprintf("[%s:%s] Configuration is already initialized.", __FUNCTION__, __LINE__));
50         } // END - if
51
52         // Set a minimum of configuration, required to by-pass some error triggers in getConfig()
53         $GLOBALS['config'] = array(
54                 'code_length'         => 0,
55                 'patch_level'         => 0,
56                 'last_update'         => time(),
57                 'activate_xchange'    => 100,
58                 'enable_mod_title'    => 'Y',
59                 'update_filter_usage' => 'N',
60                 'ADMIN_REGISTERED'    => 'N',
61                 'MXCHANGE_INSTALLED'  => 'N',
62                 'DEFAULT_LANG'        => 'de',
63                 'DEBUG_MODE'          => 'N',
64                 'DEBUG_RESET'         => 'N',
65                 'DEBUG_MONTHLY'       => 'N',
66                 'DEBUG_WEEKLY'        => 'N',
67                 'DEBUG_REGEX'         => 'N',
68                 'ADMIN_REGISTERED'    => 'N',
69                 'sql_count'           => 0,
70                 'sql_time'            => 0,
71                 'num_templates'       => 0,
72                 'default_theme'       => 'default',
73                 'verbose_sql'         => 'Y',
74                 'def_refid'           => 0,
75                 'ENABLE_BACKLINK'     => 'Y',
76                 'display_debug_sqls'  => 'N',
77                 // Keep session_save_path to fall-back to php.ini setting
78                 'session_save_path'   => '',
79                 // For installation phase:
80                 'SMTP_HOSTNAME'       => '',
81                 'SMTP_USER'           => '',
82                 'SMTP_PASSWORD'       => '',
83                 'MT_WORD'             => '{--DEFAULT_MT_WORD--}',
84         );
85 }
86
87 // Getter for $GLOBALS['config'] entries
88 function getConfig ($configEntry) {
89         // Default value
90         $value = null;
91
92         // Is the entry there?
93         if (!isset($GLOBALS['config'][$configEntry])) {
94                 // Raise an error of missing entries
95                 debug_report_bug(sprintf("[%s:%s] Configuration entry <em>%s</em> is missing.",
96                         __FUNCTION__,
97                         __LINE__,
98                         $configEntry
99                 ));
100         } // END - if
101
102         // Return it
103         return $GLOBALS['config'][$configEntry];
104 }
105
106 // Setter for $GLOBALS['config'] entries
107 function setConfigEntry ($configEntry, $value) {
108         // Just set it (unsecured won't hurt?)
109         $GLOBALS['config'][$configEntry] = $value;
110 }
111
112 // Checks wether the given config entry is set
113 function isConfigEntrySet ($configEntry) {
114         return (isset($GLOBALS['config'][$configEntry]));
115 }
116
117 // Merges $GLOBALS['config'] with data in given array
118 function mergeConfig ($newConfig) {
119         $GLOBALS['config'] = merge_array(getConfigArray(), $newConfig);
120 }
121
122 // Increment or init with given value or 1 as default the given config entry
123 function incrementConfigEntry ($configEntry, $value=1) {
124         // Increment it if set or init it with 1
125         if (getConfig($configEntry) > 0) {
126                 $GLOBALS['config'][$configEntry] += $value;
127         } else {
128                 $GLOBALS['config'][$configEntry] = $value;
129         }
130 }
131
132 // Checks wether the configuration array is set so the config is loaded
133 function isConfigLoaded () {
134         // Check all
135         return ((isset($GLOBALS['config'])) && (is_array($GLOBALS['config'])) && (count($GLOBALS['config']) > 0));
136 }
137
138 // Getter for whole $GLOBALS['config'] array
139 function getConfigArray () {
140         // Default is null
141         $return = null;
142
143         // Is the config set?
144         if (isConfigLoaded()) {
145                 // Then use it
146                 $return = $GLOBALS['config'];
147         } // END - if
148
149         // Return result
150         return $return;
151 }
152
153 // Updates an old inc/config.php to a inc/cache/config-local.php file
154 function updateOldConfigFile () {
155         // Watch out for these lines and execute them as single command
156         // @TODO Make this all better... :-/
157         $watchLines = array(
158                 'SITE_KEY'           => 'SITE_KEY',
159                 'DEFAULT_LANG'       => 'DEFAULT_LANG',
160                 'warn_no_pass'       => 'WARN_NO_PASS',
161                 'WRITE_FOOTER'       => 'WRITE_FOOTER',
162                 'OUTPUT_MODE'        => 'OUTPUT_MODE',
163                 'MAIN_TITLE'         => 'MAIN_TITLE',
164                 'SLOGAN'             => 'SLOGAN',
165                 'WEBMASTER'          => 'WEBMASTER',
166                 'mxchange_installed' => 'MXCHANGE_INSTALLED',
167                 'admin_registered'   => 'ADMIN_REGISTERED',
168                 '_MYSQL_PREFIX'      => '_MYSQL_PREFIX',
169                 '_TABLE_TYPE'        => '_TABLE_TYPE',
170                 '_DB_TYPE'           => '_DB_TYPE',
171                 'SMTP_HOSTNAME'      => 'SMTP_HOSTNAME',
172                 'SMTP_USER'           => 'SMTP_USER',
173                 'SMTP_PASSWORD'      => 'SMTP_PASSWORD',
174                 'ENABLE_BACKLINK'    => 'ENABLE_BACKLINK',
175                 'MAIN_TITLE'         => 'MAIN_TITLE',
176                 'SLOGAN'             => 'SLOGAN',
177                 'WEBMASTER'          => 'WEBMASTER',
178                 'PATH'               => 'PATH',
179                 'URL'                => 'URL',
180         );
181
182         // Make these lower-case! (damn stupid code...)
183         $lowerCase = array('WARN_NO_PASS', 'MXCHANGE_INSTALLED', 'ADMIN_REGISTERED');
184
185         // Special comments...
186         $comments = array(
187                 'WARN_NO_PASS'       => 'NULLPASS-WARNING',
188                 'MXCHANGE_INSTALLED' => 'INSTALLED',
189                 'ADMIN_REGISTERED'   => 'ADMIN-SETUP',
190                 '_MYSQL_PREFIX'      => 'MYSQL-PREFIX',
191                 '_TABLE_TYPE'        => 'TABLE-TYPE',
192                 '_DB_TYPE'           => 'DATABASE-TYPE',
193                 'ENABLE_BACKLINK'    => 'BACKLINK',
194                 'host'               => 'MYSQL-HOST',
195                 'dbase'              => 'MYSQL-DBASE',
196                 'login'              => 'MYSQL-LOGIN',
197                 'password'           => 'MYSQL-PASSWORD'
198         );
199
200         // Copy template to new file destionation
201         copyFileVerified(getConfig('PATH') . 'inc/config-local.php.dist', getConfig('CACHE_PATH') . 'config-local.php', 0644);
202
203         // First of all, load the old one!
204         $oldConfig = explode("\n", readFromFile(getConfig('PATH') . 'inc/config.php'));
205
206         // Now, analyze every entry
207         $done = array();
208         foreach ($oldConfig as $line) {
209                 // Check all watch lines
210                 foreach ($watchLines as $old => $new) {
211                         // Add define() command around old one
212                         $old = "define('" . $old . "',";
213
214                         // Is the line found?
215                         if ((substr($line, 0, strlen($old)) == $old) && (!isset($done[$old]))) {
216                                 // Entry found!
217                                 //* DEBUG: */ outputHtml(htmlentities($line) . " - FOUND!<br />");
218
219                                 // Eval the line...
220                                 eval($line);
221
222                                 // Setting config entry is new default behaviour!
223                                 $function = 'setConfigEntry';
224
225                                 // Default comment
226                                 $comment = str_replace('_', '-', $new);
227
228                                 // Do we have a special comment?
229                                 if (isset($comments[$new])) {
230                                         // Then use it
231                                         $comment = $comments[$new];
232                                 } // END - if
233
234                                 // Do we need to make $new lowercase?
235                                 $oldNew = $new;
236                                 if (in_array($new, $lowerCase)) {
237                                         // Then do so... :)
238                                         $new = strtolower($new);
239                                 } // END - if
240
241                                 /// ... and write it to the new config
242                                 //* DEBUG: */ outputHtml('function=' . $function . ',new=' . $new . ',comment=' . $comment . "<br />");
243                                 changeDataInFile(getConfig('CACHE_PATH') . 'config-local.php', $comment, $function . "('" . $oldNew . "', \"", "\");", constant($new), 0);
244                                 //* DEBUG: */ outputHtml("CHANGED!<br />");
245
246                                 // Mark it as done
247                                 $done[$old] = 1;
248                         } // END - if
249                 } // END - foreach
250         } // END - foreach
251
252         // By default the old array $MySQL was not found
253         $found = false;
254
255         // Analyze every entry again for the MySQL configuration
256         foreach ($oldConfig as $line) {
257                 // Trim spaces
258                 $line = trim($line);
259
260                 // Is the $MySQL found?
261                 if (substr($line, 0, 6) == "\$MySQL") {
262                         // Okay found!
263                         $found = true;
264                 } elseif ($found === true) {
265                         // Now check this row
266                         if (substr($line, 0, 2) == ');') {
267                                 // MySQL array is closed so stop looking for it
268                                 break;
269                         } elseif (substr($line, 0, 2) == '//') {
270                                 // Skip this line
271                                 continue;
272                         }
273
274                         // Debug output only
275                         //* DEBUG: */ outputHtml(htmlentities($line) . " - MySQL!<br />");
276
277                         // Split parts so we can check them and prepare them
278                         $parts = explode('=>', $line);
279                         $key = substr(trim($parts[0]), 1, -1); $value = substr(trim($parts[1]), 1, -2);
280
281                         // We can now save the right part in new config file
282                         changeDataInFile(getConfig('CACHE_PATH') . 'config-local.php', $comments[$key], "       '".$key."'     => \"", "\",", $value, 0);
283                 }
284         } // END - foreach
285
286         // Finally remove old config file
287         removeFile(getConfig('PATH') . 'inc/config.php');
288
289         // Redirect to same URL to reload our new config
290         redirectToUrl(getRequestUri());
291 }
292
293 // Update config entries
294 function updateConfiguration ($entries, $values, $updateMode='') {
295         // Do not update config in CSS mode
296         if ((getOutputMode() == '1') || (getOutputMode() == -1) || (isInstallationPhase())) {
297                 return;
298         } // END - if
299
300         // Do we have multiple entries?
301         if (is_array($entries)) {
302                 // Walk through all
303                 $all = '';
304                 foreach ($entries as $idx => $entry) {
305                         // Update mode set?
306                         if (!empty($updateMode)) {
307                                 // Update entry
308                                 $all .= sprintf("`%s`=`%s`%s%s,", $entry, $entry, $updateMode, (float)$values[$idx]);
309                         } else {
310                                 // Check if string or number
311                                 if (($values[$idx] + 0) === $values[$idx]) {
312                                         // Number detected
313                                         $all .= sprintf("`%s`=%s,", $entry, (float)$values[$idx]);
314                                 } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
315                                         // Function UNIX_TIMESTAMP() detected
316                                         $all .= sprintf("`%s`=%s,", $entry, $values[$idx]);
317                                 } else {
318                                         // String detected
319                                         $all .= sprintf("`%s`='%s',", $entry, SQL_ESCAPE($values[$idx]));
320                                 }
321
322                                 // Set it in config as well
323                                 setConfigEntry($entry, $values[$idx]);
324                         }
325                 } // END - foreach
326
327                 // Remove last comma
328                 $entries = substr($all, 0, -1);
329         } elseif (!empty($updateMode)) {
330                 // Update mode set
331                 // @TODO Find a way for updating configuration here
332                 $entries .= sprintf("=%s%s%s", $entries, $updateMode, (float)$values);
333         } else {
334                 // Set it in config first
335                 setConfigEntry($entries, $values);
336
337                 // Regular entry to update
338                 $entries .= sprintf("='%s'", SQL_ESCAPE($values));
339         }
340
341         // Run database update
342         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "entries={$entries}");
343         SQL_QUERY("UPDATE `{?_MYSQL_PREFIX?}_config` SET ".$entries." WHERE `config`=0 LIMIT 1", __FUNCTION__, __LINE__);
344         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):entries={$entries},affectedRows={$affectedRows}<br />");
345
346         // Rebuild cache
347         rebuildCacheFile('config', 'config');
348 }
349
350 // Filter for loading configuration
351 function FILTER_LOAD_CONFIGURATION ($no = '0') {
352         // Check for cache extension, cache-array and if the requested configuration is in cache
353         if ((isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
354                 // Load config from cache
355                 //* DEBUG: */ outputHtml(gettype($GLOBALS['cache_array']['config'][$no])."<br />");
356                 mergeConfig($GLOBALS['cache_array']['config'][$no]);
357                 //foreach ($GLOBALS['cache_array']['config'][$no] as $key => $value) {
358                 //      setConfigEntry($key, $value);
359                 //} // END - foreach
360
361                 // Count cache hits if exists
362                 if ((isStatsEntrySet('cache_hits')) && (isExtensionActive('cache'))) {
363                         incrementStatsEntry('cache_hits');
364                 } // END - if
365         } elseif ((!isExtensionActive('cache')) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
366                 // Load config from DB
367                 $result_config = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_config` WHERE config=%d LIMIT 1",
368                         array(bigintval($no)), __FUNCTION__, __LINE__);
369
370                 // Is the config there?
371                 if (SQL_NUMROWS($result_config) == 1) {
372                         // Get config from database
373                         mergeConfig(SQL_FETCHARRAY($result_config));
374                 } // END - if
375
376                 // Free result
377                 SQL_FREERESULT($result_config);
378
379                 // Remember this config in the array
380                 $GLOBALS['cache_array']['config'][$no] = getConfigArray();
381         }
382 }
383
384 // [EOF]
385 ?>