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