Added separate debugging of 'hourly' reset
[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_HOURLY'        => 'N',
59                 // 'DEBUG_RESET'         => 'N',
60                 // 'DEBUG_MONTHLY'       => 'N',
61                 // 'DEBUG_WEEKLY'        => 'N',
62                 // 'DEBUG_REGEX'         => 'N',
63                 // 'ADMIN_REGISTERED'    => 'N',
64                 // 'verbose_sql'         => 'Y',
65                 // For installation phase:
66                 'SMTP_HOSTNAME'       => '',
67                 'SMTP_USER'           => '',
68                 'SMTP_PASSWORD'       => '',
69                 'MT_WORD'             => '{--DEFAULT_MT_WORD--}',
70         );
71 }
72
73 // Getter for $GLOBALS['config'] entries
74 function getConfig ($configEntry) {
75         // Is the entry there?
76         if (!isConfigEntrySet($configEntry)) {
77                 // Raise an error of missing entries
78                 reportBug(__FUNCTION__, __LINE__, sprintf("Configuration entry <span class=\"data\">%s</span> is missing.", $configEntry));
79         } // END - if
80
81         // Return it
82         //* DEBUG: */ error_log(__FUNCTION__.'['.__LINE__.':] '.$configEntry.'='.$GLOBALS['config'][$configEntry]);
83         return $GLOBALS['config'][$configEntry];
84 }
85
86 // Setter for $GLOBALS['config'] entries
87 function setConfigEntry ($configEntry, $value) {
88         // Just set it (unsecured won't hurt?)
89         $GLOBALS['config'][$configEntry] = $value;
90
91         // Remove cache
92         removeGlobalCache($configEntry);
93 }
94
95 // Removes entry in $GLOBALS
96 function removeGlobalCache ($configEntry) {
97         // Generate key
98         $key = 'get' . capitalizeUnderscoreString($configEntry);
99
100         // Remove it
101         unset($GLOBALS[$key]);
102 }
103
104 // Checks whether the given config entry is set
105 function isConfigEntrySet ($configEntry) {
106         //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . $configEntry . '=' . intval(isset($GLOBALS['config'][$configEntry])));
107         return ((isset($GLOBALS['config'][$configEntry])) || (array_key_exists($configEntry, $GLOBALS['config'])));
108 }
109
110 // Merges $GLOBALS['config'] with data in given array
111 function mergeConfig ($newConfig) {
112         // Merge current configuration with new one
113         $GLOBALS['config'] = merge_array(getConfigArray(), $newConfig);
114 }
115
116 // Increment or init with given value or 1 as default the given config entry
117 function incrementConfigEntry ($configEntry, $value=1) {
118         // Increment it if set or init it with $value
119         if (isConfigEntrySet($configEntry)) {
120                 $GLOBALS['config'][$configEntry] += $value;
121         } else {
122                 $GLOBALS['config'][$configEntry] = $value;
123         }
124 }
125
126 // Checks whether the configuration array is set so the config is loaded
127 function isConfigurationLoaded () {
128         // Check all
129         return (isset($GLOBALS['config']['config']));
130 }
131
132 // Getter for whole $GLOBALS['config'] array
133 function getConfigArray () {
134         // Default is null
135         $return = array();
136
137         // Is the config set?
138         if (isset($GLOBALS['config'])) {
139                 // Then use it
140                 $return = $GLOBALS['config'];
141         } // END - if
142
143         // Return result
144         return $return;
145 }
146
147 // Updates an old inc/config.php to a inc/cache/config-local.php file
148 function updateOldConfigFile () {
149         // Watch out for these lines and execute them as single command
150         // @TODO Make this all better... :-/
151         $watchLines = array(
152                 'SITE_KEY'         => 'SITE_KEY',
153                 'DEFAULT_LANG'     => 'DEFAULT_LANG',
154                 'warn_no_pass'     => 'WARN_NO_PASS',
155                 'WRITE_FOOTER'     => 'WRITE_FOOTER',
156                 'OUTPUT_MODE'      => 'OUTPUT_MODE',
157                 'MAIN_TITLE'       => 'MAIN_TITLE',
158                 'SLOGAN'           => 'SLOGAN',
159                 'WEBMASTER'        => 'WEBMASTER',
160                 'mailer_installed' => 'MAILER_INSTALLED',
161                 'admin_registered' => 'ADMIN_REGISTERED',
162                 '_MYSQL_PREFIX'    => '_MYSQL_PREFIX',
163                 '_TABLE_TYPE'      => '_TABLE_TYPE',
164                 '_DB_TYPE'         => '_DB_TYPE',
165                 'SMTP_HOSTNAME'    => 'SMTP_HOSTNAME',
166                 'SMTP_USER'        => 'SMTP_USER',
167                 'SMTP_PASSWORD'    => 'SMTP_PASSWORD',
168                 'ENABLE_BACKLINK'  => 'ENABLE_BACKLINK',
169                 'MAIN_TITLE'       => 'MAIN_TITLE',
170                 'SLOGAN'           => 'SLOGAN',
171                 'WEBMASTER'        => 'WEBMASTER',
172                 'PATH'             => 'PATH',
173                 'URL'              => 'URL',
174         );
175
176         // Make these lower-case! (damn stupid code...)
177         $lowerCase = array('WARN_NO_PASS', 'MAILER_INSTALLED', 'ADMIN_REGISTERED');
178
179         // Special comments...
180         $comments = array(
181                 'WARN_NO_PASS'       => 'NULLPASS-WARNING',
182                 'MAILER_INSTALLED  ' => 'INSTALLED',
183                 'ADMIN_REGISTERED'   => 'ADMIN-SETUP',
184                 '_MYSQL_PREFIX'      => 'MYSQL-PREFIX',
185                 '_TABLE_TYPE'        => 'TABLE-TYPE',
186                 '_DB_TYPE'           => 'DATABASE-TYPE',
187                 'ENABLE_BACKLINK'    => 'BACKLINK',
188                 'host'               => 'MYSQL-HOST',
189                 'dbase'              => 'MYSQL-DBASE',
190                 'login'              => 'MYSQL-LOGIN',
191                 'password'           => 'MYSQL-PASSWORD'
192         );
193
194         // Copy template to new file destionation
195         copyFileVerified(getPath() . 'inc/config-local.php.dist', getCachePath() . 'config-local.php', 0644);
196
197         // First of all, load the old one!
198         $oldConfig = explode(PHP_EOL, readFromFile(getPath() . 'inc/config.php'));
199
200         // Now, analyze every entry
201         $done = array();
202         foreach ($oldConfig as $line) {
203                 // Check all watch lines
204                 foreach ($watchLines as $old => $new) {
205                         // Add define() command around old one
206                         $old = "define('" . $old . "',";
207
208                         // Is the line found?
209                         if ((substr($line, 0, strlen($old)) == $old) && (!isset($done[$old]))) {
210                                 // Entry found
211                                 //* DEBUG: */ debugOutput(secureString($line) . ' - FOUND!');
212
213                                 // Eval the line...
214                                 eval($line);
215
216                                 // Setting config entry is new default behaviour!
217                                 $function = 'setConfigEntry';
218
219                                 // Default comment
220                                 $comment = str_replace('_', '-', $new);
221
222                                 // Is there a special comment?
223                                 if (isset($comments[$new])) {
224                                         // Then use it
225                                         $comment = $comments[$new];
226                                 } // END - if
227
228                                 // Does $new needs to be lower-case?
229                                 $oldNew = $new;
230                                 if (in_array($new, $lowerCase)) {
231                                         // Then do so... :)
232                                         $new = strtolower($new);
233                                 } // END - if
234
235                                 // ... and write it to the new config
236                                 //* DEBUG: */ debugOutput('function=' . $function . ',new=' . $new . ',comment=' . $comment);
237                                 changeDataInInclude(getCachePath() . 'config-local.php', $comment, $function . "('" . $oldNew . "', \"", '");', constant($new), 0);
238                                 //* DEBUG: */ debugOutput('CHANGED!');
239
240                                 // Mark it as done
241                                 $done[$old] = 1;
242                         } // END - if
243                 } // END - foreach
244         } // END - foreach
245
246         // By default the old array $MySQL was not found
247         $found = FALSE;
248
249         // Analyze every entry again for the MySQL configuration
250         foreach ($oldConfig as $line) {
251                 // Trim spaces
252                 $line = trim($line);
253
254                 // Is the $MySQL found?
255                 if (substr($line, 0, 6) == '$MySQL') {
256                         // Okay, found
257                         $found = TRUE;
258                 } elseif ($found === TRUE) {
259                         // Now check this row
260                         if (substr($line, 0, 2) == ');') {
261                                 // MySQL array is closed so stop looking for it
262                                 break;
263                         } elseif (substr($line, 0, 2) == '//') {
264                                 // Skip this line
265                                 continue;
266                         }
267
268                         // Debug output only
269                         //* DEBUG: */ debugOutput(secureString($line) . ' - MySQL!');
270
271                         // Split parts so we can check them and prepare them
272                         $parts = explode('=>', $line);
273                         $key = substr(trim($parts[0]), 1, -1); $value = substr(trim($parts[1]), 1, -2);
274
275                         // We can now save the right part in new config file
276                         changeDataInInclude(getCachePath() . 'config-local.php', $comments[$key], "     '".$key."'     => \"", '",', $value, 0);
277                 }
278         } // END - foreach
279
280         // Finally remove old config file
281         removeFile(getPath() . 'inc/config.php');
282
283         // Redirect to same URL to reload our new config
284         redirectToUrl(getRequestUri());
285 }
286
287 // Update config entries
288 function updateConfiguration ($entries, $values, $updateMode = '', $config = '0') {
289         // Do not update config in CSS mode
290         if ((isCssOutputMode()) || (isRawOutputMode()) || (isInstallationPhase())) {
291                 // This logger line may be very noisy
292                 //* 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()));
293                 return;
294         } // END - if
295
296         // Default is empty SQL
297         $SQL = '';
298
299         // Is there multiple entries?
300         if (is_array($entries)) {
301                 // Walk through all
302                 foreach ($entries as $idx => $entry) {
303                         // Update mode set?
304                         if (!empty($updateMode)) {
305                                 // Update entry
306                                 $SQL .= sprintf("`%s`=`%s`%s%s,", $entry, $entry, $updateMode, (float) $values[$idx]);
307                         } else {
308                                 // Check if string or number but no array
309                                 if (is_array($values[$idx])) {
310                                         // Arrays must be fixed...
311                                         reportBug(__FUNCTION__, __LINE__, 'values[' . $idx . '] should not be an array! Content=<pre>'.print_r($values[$idx], TRUE).'</pre>');
312                                 } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
313                                         // Function UNIX_TIMESTAMP() detected
314                                         $SQL .= sprintf("`%s`=UNIX_TIMESTAMP(),", $entry);
315
316                                         // Set timestamp in array as well
317                                         setConfigEntry($entry, time());
318                                 } elseif (!empty($updateMode)) {
319                                         // Is the value zero?
320                                         if ($values[$idx] == '0') {
321                                                 // Then skip it
322                                                 continue;
323                                         } // END - if
324
325                                         // Update mode set
326                                         // @TODO Call setConfigEntry() somehow
327                                         $SQL .= $entries = sprintf("`%s`=`%s`%s%s", $entry, $entry, $updateMode, (float) $values[$idx]);
328                                 } elseif (($values[$idx] + 0) === $values[$idx]) {
329                                         // Number detected
330                                         $SQL .= sprintf("`%s`=%s,", $entry, (float) $values[$idx]);
331
332                                         // Set it in config as well
333                                         setConfigEntry($entry, $values[$idx]);
334                                 } else {
335                                         // String detected
336                                         $SQL .= sprintf("`%s`='%s',", $entry, SQL_ESCAPE($values[$idx]));
337
338                                         // Set it in config as well
339                                         setConfigEntry($entry, $values[$idx]);
340                                 }
341                         }
342                 } // END - foreach
343
344                 // Remove last comma
345                 $SQL = substr($SQL, 0, -1);
346         } elseif (!empty($updateMode)) {
347                 // Is the value zero?
348                 if ($values == '0') {
349                         // Then skip it
350                         continue;
351                 } // END - if
352
353                 // Update mode set
354                 // @TODO Call setConfigEntry() somehow
355                 $SQL = sprintf("`%s`=`%s`%s%s", $entries, $entries, $updateMode, (float) $values);
356         } elseif (($values + 0) === $values) {
357                 // Number detected
358                 $SQL = sprintf("`%s`=%s", $entries, (float) $values);
359
360                 // Set it in config first
361                 setConfigEntry($entries, (float) $values);
362         } elseif ($values == 'UNIX_TIMESTAMP()') {
363                 // Function UNIX_TIMESTAMP() detected
364                 $SQL = sprintf("`%s`=UNIX_TIMESTAMP()", $entries);
365
366                 // Set timestamp in array as well
367                 setConfigEntry($entries, time());
368         } else {
369                 // Regular entry to update
370                 $SQL = sprintf("`%s`='%s'", $entries, SQL_ESCAPE($values));
371
372                 // Set it in config as well
373                 setConfigEntry($entries, SQL_ESCAPE($values));
374         }
375
376         // Run database update
377         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL);
378         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_config` SET ".$SQL." WHERE `config`=%s LIMIT 1",
379                         array(bigintval($config)), __FUNCTION__, __LINE__);
380         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL . ',affectedRows=' . SQL_AFFECTEDROWS());
381
382         // Rebuild cache
383         rebuildCache('config', 'config');
384 }
385
386 // Filter for loading configuration
387 function FILTER_LOAD_CONFIGURATION ($no = '0') {
388         // Is installation phase?
389         if (isInstallationPhase()) {
390                 // Then don't load any configuration
391                 return;
392         } // END - if
393
394         // Is the value null, it comes from the 'init' filter chain
395         if (is_null($no)) {
396                 $no = '0';
397         } // END - if
398
399         // Check for cache extension, cache-array and if the requested configuration is in cache
400         if ((isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
401                 // Load config from cache
402                 mergeConfig($GLOBALS['cache_array']['config'][$no]);
403
404                 // Count cache hits 
405                 incrementStatsEntry('cache_hits');
406         } elseif ((!isExtensionActive('cache')) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
407                 // Load config from DB
408                 $result_config = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_config` WHERE `config`='%s' LIMIT 1",
409                         array(bigintval($no)), __FUNCTION__, __LINE__);
410
411                 // Is the config there?
412                 if (SQL_NUMROWS($result_config) == 1) {
413                         // Get config from database
414                         mergeConfig(SQL_FETCHARRAY($result_config));
415                 } // END - if
416
417                 // Free result
418                 SQL_FREERESULT($result_config);
419
420                 // Remember this config in the array
421                 $GLOBALS['cache_array']['config'][$no] = getConfigArray();
422         }
423 }
424
425 // "Getter" for "checked" configuration entries
426 function getCheckedConfig ($configEntries) {
427         // Add entries
428         $content = getConfigEntries($configEntries, ' checked="checked"');
429
430         // Return it
431         return $content;
432 }
433
434 // "Getter" for "selected" configuration entries
435 function getSelectedConfig ($configEntries) {
436         // Add entries
437         $content = getConfigEntries($configEntries, ' selected="selected"');
438
439         // Return it
440         return $content;
441 }
442
443 // "Getter" for configuration entries
444 function getConfigEntries ($configEntries, $value) {
445         // Init content
446         $content = array();
447
448         // "Walk" through all entries
449         foreach ($configEntries as $entry) {
450                 $content[$entry . '_' . strtolower(getConfig($entry))] = $value;
451         } // END - foreach
452
453         // Return it
454         return $content;
455 }
456
457 // [EOF]
458 ?>