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