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