4 namespace CoreFramework\Configuration;
6 // Import framework stuff
7 use CoreFramework\Console\Tools\ConsoleTools;
8 use CoreFramework\Dns\UnknownHostnameException;
9 use CoreFramework\Generic\FrameworkInterface;
10 use CoreFramework\Generic\NullPointerException;
11 use CoreFramework\Generic\UnsupportedOperationException;
12 use CoreFramework\Object\BaseFrameworkSystem;
13 use CoreFramework\Registry\Registerable;
16 use \InvalidArgumentException;
19 * A class for the configuration stuff implemented in a singleton design paddern
21 * NOTE: We cannot put this in framework/main/ because it would be loaded (again) in
22 * class loader. See framework/loader/class_ClassLoader.php for instance
25 * @author Roland Haeder <webmaster@shipsimu.org>
27 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.shipsimu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 class FrameworkConfiguration implements Registerable {
47 * The framework's main configuration array which will be initialized with
48 * hard-coded configuration data and might be overwritten/extended by
49 * config data from the database.
51 private $config = array();
54 * The configuration instance itself
56 private static $configInstance = NULL;
59 * Call-back instance (unused)
61 private $callbackInstance = NULL;
63 // Some constants for the configuration system
64 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
65 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
66 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
73 private function __construct () {
78 * Compatiblity method to return this class' name
80 * @return __CLASS__ This class' name
82 public function __toString () {
83 return get_class($this);
87 * Getter for a singleton instance of this class
89 * @return $configInstance A singleton instance of this class
91 public static final function getSelfInstance () {
92 // is the instance there?
93 if (is_null(self::$configInstance)) {
94 // Create a config instance
95 self::$configInstance = new FrameworkConfiguration();
98 // Return singleton instance
99 return self::$configInstance;
103 * Converts dashes to underscores, e.g. useable for configuration entries
105 * @param $str The string with maybe dashes inside
106 * @return $str The converted string with no dashed, but underscores
107 * @throws NullPointerException If $str is null
108 * @throws InvalidArgumentException If $str is empty
110 private final function convertDashesToUnderscores ($str) {
114 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
115 } elseif (empty($str)) {
117 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
121 $str = str_replace('-', '_', $str);
123 // Return converted string
128 * Setter for default time zone (must be correct!)
130 * @param $timezone The timezone string (e.g. Europe/Berlin)
131 * @return $success If timezone was accepted
132 * @throws NullPointerException If $timezone is NULL
133 * @throws InvalidArgumentException If $timezone is empty
135 public final function setDefaultTimezone ($timezone) {
137 if (is_null($timezone)) {
139 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
140 } elseif (!is_string($timezone)) {
142 throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
143 } elseif (empty($timezone)) {
145 throw new InvalidArgumentException('timezone is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
152 * Set desired time zone to prevent date() and related functions to
153 * issue an E_WARNING.
155 $success = date_default_timezone_set($timezone);
162 * Checks whether the given configuration key is set
164 * @param $configKey The configuration key we shall check
165 * @return $isset Whether the given configuration key is set
166 * @throws NullPointerException If $configKey is NULL
167 * @throws InvalidArgumentException If $configKey is empty
169 public function isConfigurationEntrySet ($configKey) {
171 if (is_null($configKey)) {
173 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
174 } elseif (!is_string($configKey)) {
176 throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
177 } elseif (empty($configKey)) {
179 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
183 $isset = ((isset($this->config[$configKey])) || (array_key_exists($configKey, $this->config)));
190 * Read a configuration element.
192 * @param $configKey The configuration element
193 * @return $configValue The fetched configuration value
194 * @throws NullPointerException If $configKey is NULL
195 * @throws InvalidArgumentException If $configKey is empty
196 * @throws NoConfigEntryException If a configuration element was not found
198 public function getConfigEntry ($configKey) {
200 if (is_null($configKey)) {
202 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
203 } elseif (!is_string($configKey)) {
205 throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
206 } elseif (empty($configKey)) {
208 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
211 // Convert dashes to underscore
212 $configKey = self::convertDashesToUnderscores($configKey);
214 // Is a valid configuration key provided?
215 if (!$this->isConfigurationEntrySet($configKey)) {
216 // Entry was not found!
217 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
220 // Return the requested value
221 return $this->config[$configKey];
225 * Set a configuration key
227 * @param $configKey The configuration key we want to add/change
228 * @param $configValue The configuration value we want to set
230 * @throws NullPointerException If $configKey is NULL
231 * @throws InvalidArgumentException If $configKey is empty
232 * @throws InvalidArgumentException If $configValue has an unsupported variable type
234 public final function setConfigEntry ($configKey, $configValue) {
235 // Is a valid configuration key key provided?
236 if (is_null($configKey)) {
237 // Configuration key is null
238 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
239 } elseif (!is_string($configKey)) {
241 throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
242 } elseif (empty($configKey)) {
244 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
245 } elseif ((is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
246 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
247 throw new InvalidArgumentException(sprintf('configValue[]=%s for configKey=%s is not supported.', gettype($configValue), $configKey), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
251 $configKey = self::convertDashesToUnderscores($configKey);
253 // Set the configuration value
254 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
255 $this->config[$configKey] = $configValue;
258 ksort($this->config);
262 * Getter for whole configuration array
264 * @return $config Configuration array
266 public final function getConfigurationArray () {
268 return $this->config;
272 * Unset a configuration key, the entry must be there or else an
273 * exception is thrown.
275 * @param $configKey Configuration key to unset
277 * @throws NullPointerException If $configKey is NULL
278 * @throws InvalidArgumentException If $configKey is empty
279 * @throws NoConfigEntryException If a configuration element was not found
281 public final function unsetConfigEntry ($configKey) {
282 // Validate parameters
283 if (is_null($configKey)) {
284 // Configuration key is null
285 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
286 } elseif (!is_string($configKey)) {
288 throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
289 } elseif (empty($configKey)) {
291 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
294 // Convert dashes to underscore
295 $configKey = self::convertDashesToUnderscores($configKey);
297 // Is the configuration key there?
298 if (!$this->isConfigurationEntrySet($configKey)) {
299 // Entry was not found!
300 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
304 unset($this->config[$configKey]);
308 * Detects the server address (SERVER_ADDR) and set it in configuration
310 * @return $serverAddress The detected server address
311 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
312 * @todo Have to check some more entries from $_SERVER here
314 public function detectServerAddress () {
316 if (!$this->isConfigurationEntrySet('server_addr')) {
317 // Is it set in $_SERVER?
318 if (isset($_SERVER['SERVER_ADDR'])) {
319 // Set it from $_SERVER
320 $this->setServerAddress($_SERVER['SERVER_ADDR']);
321 } elseif (isset($_SERVER['SERVER_NAME'])) {
322 // Resolve IP address
323 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
326 if ($serverIp === false) {
328 * Why is gethostbyname() returning the host name and not
329 * false as many other PHP functions are doing? ;-(
331 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
335 $this->setServerAddress($serverIp);
337 // Run auto-detecting through console tools lib
338 ConsoleTools::acquireSelfIpAddress();
342 // Now get it from configuration
343 $serverAddress = $this->getServerAddress();
346 return $serverAddress;
350 * Setter for SERVER_ADDR
352 * @param $serverAddress New SERVER_ADDR value to set
355 public function setServerAddress ($serverAddress) {
356 // Is a valid configuration key key provided?
357 if (is_null($serverAddress)) {
358 // Configuration key is null
359 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
360 } elseif (!is_string($serverAddress)) {
362 throw new InvalidArgumentException(sprintf('serverAddress[]=%s is not a string', gettype($serverAddress)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
363 } elseif (empty($serverAddress)) {
365 throw new InvalidArgumentException('serverAddress is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
368 // Set it, please don't do it yourself here
369 $this->setConfigEntry('server_addr', (string) $serverAddress);
373 * Getter for SERVER_ADDR
375 * @return $serverAddress New SERVER_ADDR value to set
377 public function getServerAddress () {
378 return $this->getConfigEntry('server_addr');
382 * Detects the HTTPS flag
384 * @return $https The detected HTTPS flag or null if failed
386 public function detectHttpSecured () {
391 if ($this->isHttpSecured()) {
393 $https = $_SERVER['HTTPS'];
401 * Checks whether HTTPS is set in $_SERVER
403 * @return $isset Whether HTTPS is set
404 * @todo Test more fields
406 public function isHttpSecured () {
407 return (isset($_SERVER['HTTPS']));
411 * Dectect and return the base URL for all URLs and forms
413 * @return $baseUrl Detected base URL
415 public function detectBaseUrl () {
416 // Initialize the URL
420 if ($this->isHttpSecured()) {
421 // Add the >s< for HTTPS
425 // Construct the full URL and secure it against CSRF attacks
426 $baseUrl = $protocol . '://' . $this->detectDomain() . $this->detectScriptPath();
433 * Detect safely and return the full domain where this script is installed
435 * @return $fullDomain The detected full domain
437 public function detectDomain () {
438 // Full domain is localnet.invalid by default
439 $fullDomain = 'localnet.invalid';
441 // Is the server name there?
442 if (isset($_SERVER['SERVER_NAME'])) {
443 // Detect the full domain
444 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
452 * Detect safely the script path without trailing slash which is the glue
453 * between "http://your-domain.invalid/" and "script-name.php"
455 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
457 public function detectScriptPath () {
461 // Is the scriptname set?
462 if (isset($_SERVER['SCRIPT_NAME'])) {
463 // Get dirname from it and replace back-slashes with slashes for lame OSes...
464 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
472 * Getter for field name
474 * @param $fieldName Field name which we shall get
475 * @return $fieldValue Field value from the user
476 * @throws NullPointerException If the result instance is null
478 public final function getField ($fieldName) {
479 // The super interface "FrameworkInterface" requires this
480 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
484 * Checks if given field is set
486 * @param $fieldName Field name to check
487 * @return $isSet Whether the given field name is set
488 * @throws NullPointerException If the result instance is null
490 public function isFieldSet ($fieldName) {
491 // The super interface "FrameworkInterface" requires this
492 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
496 * Generates a code for hashes from this class
498 * @return $hashCode The hash code respresenting this class
500 public function hashCode () {
501 return crc32($this->__toString());
505 * Checks whether an object equals this object. You should overwrite this
506 * method to implement own equality checks
508 * @param $objectInstance An instance of a FrameworkInterface object
509 * @return $equals Whether both objects equals
511 public function equals (FrameworkInterface $objectInstance) {
514 $this->__toString() === $objectInstance->__toString()
516 $this->hashCode() === $objectInstance->hashCode()
524 * Setter for call-back instance
526 * @param $callbackInstance An instance of a FrameworkInterface class
529 public function setCallbackInstance (FrameworkInterface $callbackInstance) {
530 $this->callbackInstance = $callbackInstance;