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