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