3 * A class for the configuration stuff implemented in a singleton design paddern
5 * NOTE: We cannot put this in inc/main/ because it would be loaded (again) in
6 * class loader. See inc/loader/class_ClassLoader.php for instance
9 * @author Roland Haeder <webmaster@shipsimu.org>
11 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
12 * @license GNU GPL 3.0 or any newer version
13 * @link http://www.shipsimu.org
15 * This program is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 class FrameworkConfiguration implements Registerable {
30 * The framework's main configuration array which will be initialized with
31 * hard-coded configuration data and might be overwritten/extended by
32 * config data from the database.
34 private $config = array();
37 * The configuration instance itself
39 private static $configInstance = NULL;
41 // Some constants for the configuration system
42 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
43 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
44 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
47 * Protected constructor
51 protected function __construct () {
56 * Compatiblity method to return this class' name
58 * @return __CLASS__ This class' name
60 public function __toString () {
61 return get_class($this);
65 * Getter for a singleton instance of this class
67 * @return $configInstance A singleton instance of this class
69 public static final function getSelfInstance () {
70 // is the instance there?
71 if (is_null(self::$configInstance)) {
72 // Create a config instance
73 self::$configInstance = new FrameworkConfiguration();
76 // Return singleton instance
77 return self::$configInstance;
81 * Converts dashes to underscores, e.g. useable for configuration entries
83 * @param $str The string with maybe dashes inside
84 * @return $str The converted string with no dashed, but underscores
86 private final function convertDashesToUnderscores ($str) {
88 $str = str_replace('-', '_', $str);
90 // Return converted string
95 * Setter for default time zone (must be correct!)
97 * @param $zone The time-zone string (e.g. Europe/Berlin)
100 public final function setDefaultTimezone ($zone) {
101 // Is PHP version 5.1.0 or higher? Older versions are being ignored
102 if (version_compare(phpversion(), '5.1.0', '>=')) {
104 * Set desired time zone to prevent date() and related functions to
107 date_default_timezone_set($zone);
112 * Setter for runtime magic quotes
114 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
116 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
118 public final function setMagicQuotesRuntime ($enableQuotes) {
119 // Is the PHP version < 5.4?
120 if (version_compare(phpversion(), '5.4', '>=')) {
121 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
125 // Cast it to boolean
126 $enableQuotes = (boolean) $enableQuotes;
129 set_magic_quotes_runtime($enableQuotes);
133 * Checks whether the given configuration key is set
135 * @param $configKey The configuration key we shall check
136 * @return $isset Whether the given configuration key is set
138 public function isConfigurationEntrySet ($configKey) {
140 $isset = isset($this->config[$configKey]);
147 * Read a configuration element.
149 * @param $configKey The configuration element
150 * @return $configValue The fetched configuration value
151 * @throws ConfigEntryIsEmptyException If $configKey is empty
152 * @throws NoConfigEntryException If a configuration element was not found
154 public function getConfigEntry ($configKey) {
155 // Convert dashes to underscore
156 $configKey = self::convertDashesToUnderscores($configKey);
158 // Is a valid configuration key provided?
159 if (empty($configKey)) {
161 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
162 } elseif (!$this->isConfigurationEntrySet($configKey)) {
163 // Entry was not found!
164 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
167 // Return the requested value
168 return $this->config[$configKey];
172 * Set a configuration key
174 * @param $configKey The configuration key we want to add/change
175 * @param $configValue The configuration value we want to set
177 * @throws ConfigEntryIsEmptyException If $configKey is empty
178 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
180 public final function setConfigEntry ($configKey, $configValue) {
182 $configKey = self::convertDashesToUnderscores($configKey);
184 // Is a valid configuration key key provided?
185 if (is_null($configKey)) {
186 // Configuration key is null
187 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
188 } elseif ((empty($configKey)) || (!is_string($configKey))) {
190 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
191 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
192 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
193 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
196 // Set the configuration value
197 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
198 $this->config[$configKey] = $configValue;
201 ksort($this->config);
205 * Unset a configuration key, the entry must be there or else an
206 * exception is thrown.
208 * @param $configKey Configuration key to unset
210 * @throws NoConfigEntryException If a configuration element was not found
212 public final function unsetConfigEntry ($configKey) {
213 // Convert dashes to underscore
214 $configKey = self::convertDashesToUnderscores($configKey);
216 // Is the configuration key there?
217 if (!$this->isConfigurationEntrySet($configKey)) {
218 // Entry was not found!
219 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
223 unset($this->config[$configKey]);
227 * Detects the server address (SERVER_ADDR) and set it in configuration
229 * @return $serverAddress The detected server address
230 * @todo We have to add some more entries from $_SERVER here
232 public function detectServerAddress () {
234 if (!$this->isConfigurationEntrySet('server_addr')) {
235 // Is it set in $_SERVER?
236 if (isset($_SERVER['SERVER_ADDR'])) {
237 // Set it from $_SERVER
238 $this->setServerAddress($_SERVER['SERVER_ADDR']);
239 } elseif (class_exists('ConsoleTools')) {
240 // Run auto-detecting through console tools lib
241 ConsoleTools::acquireSelfIPAddress();
245 // Now get it from configuration
246 $serverAddress = $this->getServerAddress();
249 return $serverAddress;
253 * Setter for SERVER_ADDR
255 * @param $serverAddress New SERVER_ADDR value to set
258 public function setServerAddress ($serverAddress) {
259 $this->setConfigEntry('server_addr', (string) $serverAddress);
263 * Getter for SERVER_ADDR
265 * @return $serverAddress New SERVER_ADDR value to set
267 public function getServerAddress () {
268 return $this->getConfigEntry('server_addr');
272 * Detects the HTTPS flag
274 * @return $https The detected HTTPS flag or null if failed
276 public function detectHttpSecured () {
281 if ($this->isHttpSecured()) {
283 $https = $_SERVER['HTTPS'];
291 * Checks whether HTTPS is set in $_SERVER
293 * @return $isset Whether HTTPS is set
295 public function isHttpSecured () {
296 return (isset($_SERVER['HTTPS']));
300 * Dectect and return the base URL for all URLs and forms
302 * @return $baseUrl Detected base URL
304 public function detectBaseUrl () {
305 // Initialize the URL
309 if ($this->isHttpSecured()) {
310 // Add the >s< for HTTPS
314 // Construct the full URL and secure it against CSRF attacks
315 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
322 * Detect safely and return the full domain where this script is installed
324 * @return $fullDomain The detected full domain
326 public function detectDomain () {
327 // Full domain is localnet.invalid by default
328 $fullDomain = 'localnet.invalid';
330 // Is the server name there?
331 if (isset($_SERVER['SERVER_NAME'])) {
332 // Detect the full domain
333 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
341 * Detect safely the script path without trailing slash which is the glue
342 * between "http://your-domain.invalid/" and "script-name.php"
344 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
346 public function detectScriptPath () {
350 // Is the scriptname set?
351 if (isset($_SERVER['SCRIPT_NAME'])) {
352 // Get dirname from it and replace back-slashes with slashes for lame OSes...
353 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
361 * Getter for field name
363 * @param $fieldName Field name which we shall get
364 * @return $fieldValue Field value from the user
365 * @throws NullPointerException If the result instance is null
367 public final function getField ($fieldName) {
368 // Our super interface "FrameworkInterface" requires this
369 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
373 * Checks if given field is set
375 * @param $fieldName Field name to check
376 * @return $isSet Whether the given field name is set
377 * @throws NullPointerException If the result instance is null
379 public function isFieldSet ($fieldName) {
380 // Our super interface "FrameworkInterface" requires this
381 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
385 * Generates a code for hashes from this class
387 * @return $hashCode The hash code respresenting this class
389 public function hashCode () {
390 return crc32($this->__toString());
394 * Checks whether an object equals this object. You should overwrite this
395 * method to implement own equality checks
397 * @param $objectInstance An instance of a FrameworkInterface object
398 * @return $equals Whether both objects equals
400 public function equals (FrameworkInterface $objectInstance) {
403 $this->__toString() == $objectInstance->__toString()
405 $this->hashCode() == $objectInstance->hashCode()