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