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