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