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;
52 // Some constants for the configuration system
53 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
54 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
55 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
58 * Protected constructor
62 protected function __construct () {
67 * Compatiblity method to return this class' name
69 * @return __CLASS__ This class' name
71 public function __toString () {
72 return get_class($this);
76 * Getter for a singleton instance of this class
78 * @return $configInstance A singleton instance of this class
80 public static final function getSelfInstance () {
81 // is the instance there?
82 if (is_null(self::$configInstance)) {
83 // Create a config instance
84 self::$configInstance = new FrameworkConfiguration();
87 // Return singleton instance
88 return self::$configInstance;
92 * Converts dashes to underscores, e.g. useable for configuration entries
94 * @param $str The string with maybe dashes inside
95 * @return $str The converted string with no dashed, but underscores
97 private final function convertDashesToUnderscores ($str) {
99 $str = str_replace('-', '_', $str);
101 // Return converted string
106 * Setter for default time zone (must be correct!)
108 * @param $zone The time-zone string (e.g. Europe/Berlin)
111 public final function setDefaultTimezone ($zone) {
112 // Is PHP version 5.1.0 or higher? Older versions are being ignored
113 if (version_compare(phpversion(), '5.1.0', '>=')) {
115 * Set desired time zone to prevent date() and related functions to
118 date_default_timezone_set($zone);
123 * Setter for runtime magic quotes
125 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
127 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
129 public final function setMagicQuotesRuntime ($enableQuotes) {
130 // Is the PHP version < 5.4?
131 if (version_compare(phpversion(), '5.4', '>=')) {
132 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
136 // Cast it to boolean
137 $enableQuotes = (boolean) $enableQuotes;
140 set_magic_quotes_runtime($enableQuotes);
144 * Checks whether the given configuration key is set
146 * @param $configKey The configuration key we shall check
147 * @return $isset Whether the given configuration key is set
149 public function isConfigurationEntrySet ($configKey) {
151 $isset = isset($this->config[$configKey]);
158 * Read a configuration element.
160 * @param $configKey The configuration element
161 * @return $configValue The fetched configuration value
162 * @throws ConfigEntryIsEmptyException If $configKey is empty
163 * @throws NoConfigEntryException If a configuration element was not found
165 public function getConfigEntry ($configKey) {
166 // Convert dashes to underscore
167 $configKey = self::convertDashesToUnderscores($configKey);
169 // Is a valid configuration key provided?
170 if (empty($configKey)) {
172 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
173 } elseif (!$this->isConfigurationEntrySet($configKey)) {
174 // Entry was not found!
175 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
178 // Return the requested value
179 return $this->config[$configKey];
183 * Set a configuration key
185 * @param $configKey The configuration key we want to add/change
186 * @param $configValue The configuration value we want to set
188 * @throws ConfigEntryIsEmptyException If $configKey is empty
189 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
191 public final function setConfigEntry ($configKey, $configValue) {
193 $configKey = self::convertDashesToUnderscores($configKey);
195 // Is a valid configuration key key provided?
196 if (is_null($configKey)) {
197 // Configuration key is null
198 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
199 } elseif ((empty($configKey)) || (!is_string($configKey))) {
201 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
202 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
203 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
204 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
207 // Set the configuration value
208 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
209 $this->config[$configKey] = $configValue;
212 ksort($this->config);
216 * Getter for whole configuration array
218 * @return $config Configuration array
220 public final function getConfigurationArray () {
222 return $this->config;
226 * Unset a configuration key, the entry must be there or else an
227 * exception is thrown.
229 * @param $configKey Configuration key to unset
231 * @throws NoConfigEntryException If a configuration element was not found
233 public final function unsetConfigEntry ($configKey) {
234 // Convert dashes to underscore
235 $configKey = self::convertDashesToUnderscores($configKey);
237 // Is the configuration key there?
238 if (!$this->isConfigurationEntrySet($configKey)) {
239 // Entry was not found!
240 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
244 unset($this->config[$configKey]);
248 * Detects the server address (SERVER_ADDR) and set it in configuration
250 * @return $serverAddress The detected server address
251 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
252 * @todo Have to check some more entries from $_SERVER here
254 public function detectServerAddress () {
256 if (!$this->isConfigurationEntrySet('server_addr')) {
257 // Is it set in $_SERVER?
258 if (isset($_SERVER['SERVER_ADDR'])) {
259 // Set it from $_SERVER
260 $this->setServerAddress($_SERVER['SERVER_ADDR']);
261 } elseif (isset($_SERVER['SERVER_NAME'])) {
262 // Resolve IP address
263 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
266 if ($serverIp === false) {
268 * Why is gethostbyname() returning the host name and not
269 * false as many other PHP functions are doing? ;-(
271 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
275 $this->setServerAddress($serverIp);
277 // Run auto-detecting through console tools lib
278 ConsoleTools::acquireSelfIPAddress();
282 // Now get it from configuration
283 $serverAddress = $this->getServerAddress();
286 return $serverAddress;
290 * Setter for SERVER_ADDR
292 * @param $serverAddress New SERVER_ADDR value to set
295 public function setServerAddress ($serverAddress) {
296 $this->setConfigEntry('server_addr', (string) $serverAddress);
300 * Getter for SERVER_ADDR
302 * @return $serverAddress New SERVER_ADDR value to set
304 public function getServerAddress () {
305 return $this->getConfigEntry('server_addr');
309 * Detects the HTTPS flag
311 * @return $isSecured The detected HTTPS flag or null if failed
313 public function detectHttpSecured () {
318 if ($this->isHttpSecured()) {
320 $isSecured = $_SERVER['HTTPS'];
328 * Checks whether HTTPS is set in $_SERVER
330 * @return $isset Whether HTTPS is set
332 public function isHttpSecured () {
333 return (isset($_SERVER['HTTPS']));
337 * Dectect and return the base URL for all URLs and forms
339 * @return $baseUrl Detected base URL
341 public function detectBaseUrl () {
342 // Initialize the URL
346 if ($this->isHttpSecured()) {
347 // Add the >s< for HTTPS
351 // Construct the full URL and secure it against CSRF attacks
352 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
359 * Detect safely and return the full domain where this script is installed
361 * @return $fullDomain The detected full domain
363 public function detectDomain () {
364 // Full domain is localnet.invalid by default
365 $fullDomain = 'localnet.invalid';
367 // Is the server name there?
368 if (isset($_SERVER['SERVER_NAME'])) {
369 // Detect the full domain
370 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
378 * Detect safely the script path without trailing slash which is the glue
379 * between "http://your-domain.invalid/" and "script-name.php"
381 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
383 public function detectScriptPath () {
387 // Is the scriptname set?
388 if (isset($_SERVER['SCRIPT_NAME'])) {
389 // Get dirname from it and replace back-slashes with slashes for lame OSes...
390 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
398 * Getter for field name
400 * @param $fieldName Field name which we shall get
401 * @return $fieldValue Field value from the user
402 * @throws NullPointerException If the result instance is null
404 public final function getField ($fieldName) {
405 // The super interface "FrameworkInterface" requires this
406 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
410 * Checks if given field is set
412 * @param $fieldName Field name to check
413 * @return $isSet Whether the given field name is set
414 * @throws NullPointerException If the result instance is null
416 public function isFieldSet ($fieldName) {
417 // The super interface "FrameworkInterface" requires this
418 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
422 * Generates a code for hashes from this class
424 * @return $hashCode The hash code respresenting this class
426 public function hashCode () {
427 return crc32($this->__toString());
431 * Checks whether an object equals this object. You should overwrite this
432 * method to implement own equality checks
434 * @param $objectInstance An instance of a FrameworkInterface object
435 * @return $equals Whether both objects equals
437 public function equals (FrameworkInterface $objectInstance) {
440 $this->__toString() === $objectInstance->__toString()
442 $this->hashCode() === $objectInstance->hashCode()