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