Mark as not found when array is closed
[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_DAILY'         => '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                                 $found = FALSE;
263                                 break;
264                         } elseif (substr($line, 0, 2) == '//') {
265                                 // Skip this line
266                                 continue;
267                         }
268
269                         // Debug output only
270                         //* DEBUG: */ debugOutput(secureString($line) . ' - MySQL!');
271
272                         // Split parts so we can check them and prepare them
273                         $parts = explode('=>', $line);
274                         $key = substr(trim($parts[0]), 1, -1); $value = substr(trim($parts[1]), 1, -2);
275
276                         // We can now save the right part in new config file
277                         changeDataInInclude(getCachePath() . 'config-local.php', $comments[$key], "     '".$key."'     => \"", '",', $value, 0);
278                 }
279         } // END - foreach
280
281         // Finally remove old config file
282         removeFile(getPath() . 'inc/config.php');
283
284         // Redirect to same URL to reload our new config
285         redirectToUrl(getRequestUri());
286 }
287
288 // Update config entries
289 function updateConfiguration ($entries, $values, $updateMode = '', $config = '0') {
290         // Do not update config in CSS mode
291         if ((isCssOutputMode()) || (isRawOutputMode()) || (isInstallationPhase())) {
292                 // This logger line may be very noisy
293                 //* 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()));
294                 return;
295         } // END - if
296
297         // Default is empty SQL
298         $SQL = '';
299
300         // Is there multiple entries?
301         if (is_array($entries)) {
302                 // Walk through all
303                 foreach ($entries as $idx => $entry) {
304                         // Update mode set?
305                         if (!empty($updateMode)) {
306                                 // Update entry
307                                 $SQL .= sprintf("`%s`=`%s`%s%s,", $entry, $entry, $updateMode, (float) $values[$idx]);
308                         } else {
309                                 // Check if string or number but no array
310                                 if (is_array($values[$idx])) {
311                                         // Arrays must be fixed...
312                                         reportBug(__FUNCTION__, __LINE__, 'values[' . $idx . '] should not be an array! Content=<pre>'.print_r($values[$idx], TRUE).'</pre>');
313                                 } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
314                                         // Function UNIX_TIMESTAMP() detected
315                                         $SQL .= sprintf("`%s`=UNIX_TIMESTAMP(),", $entry);
316
317                                         // Set timestamp in array as well
318                                         setConfigEntry($entry, time());
319                                 } elseif (!empty($updateMode)) {
320                                         // Is the value zero?
321                                         if ($values[$idx] == '0') {
322                                                 // Then skip it
323                                                 continue;
324                                         } // END - if
325
326                                         // Update mode set
327                                         // @TODO Call setConfigEntry() somehow
328                                         $SQL .= $entries = sprintf("`%s`=`%s`%s%s", $entry, $entry, $updateMode, (float) $values[$idx]);
329                                 } elseif (($values[$idx] + 0) === $values[$idx]) {
330                                         // Number detected
331                                         $SQL .= sprintf("`%s`=%s,", $entry, (float) $values[$idx]);
332
333                                         // Set it in config as well
334                                         setConfigEntry($entry, $values[$idx]);
335                                 } else {
336                                         // String detected
337                                         $SQL .= sprintf("`%s`='%s',", $entry, SQL_ESCAPE($values[$idx]));
338
339                                         // Set it in config as well
340                                         setConfigEntry($entry, $values[$idx]);
341                                 }
342                         }
343                 } // END - foreach
344
345                 // Remove last comma
346                 $SQL = substr($SQL, 0, -1);
347         } elseif (!empty($updateMode)) {
348                 // Is the value zero?
349                 if ($values == '0') {
350                         // Then skip it
351                         continue;
352                 } // END - if
353
354                 // Update mode set
355                 // @TODO Call setConfigEntry() somehow
356                 $SQL = sprintf("`%s`=`%s`%s%s", $entries, $entries, $updateMode, (float) $values);
357         } elseif (($values + 0) === $values) {
358                 // Number detected
359                 $SQL = sprintf("`%s`=%s", $entries, (float) $values);
360
361                 // Set it in config first
362                 setConfigEntry($entries, (float) $values);
363         } elseif ($values == 'UNIX_TIMESTAMP()') {
364                 // Function UNIX_TIMESTAMP() detected
365                 $SQL = sprintf("`%s`=UNIX_TIMESTAMP()", $entries);
366
367                 // Set timestamp in array as well
368                 setConfigEntry($entries, time());
369         } else {
370                 // Regular entry to update
371                 $SQL = sprintf("`%s`='%s'", $entries, SQL_ESCAPE($values));
372
373                 // Set it in config as well
374                 setConfigEntry($entries, SQL_ESCAPE($values));
375         }
376
377         // Run database update
378         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL);
379         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_config` SET ".$SQL." WHERE `config`=%s LIMIT 1",
380                         array(bigintval($config)), __FUNCTION__, __LINE__);
381         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL . ',affectedRows=' . SQL_AFFECTEDROWS());
382
383         // Rebuild cache
384         rebuildCache('config', 'config');
385 }
386
387 // Filter for loading configuration
388 function FILTER_LOAD_CONFIGURATION ($no = '0') {
389         // Is installation phase?
390         if (isInstallationPhase()) {
391                 // Then don't load any configuration
392                 return;
393         } // END - if
394
395         // Is the value null, it comes from the 'init' filter chain
396         if (is_null($no)) {
397                 $no = '0';
398         } // END - if
399
400         // Check for cache extension, cache-array and if the requested configuration is in cache
401         if ((isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
402                 // Load config from cache
403                 mergeConfig($GLOBALS['cache_array']['config'][$no]);
404
405                 // Count cache hits 
406                 incrementStatsEntry('cache_hits');
407         } elseif ((!isExtensionActive('cache')) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
408                 // Load config from DB
409                 $result_config = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_config` WHERE `config`='%s' LIMIT 1",
410                         array(bigintval($no)), __FUNCTION__, __LINE__);
411
412                 // Is the config there?
413                 if (SQL_NUMROWS($result_config) == 1) {
414                         // Get config from database
415                         mergeConfig(SQL_FETCHARRAY($result_config));
416                 } // END - if
417
418                 // Free result
419                 SQL_FREERESULT($result_config);
420
421                 // Remember this config in the array
422                 $GLOBALS['cache_array']['config'][$no] = getConfigArray();
423         }
424 }
425
426 // "Getter" for "checked" configuration entries
427 function getCheckedConfig ($configEntries) {
428         // Add entries
429         $content = getConfigEntries($configEntries, ' checked="checked"');
430
431         // Return it
432         return $content;
433 }
434
435 // "Getter" for "selected" configuration entries
436 function getSelectedConfig ($configEntries) {
437         // Add entries
438         $content = getConfigEntries($configEntries, ' selected="selected"');
439
440         // Return it
441         return $content;
442 }
443
444 // "Getter" for configuration entries
445 function getConfigEntries ($configEntries, $value) {
446         // Init content
447         $content = array();
448
449         // "Walk" through all entries
450         foreach ($configEntries as $entry) {
451                 $content[$entry . '_' . strtolower(getConfig($entry))] = $value;
452         } // END - foreach
453
454         // Return it
455         return $content;
456 }
457
458 // [EOF]
459 ?>