3 namespace CoreFramework\Configuration;
5 // Import framework stuff
6 use CoreFramework\Console\Tools\ConsoleTools;
7 use CoreFramework\Dns\UnknownHostnameException;
8 use CoreFramework\Generic\FrameworkInterface;
9 use CoreFramework\Generic\NullPointerException;
10 use CoreFramework\Generic\UnsupportedOperationException;
11 use CoreFramework\Registry\Registerable;
14 * A class for the configuration stuff implemented in a singleton design paddern
16 * NOTE: We cannot put this in framework/main/ because it would be loaded (again) in
17 * class loader. See framework/loader/class_ClassLoader.php for instance
20 * @author Roland Haeder <webmaster@shipsimu.org>
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
23 * @license GNU GPL 3.0 or any newer version
24 * @link http://www.shipsimu.org
26 * This program is free software: you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation, either version 3 of the License, or
29 * (at your option) any later version.
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 class FrameworkConfiguration implements Registerable {
41 * The framework's main configuration array which will be initialized with
42 * hard-coded configuration data and might be overwritten/extended by
43 * config data from the database.
45 private $config = array();
48 * The configuration instance itself
50 private static $configInstance = NULL;
53 * Call-back instance (unused)
55 private $callbackInstance = NULL;
57 // Some constants for the configuration system
58 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
59 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
60 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
63 * Protected constructor
67 protected function __construct () {
72 * Compatiblity method to return this class' name
74 * @return __CLASS__ This class' name
76 public function __toString () {
77 return get_class($this);
81 * Getter for a singleton instance of this class
83 * @return $configInstance A singleton instance of this class
85 public static final function getSelfInstance () {
86 // is the instance there?
87 if (is_null(self::$configInstance)) {
88 // Create a config instance
89 self::$configInstance = new FrameworkConfiguration();
92 // Return singleton instance
93 return self::$configInstance;
97 * Converts dashes to underscores, e.g. useable for configuration entries
99 * @param $str The string with maybe dashes inside
100 * @return $str The converted string with no dashed, but underscores
102 private final function convertDashesToUnderscores ($str) {
104 $str = str_replace('-', '_', $str);
106 // Return converted string
111 * Setter for default time zone (must be correct!)
113 * @param $zone The time-zone string (e.g. Europe/Berlin)
116 public final function setDefaultTimezone ($zone) {
117 // Is PHP version 5.1.0 or higher? Older versions are being ignored
118 if (version_compare(phpversion(), '5.1.0', '>=')) {
120 * Set desired time zone to prevent date() and related functions to
123 date_default_timezone_set($zone);
128 * Checks whether the given configuration key is set
130 * @param $configKey The configuration key we shall check
131 * @return $isset Whether the given configuration key is set
133 public function isConfigurationEntrySet ($configKey) {
135 $isset = isset($this->config[$configKey]);
142 * Read a configuration element.
144 * @param $configKey The configuration element
145 * @return $configValue The fetched configuration value
146 * @throws ConfigEntryIsEmptyException If $configKey is empty
147 * @throws NoConfigEntryException If a configuration element was not found
149 public function getConfigEntry ($configKey) {
150 // Convert dashes to underscore
151 $configKey = self::convertDashesToUnderscores($configKey);
153 // Is a valid configuration key provided?
154 if (empty($configKey)) {
156 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
157 } elseif (!$this->isConfigurationEntrySet($configKey)) {
158 // Entry was not found!
159 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
162 // Return the requested value
163 return $this->config[$configKey];
167 * Set a configuration key
169 * @param $configKey The configuration key we want to add/change
170 * @param $configValue The configuration value we want to set
172 * @throws ConfigEntryIsEmptyException If $configKey is empty
173 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
175 public final function setConfigEntry ($configKey, $configValue) {
177 $configKey = self::convertDashesToUnderscores($configKey);
179 // Is a valid configuration key key provided?
180 if (is_null($configKey)) {
181 // Configuration key is null
182 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
183 } elseif ((empty($configKey)) || (!is_string($configKey))) {
185 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
186 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
187 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
188 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
191 // Set the configuration value
192 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
193 $this->config[$configKey] = $configValue;
196 ksort($this->config);
200 * Getter for whole configuration array
202 * @return $config Configuration array
204 public final function getConfigurationArray () {
206 return $this->config;
210 * Unset a configuration key, the entry must be there or else an
211 * exception is thrown.
213 * @param $configKey Configuration key to unset
215 * @throws NoConfigEntryException If a configuration element was not found
217 public final function unsetConfigEntry ($configKey) {
218 // Convert dashes to underscore
219 $configKey = self::convertDashesToUnderscores($configKey);
221 // Is the configuration key there?
222 if (!$this->isConfigurationEntrySet($configKey)) {
223 // Entry was not found!
224 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
228 unset($this->config[$configKey]);
232 * Detects the server address (SERVER_ADDR) and set it in configuration
234 * @return $serverAddress The detected server address
235 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
236 * @todo Have to check some more entries from $_SERVER here
238 public function detectServerAddress () {
240 if (!$this->isConfigurationEntrySet('server_addr')) {
241 // Is it set in $_SERVER?
242 if (isset($_SERVER['SERVER_ADDR'])) {
243 // Set it from $_SERVER
244 $this->setServerAddress($_SERVER['SERVER_ADDR']);
245 } elseif (isset($_SERVER['SERVER_NAME'])) {
246 // Resolve IP address
247 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
250 if ($serverIp === false) {
252 * Why is gethostbyname() returning the host name and not
253 * false as many other PHP functions are doing? ;-(
255 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
259 $this->setServerAddress($serverIp);
261 // Run auto-detecting through console tools lib
262 ConsoleTools::acquireSelfIPAddress();
266 // Now get it from configuration
267 $serverAddress = $this->getServerAddress();
270 return $serverAddress;
274 * Setter for SERVER_ADDR
276 * @param $serverAddress New SERVER_ADDR value to set
279 public function setServerAddress ($serverAddress) {
280 $this->setConfigEntry('server_addr', (string) $serverAddress);
284 * Getter for SERVER_ADDR
286 * @return $serverAddress New SERVER_ADDR value to set
288 public function getServerAddress () {
289 return $this->getConfigEntry('server_addr');
293 * Detects the HTTPS flag
295 * @return $isSecured The detected HTTPS flag or null if failed
297 public function detectHttpSecured () {
302 if ($this->isHttpSecured()) {
304 $isSecured = $_SERVER['HTTPS'];
312 * Checks whether HTTPS is set in $_SERVER
314 * @return $isset Whether HTTPS is set
316 public function isHttpSecured () {
317 return (isset($_SERVER['HTTPS']));
321 * Dectect and return the base URL for all URLs and forms
323 * @return $baseUrl Detected base URL
325 public function detectBaseUrl () {
326 // Initialize the URL
330 if ($this->isHttpSecured()) {
331 // Add the >s< for HTTPS
335 // Construct the full URL and secure it against CSRF attacks
336 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
343 * Detect safely and return the full domain where this script is installed
345 * @return $fullDomain The detected full domain
347 public function detectDomain () {
348 // Full domain is localnet.invalid by default
349 $fullDomain = 'localnet.invalid';
351 // Is the server name there?
352 if (isset($_SERVER['SERVER_NAME'])) {
353 // Detect the full domain
354 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
362 * Detect safely the script path without trailing slash which is the glue
363 * between "http://your-domain.invalid/" and "script-name.php"
365 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
367 public function detectScriptPath () {
371 // Is the scriptname set?
372 if (isset($_SERVER['SCRIPT_NAME'])) {
373 // Get dirname from it and replace back-slashes with slashes for lame OSes...
374 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
382 * Getter for field name
384 * @param $fieldName Field name which we shall get
385 * @return $fieldValue Field value from the user
386 * @throws NullPointerException If the result instance is null
388 public final function getField ($fieldName) {
389 // The super interface "FrameworkInterface" requires this
390 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
394 * Checks if given field is set
396 * @param $fieldName Field name to check
397 * @return $isSet Whether the given field name is set
398 * @throws NullPointerException If the result instance is null
400 public function isFieldSet ($fieldName) {
401 // The super interface "FrameworkInterface" requires this
402 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
406 * Generates a code for hashes from this class
408 * @return $hashCode The hash code respresenting this class
410 public function hashCode () {
411 return crc32($this->__toString());
415 * Checks whether an object equals this object. You should overwrite this
416 * method to implement own equality checks
418 * @param $objectInstance An instance of a FrameworkInterface object
419 * @return $equals Whether both objects equals
421 public function equals (FrameworkInterface $objectInstance) {
424 $this->__toString() === $objectInstance->__toString()
426 $this->hashCode() === $objectInstance->hashCode()
434 * Setter for call-back instance
436 * @param $callbackInstance An instance of a FrameworkInterface class
439 public function setCallbackInstance (FrameworkInterface $callbackInstance) {
440 $this->callbackInstance = $callbackInstance;