The yearly copyright-update commit. 2009, 2010 are now copyrighted on the developer...
[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 : Many non-MySQL functions (also file access)      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Init the config array
46 function initConfig () {
47         // Init not if already found
48         if (isConfigurationLoaded()) {
49                 // Already initialized
50                 debug_report_bug(sprintf("[%s:%s] Configuration is already initialized.", __FUNCTION__, __LINE__));
51         } // END - if
52
53         // Set a minimum of configuration, required to by-pass some error triggers in getConfig()
54         $GLOBALS['config'] = array(
55                 'sql_time'            => 0,
56                 'sql_count'           => 0,
57                 'num_templates'       => 0,
58                 // 'DEFAULT_SALT_LENGTH' => 40,
59                 // 'DEBUG_MODE'          => 'N',
60                 // 'DEBUG_RESET'         => 'N',
61                 // 'DEBUG_MONTHLY'       => '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         // Default value
77         $value = null;
78
79         // Is the entry there?
80         if (!isset($GLOBALS['config'][$configEntry])) {
81                 // Raise an error of missing entries
82                 debug_report_bug(sprintf("[%s:%s] Configuration entry <em>%s</em> is missing.",
83                         __FUNCTION__,
84                         __LINE__,
85                         $configEntry
86                 ));
87         } // END - if
88
89         // Return it
90         return $GLOBALS['config'][$configEntry];
91 }
92
93 // Setter for $GLOBALS['config'] entries
94 function setConfigEntry ($configEntry, $value) {
95         // Just set it (unsecured won't hurt?)
96         $GLOBALS['config'][$configEntry] = $value;
97 }
98
99 // Checks wether the given config entry is set
100 function isConfigEntrySet ($configEntry) {
101         //* DEBUG: */ print __FUNCTION__.':'.$configEntry.'='.intval(isset($GLOBALS['config'][$configEntry])).'<br />';
102         return (isset($GLOBALS['config'][$configEntry]));
103 }
104
105 // Merges $GLOBALS['config'] with data in given array
106 function mergeConfig ($newConfig) {
107         $GLOBALS['config'] = merge_array(getConfigArray(), $newConfig);
108 }
109
110 // Increment or init with given value or 1 as default the given config entry
111 function incrementConfigEntry ($configEntry, $value=1) {
112         // Increment it if set or init it with 1
113         if (isConfigEntrySet($configEntry)) {
114                 $GLOBALS['config'][$configEntry] += $value;
115         } else {
116                 $GLOBALS['config'][$configEntry] = $value;
117         }
118 }
119
120 // Checks wether the configuration array is set so the config is loaded
121 function isConfigurationLoaded () {
122         // Check all
123         return (isset($GLOBALS['config']['config']));
124 }
125
126 // Getter for whole $GLOBALS['config'] array
127 function getConfigArray () {
128         // Default is null
129         $return = array();
130
131         // Is the config set?
132         if (isset($GLOBALS['config'])) {
133                 // Then use it
134                 $return = $GLOBALS['config'];
135         } // END - if
136
137         // Return result
138         return $return;
139 }
140
141 // Updates an old inc/config.php to a inc/cache/config-local.php file
142 function updateOldConfigFile () {
143         // Watch out for these lines and execute them as single command
144         // @TODO Make this all better... :-/
145         $watchLines = array(
146                 'SITE_KEY'           => 'SITE_KEY',
147                 'DEFAULT_LANG'       => 'DEFAULT_LANG',
148                 'warn_no_pass'       => 'WARN_NO_PASS',
149                 'WRITE_FOOTER'       => 'WRITE_FOOTER',
150                 'OUTPUT_MODE'        => 'OUTPUT_MODE',
151                 'MAIN_TITLE'         => 'MAIN_TITLE',
152                 'SLOGAN'             => 'SLOGAN',
153                 'WEBMASTER'          => 'WEBMASTER',
154                 'mxchange_installed' => 'MXCHANGE_INSTALLED',
155                 'admin_registered'   => 'ADMIN_REGISTERED',
156                 '_MYSQL_PREFIX'      => '_MYSQL_PREFIX',
157                 '_TABLE_TYPE'        => '_TABLE_TYPE',
158                 '_DB_TYPE'           => '_DB_TYPE',
159                 'SMTP_HOSTNAME'      => 'SMTP_HOSTNAME',
160                 'SMTP_USER'           => 'SMTP_USER',
161                 'SMTP_PASSWORD'      => 'SMTP_PASSWORD',
162                 'ENABLE_BACKLINK'    => 'ENABLE_BACKLINK',
163                 'MAIN_TITLE'         => 'MAIN_TITLE',
164                 'SLOGAN'             => 'SLOGAN',
165                 'WEBMASTER'          => 'WEBMASTER',
166                 'PATH'               => 'PATH',
167                 'URL'                => 'URL',
168         );
169
170         // Make these lower-case! (damn stupid code...)
171         $lowerCase = array('WARN_NO_PASS', 'MXCHANGE_INSTALLED', 'ADMIN_REGISTERED');
172
173         // Special comments...
174         $comments = array(
175                 'WARN_NO_PASS'       => 'NULLPASS-WARNING',
176                 'MXCHANGE_INSTALLED' => 'INSTALLED',
177                 'ADMIN_REGISTERED'   => 'ADMIN-SETUP',
178                 '_MYSQL_PREFIX'      => 'MYSQL-PREFIX',
179                 '_TABLE_TYPE'        => 'TABLE-TYPE',
180                 '_DB_TYPE'           => 'DATABASE-TYPE',
181                 'ENABLE_BACKLINK'    => 'BACKLINK',
182                 'host'               => 'MYSQL-HOST',
183                 'dbase'              => 'MYSQL-DBASE',
184                 'login'              => 'MYSQL-LOGIN',
185                 'password'           => 'MYSQL-PASSWORD'
186         );
187
188         // Copy template to new file destionation
189         copyFileVerified(getConfig('PATH') . 'inc/config-local.php.dist', getConfig('CACHE_PATH') . 'config-local.php', 0644);
190
191         // First of all, load the old one!
192         $oldConfig = explode("\n", readFromFile(getConfig('PATH') . 'inc/config.php'));
193
194         // Now, analyze every entry
195         $done = array();
196         foreach ($oldConfig as $line) {
197                 // Check all watch lines
198                 foreach ($watchLines as $old => $new) {
199                         // Add define() command around old one
200                         $old = "define('" . $old . "',";
201
202                         // Is the line found?
203                         if ((substr($line, 0, strlen($old)) == $old) && (!isset($done[$old]))) {
204                                 // Entry found!
205                                 //* DEBUG: */ outputHtml(secureString($line) . " - FOUND!<br />");
206
207                                 // Eval the line...
208                                 eval($line);
209
210                                 // Setting config entry is new default behaviour!
211                                 $function = 'setConfigEntry';
212
213                                 // Default comment
214                                 $comment = str_replace('_', '-', $new);
215
216                                 // Do we have a special comment?
217                                 if (isset($comments[$new])) {
218                                         // Then use it
219                                         $comment = $comments[$new];
220                                 } // END - if
221
222                                 // Do we need to make $new lowercase?
223                                 $oldNew = $new;
224                                 if (in_array($new, $lowerCase)) {
225                                         // Then do so... :)
226                                         $new = strtolower($new);
227                                 } // END - if
228
229                                 /// ... and write it to the new config
230                                 //* DEBUG: */ outputHtml('function=' . $function . ',new=' . $new . ',comment=' . $comment . "<br />");
231                                 changeDataInFile(getConfig('CACHE_PATH') . 'config-local.php', $comment, $function . "('" . $oldNew . "', \"", "\");", constant($new), 0);
232                                 //* DEBUG: */ outputHtml("CHANGED!<br />");
233
234                                 // Mark it as done
235                                 $done[$old] = 1;
236                         } // END - if
237                 } // END - foreach
238         } // END - foreach
239
240         // By default the old array $MySQL was not found
241         $found = false;
242
243         // Analyze every entry again for the MySQL configuration
244         foreach ($oldConfig as $line) {
245                 // Trim spaces
246                 $line = trim($line);
247
248                 // Is the $MySQL found?
249                 if (substr($line, 0, 6) == "\$MySQL") {
250                         // Okay found!
251                         $found = true;
252                 } elseif ($found === true) {
253                         // Now check this row
254                         if (substr($line, 0, 2) == ');') {
255                                 // MySQL array is closed so stop looking for it
256                                 break;
257                         } elseif (substr($line, 0, 2) == '//') {
258                                 // Skip this line
259                                 continue;
260                         }
261
262                         // Debug output only
263                         //* DEBUG: */ outputHtml(secureString($line) . " - MySQL!<br />");
264
265                         // Split parts so we can check them and prepare them
266                         $parts = explode('=>', $line);
267                         $key = substr(trim($parts[0]), 1, -1); $value = substr(trim($parts[1]), 1, -2);
268
269                         // We can now save the right part in new config file
270                         changeDataInFile(getConfig('CACHE_PATH') . 'config-local.php', $comments[$key], "       '".$key."'     => \"", "\",", $value, 0);
271                 }
272         } // END - foreach
273
274         // Finally remove old config file
275         removeFile(getConfig('PATH') . 'inc/config.php');
276
277         // Redirect to same URL to reload our new config
278         redirectToUrl(getRequestUri());
279 }
280
281 // Update config entries
282 function updateConfiguration ($entries, $values, $updateMode='', $config = '0') {
283         // Do not update config in CSS mode
284         if ((getOutputMode() == 1) || (getOutputMode() == -1) || (isInstallationPhase())) {
285                 return;
286         } // END - if
287
288         // Do we have multiple entries?
289         if (is_array($entries)) {
290                 // Walk through all
291                 $all = '';
292                 foreach ($entries as $idx => $entry) {
293                         // Update mode set?
294                         if (!empty($updateMode)) {
295                                 // Update entry
296                                 $all .= sprintf("`%s`=`%s`%s%s,", $entry, $entry, $updateMode, (float)$values[$idx]);
297                         } else {
298                                 // Check if string or number but no array
299                                 if (is_array($values[$idx])) {
300                                         // Arrays must be fixed...
301                                         debug_report_bug('values[' . $idx . '] should not be an array! Content=<pre>'.print_r($values[$idx], true).'</pre>');
302                                 } elseif (($values[$idx] + 0) === $values[$idx]) {
303                                         // Number detected
304                                         $all .= sprintf("`%s`=%s,", $entry, (float)$values[$idx]);
305
306                                         // Set it in config as well
307                                         setConfigEntry($entry, $values[$idx]);
308                                 } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
309                                         // Function UNIX_TIMESTAMP() detected
310                                         $all .= sprintf("`%s`=UNIX_TIMESTAMP(),", $entry);
311
312                                         // Set timestamp in array as well
313                                         setConfigEntry($entry, time());
314                                 } else {
315                                         // String detected
316                                         $all .= sprintf("`%s`='%s',", $entry, SQL_ESCAPE($values[$idx]));
317
318                                         // Set it in config as well
319                                         setConfigEntry($entry, $values[$idx]);
320                                 }
321                         }
322                 } // END - foreach
323
324                 // Remove last comma
325                 $entries = substr($all, 0, -1);
326         } elseif (!empty($updateMode)) {
327                 // Update mode set
328                 $entries = sprintf("`%s`=`%s`%s%s", $entries, $entries, $updateMode, (float)$values);
329         } elseif (($values + 0) === $values) {
330                 // Number detected
331                 $entries = sprintf("`%s`=%s", $entries, (float)$values);
332
333                 // Set it in config first
334                 setConfigEntry($entries, (float)$values);
335         } elseif ($values == 'UNIX_TIMESTAMP()') {
336                 // Function UNIX_TIMESTAMP() detected
337                 $entries = sprintf("`%s`=UNIX_TIMESTAMP()", $entries);
338
339                 // Set timestamp in array as well
340                 setConfigEntry($entries, time());
341         } else {
342                 // Regular entry to update
343                 $entries = sprintf("`%s`='%s'", $entries, SQL_ESCAPE($values));
344
345                 // Set it in config as well
346                 setConfigEntry($entries, SQL_ESCAPE($values));
347         }
348
349         // Run database update
350         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "entries={$entries}");
351         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_config` SET ".$entries." WHERE `config`=%s LIMIT 1",
352                         array(bigintval($config)), __FUNCTION__, __LINE__);
353         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "entries={$entries},affectedRows={$affectedRows}<br />");
354
355         // Rebuild cache
356         rebuildCache('config', 'config');
357 }
358
359 // Filter for loading configuration
360 function FILTER_LOAD_CONFIGURATION ($no = '0') {
361         // Is the value null, fix it :(
362         if (is_null($no)) $no = '0';
363
364         // Check for cache extension, cache-array and if the requested configuration is in cache
365         if ((isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
366                 // Load config from cache
367                 mergeConfig($GLOBALS['cache_array']['config'][$no]);
368
369                 // Count cache hits if exists
370                 if ((isStatsEntrySet('cache_hits')) && (isExtensionActive('cache'))) {
371                         incrementStatsEntry('cache_hits');
372                 } // END - if
373         } elseif ((!isExtensionActive('cache')) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
374                 // Load config from DB
375                 $result_config = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_config` WHERE `config`='%s' LIMIT 1",
376                         array(bigintval($no)), __FUNCTION__, __LINE__);
377
378                 // Is the config there?
379                 if (SQL_NUMROWS($result_config) == 1) {
380                         // Get config from database
381                         mergeConfig(SQL_FETCHARRAY($result_config));
382                 } // END - if
383
384                 // Free result
385                 SQL_FREERESULT($result_config);
386
387                 // Remember this config in the array
388                 $GLOBALS['cache_array']['config'][$no] = getConfigArray();
389         }
390 }
391
392 // [EOF]
393 ?>