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