Updated domain without a dash :(
[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%01.5f,', $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                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Function UNIX_TIMESAMP() detected: entry=' . $entry);
317                                         $SQL .= sprintf('`%s`=UNIX_TIMESTAMP(),', $entry);
318
319                                         // Set timestamp in array as well
320                                         setConfigEntry($entry, time());
321                                 } elseif (!empty($updateMode)) {
322                                         // Is the value zero?
323                                         if ($values[$idx] == '0') {
324                                                 // Then skip it
325                                                 continue;
326                                         } // END - if
327
328                                         // Update mode set
329                                         // @TODO Call setConfigEntry() somehow
330                                         $SQL .= $entries = sprintf('`%s`=`%s`%s%01.5f', $entry, $entry, $updateMode, (float) $values[$idx]);
331                                 } elseif (($values[$idx] + 0) === $values[$idx]) {
332                                         // Number detected
333                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Number detected: entry=' . $entry . ',values[' . $idx . '/' . gettype($values[$idx]) . ']=' . $values[$idx]);
334                                         $SQL .= sprintf('`%s`=%01.5f,', $entry, (float) $values[$idx]);
335
336                                         // Set it in config as well
337                                         setConfigEntry($entry, $values[$idx]);
338                                 } else {
339                                         // String detected
340                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular value detected: entry=' . $entry . ',values[' . $idx . '/' . gettype($values[$idx]) . ']=' . $values[$idx]);
341                                         $SQL .= sprintf("`%s`='%s',", $entry, sqlEscapeString($values[$idx]));
342
343                                         // Set it in config as well
344                                         setConfigEntry($entry, $values[$idx]);
345                                 }
346                         }
347                 } // END - foreach
348
349                 // Remove last comma
350                 $SQL = substr($SQL, 0, -1);
351         } elseif (!empty($updateMode)) {
352                 // Is the value zero?
353                 if ($values == '0') {
354                         // Then skip it
355                         continue;
356                 } // END - if
357
358                 // Update mode set
359                 // @TODO Call setConfigEntry() somehow
360                 $SQL = sprintf('`%s`=`%s`%s%01.5f', $entries, $entries, $updateMode, (float) $values);
361         } elseif ($values == 'UNIX_TIMESTAMP()') {
362                 // Function UNIX_TIMESTAMP() detected
363                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Function UNIX_TIMESAMP() detected: entries=' . $entries);
364                 $SQL = sprintf('`%s`=UNIX_TIMESTAMP()', $entries);
365
366                 // Set timestamp in array as well
367                 setConfigEntry($entries, time());
368         } elseif (($values + 0) === $values) {
369                 // Number detected
370                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Number detected: entries=' . $entries . ',values[' . gettype($values) . ']=' . $values);
371                 $SQL = sprintf('`%s`=%01.5f', $entries, (float) $values);
372
373                 // Set it in config first
374                 setConfigEntry($entries, (float) $values);
375         } else {
376                 // Regular entry to update
377                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular value detected: entries=' . $entries . ',values[' . gettype($values) . ']=' . $values);
378                 $SQL = sprintf("`%s`='%s'", $entries, sqlEscapeString($values));
379
380                 // Set it in config as well
381                 setConfigEntry($entries, sqlEscapeString($values));
382         }
383
384         // Run database update
385         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL);
386         sqlQueryEscaped('UPDATE `{?_MYSQL_PREFIX?}_config` SET ' . $SQL . ' WHERE `config`=%s LIMIT 1',
387                         array(bigintval($config)), __FUNCTION__, __LINE__);
388         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL . ',affectedRows=' . sqlAffectedRows());
389
390         // Rebuild cache
391         rebuildCache('config', 'config');
392 }
393
394 // Filter for loading configuration
395 function FILTER_LOAD_CONFIGURATION ($no = '0') {
396         // Is installation phase?
397         if (isInstaller()) {
398                 // Then don't load any configuration
399                 return;
400         } // END - if
401
402         // Is the value null, it comes from the 'init' filter chain
403         if (is_null($no)) {
404                 $no = '0';
405         } // END - if
406
407         // Check for cache extension, cache-array and if the requested configuration is in cache
408         if ((isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
409                 // Load config from cache
410                 mergeConfig($GLOBALS['cache_array']['config'][$no]);
411
412                 // Count cache hits
413                 incrementStatsEntry('cache_hits');
414         } elseif ((!isExtensionActive('cache')) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
415                 // Load config from DB
416                 $result_config = sqlQueryEscaped('SELECT * FROM `{?_MYSQL_PREFIX?}_config` WHERE `config`=%s LIMIT 1',
417                         array(bigintval($no)), __FUNCTION__, __LINE__);
418
419                 // Is the config there?
420                 if (sqlNumRows($result_config) == 1) {
421                         // Get config from database
422                         mergeConfig(sqlFetchArray($result_config));
423                 } // END - if
424
425                 // Free result
426                 sqlFreeResult($result_config);
427
428                 // Remember this config in the array
429                 $GLOBALS['cache_array']['config'][$no] = getConfigArray();
430         }
431 }
432
433 // "Getter" for "checked" configuration entries
434 function getCheckedConfig ($configEntries) {
435         // Add entries
436         $content = getConfigEntries($configEntries, ' checked="checked"');
437
438         // Return it
439         return $content;
440 }
441
442 // "Getter" for "selected" configuration entries
443 function getSelectedConfig ($configEntries) {
444         // Add entries
445         $content = getConfigEntries($configEntries, ' selected="selected"');
446
447         // Return it
448         return $content;
449 }
450
451 // "Getter" for configuration entries
452 function getConfigEntries ($configEntries, $value) {
453         // Init content
454         $content = array();
455
456         // "Walk" through all entries
457         foreach ($configEntries as $entry) {
458                 $content[$entry . '_' . strtolower(getConfig($entry))] = $value;
459         } // END - foreach
460
461         // Return it
462         return $content;
463 }
464
465 // [EOF]
466 ?>