Some updates:
[core.git] / inc / config / class_FrameworkConfiguration.php
diff --git a/inc/config/class_FrameworkConfiguration.php b/inc/config/class_FrameworkConfiguration.php
new file mode 100644 (file)
index 0000000..b89791b
--- /dev/null
@@ -0,0 +1,414 @@
+<?php
+/**
+ * A class for the configuration stuff implemented in a singleton design paddern
+ *
+ * NOTE: We cannot put this in inc/main/ because it would be loaded (again) in
+ * class loader. See inc/loader/class_ClassLoader.php for instance
+ *
+ * @see                        ClassLoader
+ * @author             Roland Haeder <webmaster@shipsimu.org>
+ * @version            0.0.0
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.shipsimu.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
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class FrameworkConfiguration implements Registerable {
+       /**
+        * The framework's main configuration array which will be initialized with
+        * hard-coded configuration data and might be overwritten/extended by
+        * config data from the database.
+        */
+       private $config = array();
+
+       /**
+        * The configuration instance itself
+        */
+       private static $configInstance = NULL;
+
+       // Some constants for the configuration system
+       const EXCEPTION_CONFIG_KEY_IS_EMPTY           = 0x130;
+       const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND      = 0x131;
+       const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
+
+       /**
+        * Protected constructor
+        *
+        * @return      void
+        */
+       protected function __construct () {
+               // Empty for now
+       }
+
+       /**
+        * Compatiblity method to return this class' name
+        *
+        * @return      __CLASS__       This class' name
+        */
+       public function __toString () {
+               return get_class($this);
+       }
+
+       /**
+        * Getter for a singleton instance of this class
+        *
+        * @return      $configInstance         A singleton instance of this class
+        */
+       public static final function getSelfInstance () {
+               // is the instance there?
+               if (is_null(self::$configInstance))  {
+                       // Create a config instance
+                       self::$configInstance = new FrameworkConfiguration();
+               } // END - if
+
+               // Return singleton instance
+               return self::$configInstance;
+       }
+
+       /**
+        * Converts dashes to underscores, e.g. useable for configuration entries
+        *
+        * @param       $str    The string with maybe dashes inside
+        * @return      $str    The converted string with no dashed, but underscores
+        */
+       private final function convertDashesToUnderscores ($str) {
+               // Convert them all
+               $str = str_replace('-', '_', $str);
+
+               // Return converted string
+               return $str;
+       }
+
+       /**
+        * Setter for default time zone (must be correct!)
+        *
+        * @param       $zone   The time-zone string (e.g. Europe/Berlin)
+        * @return      void
+        */
+       public final function setDefaultTimezone ($zone) {
+               // Is PHP version 5.1.0 or higher? Older versions are being ignored
+               if (version_compare(phpversion(), '5.1.0', '>=')) {
+                       /*
+                        * Set desired time zone to prevent date() and related functions to
+                        * issue a E_WARNING.
+                        */
+                       date_default_timezone_set($zone);
+               } // END - if
+       }
+
+       /**
+        * Setter for runtime magic quotes
+        *
+        * @param       $enableQuotes   Whether enable magic runtime quotes (should be disabled for security reasons)
+        * @return      void
+        * @todo        This method encapsulates a deprecated PHP function and should be deprecated, too.
+        */
+       public final function setMagicQuotesRuntime ($enableQuotes) {
+               // Is the PHP version < 5.4?
+               if (version_compare(phpversion(), '5.4', '>=')) {
+                       // Then silently skip this part as set_magic_quotes_runtime() is deprecated
+                       return;
+               } // END - if
+
+               // Cast it to boolean
+               $enableQuotes = (boolean) $enableQuotes;
+
+               // Set it
+               set_magic_quotes_runtime($enableQuotes);
+       }
+
+       /**
+        * Checks whether the given configuration key is set
+        *
+        * @param       $configKey      The configuration key we shall check
+        * @return      $isset          Whether the given configuration key is set
+        */
+       public function isConfigurationEntrySet ($configKey) {
+               // Is it set?
+               $isset = isset($this->config[$configKey]);
+
+               // Return the result
+               return $isset;
+       }
+
+       /**
+        * Read a configuration element.
+        *
+        * @param       $configKey              The configuration element
+        * @return      $configValue    The fetched configuration value
+        * @throws      ConfigEntryIsEmptyException             If $configKey is empty
+        * @throws      NoConfigEntryException                  If a configuration element was not found
+        */
+       public function getConfigEntry ($configKey) {
+               // Convert dashes to underscore
+               $configKey = self::convertDashesToUnderscores($configKey);
+
+               // Is a valid configuration key provided?
+               if (empty($configKey)) {
+                       // Entry is empty
+                       throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+               } elseif (!$this->isConfigurationEntrySet($configKey)) {
+                       // Entry was not found!
+                       throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
+               }
+
+               // Return the requested value
+               return $this->config[$configKey];
+       }
+
+       /**
+        * Set a configuration key
+        *
+        * @param       $configKey      The configuration key we want to add/change
+        * @param       $configValue    The configuration value we want to set
+        * @return      void
+        * @throws      ConfigEntryIsEmptyException                     If $configKey is empty
+        * @throws      ConfigValueTypeUnsupportedException     If $configValue has an unsupported variable type
+        */
+       public final function setConfigEntry ($configKey, $configValue) {
+               // Cast to string
+               $configKey = self::convertDashesToUnderscores($configKey);
+
+               // Is a valid configuration key key provided?
+               if (is_null($configKey)) {
+                       // Configuration key is null
+                       throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+               } elseif ((empty($configKey)) || (!is_string($configKey))) {
+                       // Entry is empty
+                       throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+               } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
+                       // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
+                       throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
+               }
+
+               // Set the configuration value
+               //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
+               $this->config[$configKey] = $configValue;
+
+               // Resort the array
+               ksort($this->config);
+       }
+
+       /**
+        * Unset a configuration key, the entry must be there or else an
+        * exception is thrown.
+        *
+        * @param       $configKey      Configuration key to unset
+        * @return      void
+        * @throws      NoConfigEntryException  If a configuration element was not found
+        */
+       public final function unsetConfigEntry ($configKey) {
+               // Convert dashes to underscore
+               $configKey = self::convertDashesToUnderscores($configKey);
+
+               // Is the configuration key there?
+               if (!$this->isConfigurationEntrySet($configKey)) {
+                       // Entry was not found!
+                       throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
+               } // END - if
+
+               // Unset it
+               unset($this->config[$configKey]);
+       }
+
+       /**
+        * Detects the server address (SERVER_ADDR) and set it in configuration
+        *
+        * @return      $serverAddress  The detected server address
+        * @todo        We have to add some more entries from $_SERVER here
+        */
+       public function detectServerAddress () {
+               // Is the entry set?
+               if (!$this->isConfigurationEntrySet('server_addr')) {
+                       // Is it set in $_SERVER?
+                       if (isset($_SERVER['SERVER_ADDR'])) {
+                               // Set it from $_SERVER
+                               $this->setServerAddress($_SERVER['SERVER_ADDR']);
+                       } elseif (class_exists('ConsoleTools')) {
+                               // Run auto-detecting through console tools lib
+                               ConsoleTools::acquireSelfIPAddress();
+                       }
+               } // END - if
+
+               // Now get it from configuration
+               $serverAddress = $this->getServerAddress();
+
+               // Return it
+               return $serverAddress;
+       }
+
+       /**
+        * Setter for SERVER_ADDR
+        *
+        * @param       $serverAddress  New SERVER_ADDR value to set
+        * @return      void
+        */
+       public function setServerAddress ($serverAddress) {
+               $this->setConfigEntry('server_addr', (string) $serverAddress);
+       }
+
+       /**
+        * Getter for SERVER_ADDR
+        *
+        * @return      $serverAddress  New SERVER_ADDR value to set
+        */
+       public function getServerAddress () {
+               return $this->getConfigEntry('server_addr');
+       }
+
+       /**
+        * Detects the HTTPS flag
+        *
+        * @return      $https  The detected HTTPS flag or null if failed
+        */
+       public function detectHttpSecured () {
+               // Default is null
+               $https = NULL;
+
+               // Is HTTPS set?
+               if ($this->isHttpSecured()) {
+                       // Then use it
+                       $https = $_SERVER['HTTPS'];
+               } // END - if
+
+               // Return it
+               return $https;
+       }
+
+       /**
+        * Checks whether HTTPS is set in $_SERVER
+        *
+        * @return $isset       Whether HTTPS is set
+        */
+       public function isHttpSecured () {
+               return (isset($_SERVER['HTTPS']));
+       }
+
+       /**
+        * Dectect and return the base URL for all URLs and forms
+        *
+        * @return      $baseUrl        Detected base URL
+        */
+       public function detectBaseUrl () {
+               // Initialize the URL
+               $baseUrl = 'http';
+
+               // Do we have HTTPS?
+               if ($this->isHttpSecured()) {
+                       // Add the >s< for HTTPS
+                       $baseUrl .= 's';
+               } // END - if
+
+               // Construct the full URL and secure it against CSRF attacks
+               $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
+
+               // Return the URL
+               return $baseUrl;
+       }
+
+       /**
+        * Detect safely and return the full domain where this script is installed
+        *
+        * @return      $fullDomain             The detected full domain
+        */
+       public function detectDomain () {
+               // Full domain is localnet.invalid by default
+               $fullDomain = 'localnet.invalid';
+
+               // Is the server name there?
+               if (isset($_SERVER['SERVER_NAME'])) {
+                       // Detect the full domain
+                       $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
+               } // END - if
+
+               // Return it
+               return $fullDomain;
+       }
+
+       /**
+        * Detect safely the script path without trailing slash which is the glue
+        * between "http://your-domain.invalid/" and "script-name.php"
+        *
+        * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
+        */
+       public function detectScriptPath () {
+               // Default is empty
+               $scriptPath = '';
+
+               // Is the scriptname set?
+               if (isset($_SERVER['SCRIPT_NAME'])) {
+                       // Get dirname from it and replace back-slashes with slashes for lame OSes...
+                       $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
+               } // END - if
+
+               // Return it
+               return $scriptPath;
+       }
+
+       /**
+        * Getter for field name
+        *
+        * @param       $fieldName              Field name which we shall get
+        * @return      $fieldValue             Field value from the user
+        * @throws      NullPointerException    If the result instance is null
+        */
+       public final function getField ($fieldName) {
+               // Our super interface "FrameworkInterface" requires this
+               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+       }
+
+       /**
+        * Checks if given field is set
+        *
+        * @param       $fieldName      Field name to check
+        * @return      $isSet          Whether the given field name is set
+        * @throws      NullPointerException    If the result instance is null
+        */
+       public function isFieldSet ($fieldName) {
+               // Our super interface "FrameworkInterface" requires this
+               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+       }
+
+       /**
+        * Generates a code for hashes from this class
+        *
+        * @return      $hashCode       The hash code respresenting this class
+        */
+       public function hashCode () {
+               return crc32($this->__toString());
+       }
+
+       /**
+        * Checks whether an object equals this object. You should overwrite this
+        * method to implement own equality checks
+        *
+        * @param       $objectInstance         An instance of a FrameworkInterface object
+        * @return      $equals                         Whether both objects equals
+        */
+       public function equals (FrameworkInterface $objectInstance) {
+               // Now test it
+               $equals = ((
+                       $this->__toString() == $objectInstance->__toString()
+               ) && (
+                       $this->hashCode() == $objectInstance->hashCode()
+               ));
+
+               // Return the result
+               return $equals;
+       }
+}
+
+// [EOF]
+?>