Continued a bit:
[mailer.git] / inc / config-functions.php
index 3358a302a9eedee88469c92e1048188bb11f233b..825faea0d883e6fa11593a19de0ac1919229ae31 100644 (file)
@@ -1,24 +1,18 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 02/28/2009 *
- * ===============                              Last change: 02/28/2009 *
+ * Mailer v0.2.1-FINAL                                Start: 02/28/2009 *
+ * ===================                          Last change: 02/28/2009 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : config-functions.php                             *
  * -------------------------------------------------------------------- *
- * Short description : Many non-MySQL functions (also file access)      *
+ * Short description : Configuration functions                          *
  * -------------------------------------------------------------------- *
- * Kurzbeschreibung  : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
+ * Kurzbeschreibung  : Konfigurationsfunktionen                         *
  * -------------------------------------------------------------------- *
- * $Revision::                                                        $ *
- * $Date::                                                            $ *
- * $Tag:: 0.2.1-FINAL                                                 $ *
- * $Author::                                                          $ *
- * Needs to be in all Files and every File needs "svn propset           *
- * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
- * -------------------------------------------------------------------- *
- * Copyright (c) 2003 - 2008 by Roland Haeder                           *
- * For more information visit: http://www.mxchange.org                  *
+ * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009 - 2016 by Mailer Developer Team                   *
+ * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
  * it under the terms of the GNU General Public License as published by *
 
 // Some security stuff...
 if (!defined('__SECURITY')) {
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
-       require($INC);
-}
-
-// Merges $_CONFIG with data in given array
-function mergeConfig ($newConfig) {
-       global $_CONFIG;
-       $_CONFIG = merge_array($_CONFIG, $newConfig);
-}
+       die();
+} // END - if
 
