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 * Setter for runtime magic quotes
130 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
132 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
134 public final function setMagicQuotesRuntime ($enableQuotes) {
135 // Is the PHP version < 5.4?
136 if (version_compare(phpversion(), '5.4', '>=')) {
137 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
141 // Cast it to boolean
142 $enableQuotes = (boolean) $enableQuotes;
145 set_magic_quotes_runtime($enableQuotes);
149 * Checks whether the given configuration key is set
151 * @param $configKey The configuration key we shall check
152 * @return $isset Whether the given configuration key is set
154 public function isConfigurationEntrySet ($configKey) {
156 $isset = isset($this->config[$configKey]);
163 * Read a configuration element.
165 * @param $configKey The configuration element
166 * @return $configValue The fetched configuration value
167 * @throws ConfigEntryIsEmptyException If $configKey is empty
168 * @throws NoConfigEntryException If a configuration element was not found
170 public function getConfigEntry ($configKey) {
171 // Convert dashes to underscore
172 $configKey = self::convertDashesToUnderscores($configKey);
174 // Is a valid configuration key provided?
175 if (empty($configKey)) {
177 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
178 } elseif (!$this->isConfigurationEntrySet($configKey)) {
179 // Entry was not found!
180 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
183 // Return the requested value
184 return $this->config[$configKey];
188 * Set a configuration key
190 * @param $configKey The configuration key we want to add/change
191 * @param $configValue The configuration value we want to set
193 * @throws ConfigEntryIsEmptyException If $configKey is empty
194 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
196 public final function setConfigEntry ($configKey, $configValue) {
198 $configKey = self::convertDashesToUnderscores($configKey);
200 // Is a valid configuration key key provided?
201 if (is_null($configKey)) {
202 // Configuration key is null
203 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
204 } elseif ((empty($configKey)) || (!is_string($configKey))) {
206 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
207 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
208 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
209 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
212 // Set the configuration value
213 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
214 $this->config[$configKey] = $configValue;
217 ksort($this->config);
221 * Getter for whole configuration array
223 * @return $config Configuration array
225 public final function getConfigurationArray () {
227 return $this->config;
231 * Unset a configuration key, the entry must be there or else an
232 * exception is thrown.
234 * @param $configKey Configuration key to unset
236 * @throws NoConfigEntryException If a configuration element was not found
238 public final function unsetConfigEntry ($configKey) {
239 // Convert dashes to underscore
240 $configKey = self::convertDashesToUnderscores($configKey);
242 // Is the configuration key there?
243 if (!$this->isConfigurationEntrySet($configKey)) {
244 // Entry was not found!
245 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
249 unset($this->config[$configKey]);
253 * Detects the server address (SERVER_ADDR) and set it in configuration
255 * @return $serverAddress The detected server address
256 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
257 * @todo Have to check some more entries from $_SERVER here
259 public function detectServerAddress () {
261 if (!$this->isConfigurationEntrySet('server_addr')) {
262 // Is it set in $_SERVER?
263 if (isset($_SERVER['SERVER_ADDR'])) {
264 // Set it from $_SERVER
265 $this->setServerAddress($_SERVER['SERVER_ADDR']);
266 } elseif (isset($_SERVER['SERVER_NAME'])) {
267 // Resolve IP address
268 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
271 if ($serverIp === false) {
273 * Why is gethostbyname() returning the host name and not
274 * false as many other PHP functions are doing? ;-(
276 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
280 $this->setServerAddress($serverIp);
282 // Run auto-detecting through console tools lib
283 ConsoleTools::acquireSelfIPAddress();
287 // Now get it from configuration
288 $serverAddress = $this->getServerAddress();
291 return $serverAddress;
295 * Setter for SERVER_ADDR
297 * @param $serverAddress New SERVER_ADDR value to set
300 public function setServerAddress ($serverAddress) {
301 $this->setConfigEntry('server_addr', (string) $serverAddress);
305 * Getter for SERVER_ADDR
307 * @return $serverAddress New SERVER_ADDR value to set
309 public function getServerAddress () {
310 return $this->getConfigEntry('server_addr');
314 * Detects the HTTPS flag
316 * @return $isSecured The detected HTTPS flag or null if failed
318 public function detectHttpSecured () {
323 if ($this->isHttpSecured()) {
325 $isSecured = $_SERVER['HTTPS'];
333 * Checks whether HTTPS is set in $_SERVER
335 * @return $isset Whether HTTPS is set
337 public function isHttpSecured () {
338 return (isset($_SERVER['HTTPS']));
342 * Dectect and return the base URL for all URLs and forms
344 * @return $baseUrl Detected base URL
346 public function detectBaseUrl () {
347 // Initialize the URL
351 if ($this->isHttpSecured()) {
352 // Add the >s< for HTTPS
356 // Construct the full URL and secure it against CSRF attacks
357 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
364 * Detect safely and return the full domain where this script is installed
366 * @return $fullDomain The detected full domain
368 public function detectDomain () {
369 // Full domain is localnet.invalid by default
370 $fullDomain = 'localnet.invalid';
372 // Is the server name there?
373 if (isset($_SERVER['SERVER_NAME'])) {
374 // Detect the full domain
375 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
383 * Detect safely the script path without trailing slash which is the glue
384 * between "http://your-domain.invalid/" and "script-name.php"
386 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
388 public function detectScriptPath () {
392 // Is the scriptname set?
393 if (isset($_SERVER['SCRIPT_NAME'])) {
394 // Get dirname from it and replace back-slashes with slashes for lame OSes...
395 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
403 * Getter for field name
405 * @param $fieldName Field name which we shall get
406 * @return $fieldValue Field value from the user
407 * @throws NullPointerException If the result instance is null
409 public final function getField ($fieldName) {
410 // The super interface "FrameworkInterface" requires this
411 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
415 * Checks if given field is set
417 * @param $fieldName Field name to check
418 * @return $isSet Whether the given field name is set
419 * @throws NullPointerException If the result instance is null
421 public function isFieldSet ($fieldName) {
422 // The super interface "FrameworkInterface" requires this
423 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
427 * Generates a code for hashes from this class
429 * @return $hashCode The hash code respresenting this class
431 public function hashCode () {
432 return crc32($this->__toString());
436 * Checks whether an object equals this object. You should overwrite this
437 * method to implement own equality checks
439 * @param $objectInstance An instance of a FrameworkInterface object
440 * @return $equals Whether both objects equals
442 public function equals (FrameworkInterface $objectInstance) {
445 $this->__toString() === $objectInstance->__toString()
447 $this->hashCode() === $objectInstance->hashCode()
455 * Setter for call-back instance
457 * @param $callbackInstance An instance of a FrameworkInterface class
460 public function setCallbackInstance (FrameworkInterface $callbackInstance) {
461 $this->callbackInstance = $callbackInstance;