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