-// Getter for $_CONFIG entries
-function getConfig ($entry) {
-       global $_CONFIG;
+// Init the config array
+function initConfig () {
+       // Init not if already found
+       if (isConfigurationLoaded()) {
+               // Already initialized
+               reportBug(__FUNCTION__, __LINE__, 'Configuration is already initialized.');
+       } // END - if
 
-       // Default value
-       $value = null;
+       // Set a minimum of configuration, required to by-pass some error triggers in getConfig()
+       $GLOBALS['config'] = array(
+               'sql_time'            => 0,
+               'sql_count'           => 0,
+               'num_templates'       => 0,
+               // 'DEFAULT_SALT_LENGTH' => 40,
+               // 'DEBUG_MODE'          => 'N',
+               // 'DEBUG_HOURLY'        => 'N',
+               // 'DEBUG_DAILY'         => 'N',
+               // 'DEBUG_MONTHLY'       => 'N',
+               // 'DEBUG_YEARLY'        => 'N',
+               // 'DEBUG_WEEKLY'        => 'N',
+               // 'DEBUG_REGEX'         => 'N',
+               // 'ADMIN_REGISTERED'    => 'N',
+               // 'verbose_sql'         => 'Y',
+               // For installation phase:
+               'SMTP_HOSTNAME'       => '',
+               'SMTP_USER'           => '',
+               'SMTP_PASSWORD'       => '',
+               'MT_WORD'             => '{--DEFAULT_MT_WORD--}',
+       );
+}
 
+// Getter for $GLOBALS['config'] entries
+function getConfig ($configEntry) {
        // Is the entry there?
-       if (isConfigEntrySet($entry)) {
-               // Then use it
-               $value = $_CONFIG[$entry];
+       if (!isConfigEntrySet($configEntry)) {
+               // Raise an error of missing entries
+               reportBug(__FUNCTION__, __LINE__, sprintf('Configuration entry <span class="data">%s</span> is missing.', $configEntry));
        } // END - if
 
        // Return it
-       return $value;
+       //* DEBUG: */ error_log(__FUNCTION__.'['.__LINE__.':] '.$configEntry.'='.$GLOBALS['config'][$configEntry]);
+       return $GLOBALS['config'][$configEntry];
 }
 
-// Setter for $_CONFIG entries
-function setConfigEntry ($entry, $value) {
-       global $_CONFIG;
+// Setter for $GLOBALS['config'] entries
+function setConfigEntry ($configEntry, $value) {
+       // Just set it (unsecured won't hurt?)
+       $GLOBALS['config'][$configEntry] = $value;
 
-       // Secure the entry name
-       $entry = SQL_ESCAPE($entry);
+       // Remove cache
+       removeGlobalCache($configEntry);
+}
+
+// Removes entry in $GLOBALS
+function removeGlobalCache ($configEntry) {
+       // Generate key
+       $key = 'get' . capitalizeUnderscoreString($configEntry);
+
+       // Remove it
+       unset($GLOBALS[$key]);
+}
 
-       // And set it
-       $_CONFIG[$entry] = $value;
+// Checks whether the given config entry is set
+function isConfigEntrySet ($configEntry) {
+       //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . $configEntry . '=' . intval(isset($GLOBALS['config'][$configEntry])));
+       return ((isset($GLOBALS['config'][$configEntry])) || (array_key_exists($configEntry, $GLOBALS['config'])));
 }
 
-// Checks wether the given config entry is set
-function isConfigEntrySet ($entry) {
-       global $_CONFIG;
-       return (isset($_CONFIG[$entry]));
+// Merges $GLOBALS['config'] with data in given array
+function mergeConfig ($newConfig) {
+       // Merge current configuration with new one
+       $GLOBALS['config'] = merge_array(getConfigArray(), $newConfig);
 }
 
 // Increment or init with given value or 1 as default the given config entry
 function incrementConfigEntry ($configEntry, $value=1) {
-       global $_CONFIG;
-
-       // Increment it if set or init it with 1
-       if (getConfig($configEntry) > 0) {
-               $_CONFIG[$configEntry] += $value;
+       // Increment it if set or init it with $value
+       if (isConfigEntrySet($configEntry)) {
+               $GLOBALS['config'][$configEntry] += $value;
        } else {
-               $_CONFIG[$configEntry] = $value;
+               $GLOBALS['config'][$configEntry] = $value;
        }
 }
 
-// Checks wether the configuration array is set so the config is loaded
-function isConfigLoaded () {
-       global $_CONFIG;
-
+// Checks whether the configuration array is set so the config is loaded
+function isConfigurationLoaded () {
        // Check all
-       return ((isset($_CONFIG)) && (is_array($_CONFIG)) && (count($_CONFIG) > 0));
+       return (isset($GLOBALS['config']['config']));
 }
 
-// Init the config array
-function initConfig () {
-       global $_CONFIG;
+// Getter for whole $GLOBALS['config'] array
+function getConfigArray () {
+       // Default is null
+       $return = array();
 
-       // Set a minimum dummy configuration
-       $_CONFIG = array(
-               'code_length' => 0,
-               'patch_level' => 0,
-               'last_update' => time()
+       // Is the config set?
+       if (isset($GLOBALS['config'])) {
+               // Then use it
+               $return = $GLOBALS['config'];
+       } // END - if
+
+       // Return result
+       return $return;
+}
+
+// Updates an old inc/config.php to a inc/cache/config-local.php file
+function updateOldConfigFile () {
+       // Watch out for these lines and execute them as single command
+       // @TODO Make this all better... :-/
+       $watchLines = array(
+               'SITE_KEY'         => 'SITE_KEY',
+               'DEFAULT_LANG'     => 'DEFAULT_LANG',
+               'warn_no_pass'     => 'WARN_NO_PASS',
+               'WRITE_FOOTER'     => 'WRITE_FOOTER',
+               'OUTPUT_MODE'      => 'OUTPUT_MODE',
+               'MAIN_TITLE'       => 'MAIN_TITLE',
+               'SLOGAN'           => 'SLOGAN',
+               'WEBMASTER'        => 'WEBMASTER',
+               'mailer_installed' => 'MAILER_INSTALLED',
+               'admin_registered' => 'ADMIN_REGISTERED',
+               '_MYSQL_PREFIX'    => '_MYSQL_PREFIX',
+               '_TABLE_TYPE'      => '_TABLE_TYPE',
+               '_DB_TYPE'         => '_DB_TYPE',
+               'SMTP_HOSTNAME'    => 'SMTP_HOSTNAME',
+               'SMTP_USER'        => 'SMTP_USER',
+               'SMTP_PASSWORD'    => 'SMTP_PASSWORD',
+               'ENABLE_BACKLINK'  => 'ENABLE_BACKLINK',
+               'MAIN_TITLE'       => 'MAIN_TITLE',
+               'SLOGAN'           => 'SLOGAN',
+               'WEBMASTER'        => 'WEBMASTER',
+               'PATH'             => 'PATH',
+               'URL'              => 'URL',
+       );
+
+       // Make these lower-case! (damn stupid code...)
+       $lowerCase = array('WARN_NO_PASS', 'MAILER_INSTALLED', 'ADMIN_REGISTERED');
+
+       // Special comments...
+       $comments = array(
+               'WARN_NO_PASS'       => 'NULLPASS-WARNING',
+               'MAILER_INSTALLED  ' => 'INSTALLED',
+               'ADMIN_REGISTERED'   => 'ADMIN-SETUP',
+               '_MYSQL_PREFIX'      => 'MYSQL-PREFIX',
+               '_TABLE_TYPE'        => 'TABLE-TYPE',
+               '_DB_TYPE'           => 'DATABASE-TYPE',
+               'ENABLE_BACKLINK'    => 'BACKLINK',
+               'host'               => 'MYSQL-HOST',
+               'dbase'              => 'MYSQL-DBASE',
+               'login'              => 'MYSQL-LOGIN',
+               'password'           => 'MYSQL-PASSWORD'
        );
+
+       // Copy template to new file destionation
+       copyFileVerified(getPath() . 'inc/config-local.php.dist', getCachePath() . 'config-local.php', 0644);
+
+       // First of all, load the old one!
+       $oldConfig = explode(PHP_EOL, readFromFile(getPath() . 'inc/config.php'));
+
+       // Now, analyze every entry
+       $done = array();
+       foreach ($oldConfig as $line) {
+               // Check all watch lines
+               foreach ($watchLines as $old => $new) {
+                       // Add define() command around old one
+                       $old = "define('" . $old . "',";
+
+                       // Is the line found?
+                       if ((substr($line, 0, strlen($old)) == $old) && (!isset($done[$old]))) {
+                               // Entry found
+                               //* DEBUG: */ debugOutput(secureString($line) . ' - FOUND!');
+
+                               // Eval the line...
+                               eval($line);
+
+                               // Setting config entry is new default behaviour!
+                               $function = 'setConfigEntry';
+
+                               // Default comment
+                               $comment = str_replace('_', '-', $new);
+
+                               // Is there a special comment?
+                               if (isset($comments[$new])) {
+                                       // Then use it
+                                       $comment = $comments[$new];
+                               } // END - if
+
+                               // Does $new needs to be lower-case?
+                               $oldNew = $new;
+                               if (in_array($new, $lowerCase)) {
+                                       // Then do so... :)
+                                       $new = strtolower($new);
+                               } // END - if
+
+                               // ... and write it to the new config
+                               //* DEBUG: */ debugOutput('function=' . $function . ',new=' . $new . ',comment=' . $comment);
+                               changeDataInInclude(getCachePath() . 'config-local.php', $comment, $function . "('" . $oldNew . "', \"", '");', constant($new), 0);
+                               //* DEBUG: */ debugOutput('CHANGED!');
+
+                               // Mark it as done
+                               $done[$old] = 1;
+                       } // END - if
+               } // END - foreach
+       } // END - foreach
+
+       // By default the old array $MySQL was not found
+       $found = FALSE;
+
+       // Analyze every entry again for the MySQL configuration
+       foreach ($oldConfig as $line) {
+               // Trim spaces
+               $line = trim($line);
+
+               // Is the $MySQL found?
+               if (substr($line, 0, 6) == '$MySQL') {
+                       // Okay, found
+                       $found = TRUE;
+               } elseif ($found === TRUE) {
+                       // Now check this row
+                       if (substr($line, 0, 2) == ');') {
+                               // MySQL array is closed so stop looking for it
+                               $found = FALSE;
+                               break;
+                       } elseif (substr($line, 0, 2) == '//') {
+                               // Skip this line
+                               continue;
+                       }
+
+                       // Debug output only
+                       //* DEBUG: */ debugOutput(secureString($line) . ' - MySQL!');
+
+                       // Split parts so we can check them and prepare them
+                       $parts = explode('=>', $line);
+                       $key = substr(trim($parts[0]), 1, -1); $value = substr(trim($parts[1]), 1, -2);
+
+                       // We can now save the right part in new config file
+                       changeDataInInclude(getCachePath() . 'config-local.php', $comments[$key], "     '".$key."'     => \"", '",', $value, 0);
+               }
+       } // END - foreach
+
+       // Finally remove old config file
+       removeFile(getPath() . 'inc/config.php');
+
+       // Redirect to same URL to reload our new config
+       redirectToUrl(getRequestUri());
 }
 
-// Load configuration and return it as an arry
-function loadConfiguration ($no="0") {
-       global $_CONFIG;
+// Update config entries
+function updateConfiguration ($entries, $values, $updateMode = '', $config = '0', $force = FALSE) {
+       // Do not update config in CSS mode
+       if (($force === FALSE) && ((isCssOutputMode()) || (isRawOutputMode()) || (isInstaller()))) {
+               // This logger line may be very noisy
+               /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not updating configuration. entries[]=' . gettype($entries) . ',values[]=' . gettype($values) . ',updateMode=' . $updateMode . ',config=' . $config . ',isCssOutputMode()=' . intval(isCssOutputMode()) . ',isRawOutputMode()=' . intval(isRawOutputMode()) . ',isInstaller()=' . intval(isInstaller()));
+               return;
+       } // END - if
 
-       // Check for cache extension, cache-array and if the requested configuration is in cache
-       if ((is_array($GLOBALS['cache_array'])) && (isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
-               // Load config from cache
-               //* DEBUG: */ echo gettype($GLOBALS['cache_array']['config'][$no])."<br />\n";
-               foreach ($GLOBALS['cache_array']['config'][$no] as $key => $value) {
-                       $_CONFIG[$key] = $value;
+       // Default is empty SQL
+       $SQL = '';
+
+       // Is there multiple entries?
+       if (is_array($entries)) {
+               // Walk through all
+               foreach ($entries as $idx => $entry) {
+                       // Update mode set?
+                       if (!empty($updateMode)) {
+                               // Update entry
+                               $SQL .= sprintf('`%s`=`%s`%s%01.5f,', $entry, $entry, $updateMode, (float) $values[$idx]);
+                       } else {
+                               // Check if string or number but no array
+                               if (is_array($values[$idx])) {
+                                       // Arrays must be fixed...
+                                       reportBug(__FUNCTION__, __LINE__, 'values[' . $idx . '] should not be an array! Content=<pre>'.print_r($values[$idx], TRUE).'</pre>');
+                               } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
+                                       // Function UNIX_TIMESTAMP() detected
+                                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Function UNIX_TIMESAMP() detected: entry=' . $entry);
+                                       $SQL .= sprintf('`%s`=UNIX_TIMESTAMP(),', $entry);
+
+                                       // Set timestamp in array as well
+                                       setConfigEntry($entry, time());
+                               } elseif (!empty($updateMode)) {
+                                       // Is the value zero?
+                                       if ($values[$idx] == '0') {
+                                               // Then skip it
+                                               continue;
+                                       } // END - if
+
+                                       // Update mode set
+                                       // @TODO Call setConfigEntry() somehow
+                                       $SQL .= $entries = sprintf('`%s`=`%s`%s%01.5f', $entry, $entry, $updateMode, (float) $values[$idx]);
+                               } elseif (($values[$idx] + 0) === $values[$idx]) {
+                                       // Number detected
+                                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Number detected: entry=' . $entry . ',values[' . $idx . '/' . gettype($values[$idx]) . ']=' . $values[$idx]);
+                                       $SQL .= sprintf('`%s`=%01.5f,', $entry, (float) $values[$idx]);
+
+                                       // Set it in config as well
+                                       setConfigEntry($entry, $values[$idx]);
+                               } else {
+                                       // String detected
+                                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular value detected: entry=' . $entry . ',values[' . $idx . '/' . gettype($values[$idx]) . ']=' . $values[$idx]);
+                                       $SQL .= sprintf("`%s`='%s',", $entry, sqlEscapeString($values[$idx]));
+
+                                       // Set it in config as well
+                                       setConfigEntry($entry, $values[$idx]);
+                               }
+                       }
                } // END - foreach
 
-               // Count cache hits if exists
-               if ((isset($_CONFIG['cache_hits'])) && (EXT_IS_ACTIVE("cache"))) {
-                       $_CONFIG['cache_hits']++;
+               // Remove last comma
+               $SQL = substr($SQL, 0, -1);
+       } elseif (!empty($updateMode)) {
+               // Is the value zero?
+               if ($values == '0') {
+                       // Then skip it
+                       return;
                } // END - if
-       } elseif ((!EXT_IS_ACTIVE("cache")) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
+
+               // Update mode set
+               // @TODO Call setConfigEntry() somehow
+               $SQL = sprintf('`%s`=`%s`%s%01.5f', $entries, $entries, $updateMode, (float) $values);
+       } elseif ($values == 'UNIX_TIMESTAMP()') {
+               // Function UNIX_TIMESTAMP() detected
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Function UNIX_TIMESAMP() detected: entries=' . $entries);
+               $SQL = sprintf('`%s`=UNIX_TIMESTAMP()', $entries);
+
+               // Set timestamp in array as well
+               setConfigEntry($entries, time());
+       } elseif (($values + 0) === $values) {
+               // Number detected
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Number detected: entries=' . $entries . ',values[' . gettype($values) . ']=' . $values);
+               $SQL = sprintf('`%s`=%01.5f', $entries, (float) $values);
+
+               // Set it in config first
+               setConfigEntry($entries, (float) $values);
+       } else {
+               // Regular entry to update
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular value detected: entries=' . $entries . ',values[' . gettype($values) . ']=' . $values);
+               $SQL = sprintf("`%s`='%s'", $entries, sqlEscapeString($values));
+
+               // Set it in config as well
+               setConfigEntry($entries, sqlEscapeString($values));
+       }
+
+       // Run database update
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL);
+       sqlQueryEscaped('UPDATE `{?_MYSQL_PREFIX?}_config` SET ' . $SQL . ' WHERE `config`=%s LIMIT 1',
+                       array(bigintval($config)), __FUNCTION__, __LINE__);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SQL=' . $SQL . ',affectedRows=' . sqlAffectedRows());
+
+       // Rebuild cache
+       rebuildCache('config', 'config');
+}
+
+// Filter for loading configuration
+function FILTER_LOAD_CONFIGURATION ($no = '0') {
+       // Is installation phase?
+       if (isInstaller()) {
+               // Then don't load any configuration
+               return;
+       } // END - if
+
+       // Is the value null, it comes from the 'init' filter chain
+       if (is_null($no)) {
+               $no = '0';
+       } // END - if
+
+       // Check for cache extension, cache-array and if the requested configuration is in cache
+       if ((isset($GLOBALS['cache_array']['config'][$no])) && (is_array($GLOBALS['cache_array']['config'][$no]))) {
+               // Load config from cache
+               mergeConfig($GLOBALS['cache_array']['config'][$no]);
+
+               // Count cache hits
+               incrementStatsEntry('cache_hits');
+       } elseif ((!isExtensionActive('cache')) || (!isset($GLOBALS['cache_array']['config'][$no]))) {
                // Load config from DB
-               $result_config = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_config` WHERE config=%d LIMIT 1",
+               $result_config = sqlQueryEscaped('SELECT * FROM `{?_MYSQL_PREFIX?}_config` WHERE `config`=%s LIMIT 1',
                        array(bigintval($no)), __FUNCTION__, __LINE__);
 
                // Is the config there?
-               if (SQL_NUMROWS($result_config) == 1) {
+               if (sqlNumRows($result_config) == 1) {
                        // Get config from database
-                       $_CONFIG = SQL_FETCHARRAY($result_config);
+                       mergeConfig(sqlFetchArray($result_config));
                } // END - if
 
                // Free result
-               SQL_FREERESULT($result_config);
+               sqlFreeResult($result_config);
 
                // Remember this config in the array
-               $GLOBALS['cache_array']['config'][$no] = $_CONFIG;
+               $GLOBALS['cache_array']['config'][$no] = getConfigArray();
        }
 }
 
+// "Getter" for "checked" configuration entries
+function getCheckedConfig ($configEntries) {
+       // Add entries
+       $content = getConfigEntries($configEntries, ' checked="checked"');
+
+       // Return it
+       return $content;
+}
+
+// "Getter" for "selected" configuration entries
+function getSelectedConfig ($configEntries) {
+       // Add entries
+       $content = getConfigEntries($configEntries, ' selected="selected"');
+
+       // Return it
+       return $content;
+}
+
+// "Getter" for configuration entries
+function getConfigEntries ($configEntries, $value) {
+       // Init content
+       $content = array();
+
+       // "Walk" through all entries
+       foreach ($configEntries as $entry) {
+               $content[$entry . '_' . strtolower(getConfig($entry))] = $value;
+       } // END - foreach
+
+       // Return it
+       return $content;
+}
+
 // [EOF]
 ?>