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\Registry\Registerable;
13 * A class for the configuration stuff implemented in a singleton design paddern
15 * NOTE: We cannot put this in framework/main/ because it would be loaded (again) in
16 * class loader. See framework/loader/class_ClassLoader.php for instance
19 * @author Roland Haeder <webmaster@shipsimu.org>
21 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
22 * @license GNU GPL 3.0 or any newer version
23 * @link http://www.shipsimu.org
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 class FrameworkConfiguration implements Registerable {
40 * The framework's main configuration array which will be initialized with
41 * hard-coded configuration data and might be overwritten/extended by
42 * config data from the database.
44 private $config = array();
47 * The configuration instance itself
49 private static $configInstance = NULL;
51 // Some constants for the configuration system
52 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
53 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
54 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
57 * Protected constructor
61 protected function __construct () {
66 * Compatiblity method to return this class' name
68 * @return __CLASS__ This class' name
70 public function __toString () {
71 return get_class($this);
75 * Getter for a singleton instance of this class
77 * @return $configInstance A singleton instance of this class
79 public static final function getSelfInstance () {
80 // is the instance there?
81 if (is_null(self::$configInstance)) {
82 // Create a config instance
83 self::$configInstance = new FrameworkConfiguration();
86 // Return singleton instance
87 return self::$configInstance;
91 * Converts dashes to underscores, e.g. useable for configuration entries
93 * @param $str The string with maybe dashes inside
94 * @return $str The converted string with no dashed, but underscores
96 private final function convertDashesToUnderscores ($str) {
98 $str = str_replace('-', '_', $str);
100 // Return converted string
105 * Setter for default time zone (must be correct!)
107 * @param $zone The time-zone string (e.g. Europe/Berlin)
110 public final function setDefaultTimezone ($zone) {
111 // Is PHP version 5.1.0 or higher? Older versions are being ignored
112 if (version_compare(phpversion(), '5.1.0', '>=')) {
114 * Set desired time zone to prevent date() and related functions to
117 date_default_timezone_set($zone);
122 * Setter for runtime magic quotes
124 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
126 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
128 public final function setMagicQuotesRuntime ($enableQuotes) {
129 // Is the PHP version < 5.4?
130 if (version_compare(phpversion(), '5.4', '>=')) {
131 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
135 // Cast it to boolean
136 $enableQuotes = (boolean) $enableQuotes;
139 set_magic_quotes_runtime($enableQuotes);
143 * Checks whether the given configuration key is set
145 * @param $configKey The configuration key we shall check
146 * @return $isset Whether the given configuration key is set
148 public function isConfigurationEntrySet ($configKey) {
150 $isset = isset($this->config[$configKey]);
157 * Read a configuration element.
159 * @param $configKey The configuration element
160 * @return $configValue The fetched configuration value
161 * @throws ConfigEntryIsEmptyException If $configKey is empty
162 * @throws NoConfigEntryException If a configuration element was not found
164 public function getConfigEntry ($configKey) {
165 // Convert dashes to underscore
166 $configKey = self::convertDashesToUnderscores($configKey);
168 // Is a valid configuration key provided?
169 if (empty($configKey)) {
171 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
172 } elseif (!$this->isConfigurationEntrySet($configKey)) {
173 // Entry was not found!
174 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
177 // Return the requested value
178 return $this->config[$configKey];
182 * Set a configuration key
184 * @param $configKey The configuration key we want to add/change
185 * @param $configValue The configuration value we want to set
187 * @throws ConfigEntryIsEmptyException If $configKey is empty
188 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
190 public final function setConfigEntry ($configKey, $configValue) {
192 $configKey = self::convertDashesToUnderscores($configKey);
194 // Is a valid configuration key key provided?
195 if (is_null($configKey)) {
196 // Configuration key is null
197 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
198 } elseif ((empty($configKey)) || (!is_string($configKey))) {
200 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
201 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
202 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
203 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
206 // Set the configuration value
207 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
208 $this->config[$configKey] = $configValue;
211 ksort($this->config);
215 * Getter for whole configuration array
217 * @return $config Configuration array
219 public final function getConfigurationArray () {
221 return $this->config;
225 * Unset a configuration key, the entry must be there or else an
226 * exception is thrown.
228 * @param $configKey Configuration key to unset
230 * @throws NoConfigEntryException If a configuration element was not found
232 public final function unsetConfigEntry ($configKey) {
233 // Convert dashes to underscore
234 $configKey = self::convertDashesToUnderscores($configKey);
236 // Is the configuration key there?
237 if (!$this->isConfigurationEntrySet($configKey)) {
238 // Entry was not found!
239 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
243 unset($this->config[$configKey]);
247 * Detects the server address (SERVER_ADDR) and set it in configuration
249 * @return $serverAddress The detected server address
250 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
251 * @todo Have to check some more entries from $_SERVER here
253 public function detectServerAddress () {
255 if (!$this->isConfigurationEntrySet('server_addr')) {
256 // Is it set in $_SERVER?
257 if (isset($_SERVER['SERVER_ADDR'])) {
258 // Set it from $_SERVER
259 $this->setServerAddress($_SERVER['SERVER_ADDR']);
260 } elseif (isset($_SERVER['SERVER_NAME'])) {
261 // Resolve IP address
262 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
265 if ($serverIp === false) {
267 * Why is gethostbyname() returning the host name and not
268 * false as many other PHP functions are doing? ;-(
270 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
274 $this->setServerAddress($serverIp);
276 // Run auto-detecting through console tools lib
277 ConsoleTools::acquireSelfIPAddress();
281 // Now get it from configuration
282 $serverAddress = $this->getServerAddress();
285 return $serverAddress;
289 * Setter for SERVER_ADDR
291 * @param $serverAddress New SERVER_ADDR value to set
294 public function setServerAddress ($serverAddress) {
295 $this->setConfigEntry('server_addr', (string) $serverAddress);
299 * Getter for SERVER_ADDR
301 * @return $serverAddress New SERVER_ADDR value to set
303 public function getServerAddress () {
304 return $this->getConfigEntry('server_addr');
308 * Detects the HTTPS flag
310 * @return $isSecured The detected HTTPS flag or null if failed
312 public function detectHttpSecured () {
317 if ($this->isHttpSecured()) {
319 $isSecured = $_SERVER['HTTPS'];
327 * Checks whether HTTPS is set in $_SERVER
329 * @return $isset Whether HTTPS is set
331 public function isHttpSecured () {
332 return (isset($_SERVER['HTTPS']));
336 * Dectect and return the base URL for all URLs and forms
338 * @return $baseUrl Detected base URL
340 public function detectBaseUrl () {
341 // Initialize the URL
345 if ($this->isHttpSecured()) {
346 // Add the >s< for HTTPS
350 // Construct the full URL and secure it against CSRF attacks
351 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
358 * Detect safely and return the full domain where this script is installed
360 * @return $fullDomain The detected full domain
362 public function detectDomain () {
363 // Full domain is localnet.invalid by default
364 $fullDomain = 'localnet.invalid';
366 // Is the server name there?
367 if (isset($_SERVER['SERVER_NAME'])) {
368 // Detect the full domain
369 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
377 * Detect safely the script path without trailing slash which is the glue
378 * between "http://your-domain.invalid/" and "script-name.php"
380 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
382 public function detectScriptPath () {
386 // Is the scriptname set?
387 if (isset($_SERVER['SCRIPT_NAME'])) {
388 // Get dirname from it and replace back-slashes with slashes for lame OSes...
389 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
397 * Getter for field name
399 * @param $fieldName Field name which we shall get
400 * @return $fieldValue Field value from the user
401 * @throws NullPointerException If the result instance is null
403 public final function getField ($fieldName) {
404 // The super interface "FrameworkInterface" requires this
405 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
409 * Checks if given field is set
411 * @param $fieldName Field name to check
412 * @return $isSet Whether the given field name is set
413 * @throws NullPointerException If the result instance is null
415 public function isFieldSet ($fieldName) {
416 // The super interface "FrameworkInterface" requires this
417 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
421 * Generates a code for hashes from this class
423 * @return $hashCode The hash code respresenting this class
425 public function hashCode () {
426 return crc32($this->__toString());
430 * Checks whether an object equals this object. You should overwrite this
431 * method to implement own equality checks
433 * @param $objectInstance An instance of a FrameworkInterface object
434 * @return $equals Whether both objects equals
436 public function equals (FrameworkInterface $objectInstance) {
439 $this->__toString() === $objectInstance->__toString()
441 $this->hashCode() === $objectInstance->hashCode()