5 namespace CoreFramework\Configuration;
7 // Import framework stuff
8 use CoreFramework\Console\Tools\ConsoleTools;
9 use CoreFramework\Dns\UnknownHostnameException;
10 use CoreFramework\Generic\FrameworkInterface;
11 use CoreFramework\Generic\NullPointerException;
12 use CoreFramework\Generic\UnsupportedOperationException;
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;
69 * Protected constructor
73 protected 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, self::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 $zone The time-zone string (e.g. Europe/Berlin)
132 * @throws NullPointerException If $zone is NULL
133 * @throws InvalidArgumentException If $zone is empty
135 public final function setDefaultTimezone ($zone) {
137 if (is_null($zone)) {
139 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
140 } elseif (empty($zone)) {
142 throw new InvalidArgumentException('zone is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
145 // Is PHP version 5.1.0 or higher? Older versions are being ignored
146 if (version_compare(phpversion(), '5.1.0', '>=')) {
148 * Set desired time zone to prevent date() and related functions to
151 date_default_timezone_set($zone);
156 * Checks whether the given configuration key is set
158 * @param $configKey The configuration key we shall check
159 * @return $isset Whether the given configuration key is set
160 * @throws NullPointerException If $configKey is NULL
161 * @throws InvalidArgumentException If $configKey is empty
163 public function isConfigurationEntrySet ($configKey) {
165 if (is_null($configKey)) {
167 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
168 } elseif (empty($configKey)) {
170 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
174 $isset = isset($this->config[$configKey]);
181 * Read a configuration element.
183 * @param $configKey The configuration element
184 * @return $configValue The fetched configuration value
185 * @throws NullPointerException If $configKey is NULL
186 * @throws InvalidArgumentException If $configKey is empty
187 * @throws NoConfigEntryException If a configuration element was not found
189 public function getConfigEntry ($configKey) {
191 if (is_null($configKey)) {
193 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
194 } elseif (empty($configKey)) {
196 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
199 // Convert dashes to underscore
200 $configKey = self::convertDashesToUnderscores($configKey);
202 // Is a valid configuration key provided?
203 if (!$this->isConfigurationEntrySet($configKey)) {
204 // Entry was not found!
205 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
208 // Return the requested value
209 return $this->config[$configKey];
213 * Set a configuration key
215 * @param $configKey The configuration key we want to add/change
216 * @param $configValue The configuration value we want to set
218 * @throws NullPointerException If $configKey is NULL
219 * @throws InvalidArgumentException If $configKey is empty
220 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
222 public final function setConfigEntry ($configKey, $configValue) {
223 // Is a valid configuration key key provided?
224 if (is_null($configKey)) {
225 // Configuration key is null
226 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
227 } elseif ((empty($configKey)) || (!is_string($configKey))) {
229 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
230 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
231 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
232 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
236 $configKey = self::convertDashesToUnderscores($configKey);
238 // Set the configuration value
239 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
240 $this->config[$configKey] = $configValue;
243 ksort($this->config);
247 * Getter for whole configuration array
249 * @return $config Configuration array
251 public final function getConfigurationArray () {
253 return $this->config;
257 * Unset a configuration key, the entry must be there or else an
258 * exception is thrown.
260 * @param $configKey Configuration key to unset
262 * @throws NullPointerException If $configKey is NULL
263 * @throws InvalidArgumentException If $configKey is empty
264 * @throws NoConfigEntryException If a configuration element was not found
266 public final function unsetConfigEntry ($configKey) {
267 if (is_null($configKey)) {
268 // Configuration key is null
269 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
270 } elseif ((empty($configKey)) || (!is_string($configKey))) {
272 throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
275 // Convert dashes to underscore
276 $configKey = self::convertDashesToUnderscores($configKey);
278 // Is the configuration key there?
279 if (!$this->isConfigurationEntrySet($configKey)) {
280 // Entry was not found!
281 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
285 unset($this->config[$configKey]);
289 * Detects the server address (SERVER_ADDR) and set it in configuration
291 * @return $serverAddress The detected server address
292 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
293 * @todo Have to check some more entries from $_SERVER here
295 public function detectServerAddress () {
297 if (!$this->isConfigurationEntrySet('server_addr')) {
298 // Is it set in $_SERVER?
299 if (isset($_SERVER['SERVER_ADDR'])) {
300 // Set it from $_SERVER
301 $this->setServerAddress($_SERVER['SERVER_ADDR']);
302 } elseif (isset($_SERVER['SERVER_NAME'])) {
303 // Resolve IP address
304 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
307 if ($serverIp === false) {
309 * Why is gethostbyname() returning the host name and not
310 * false as many other PHP functions are doing? ;-(
312 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
316 $this->setServerAddress($serverIp);
318 // Run auto-detecting through console tools lib
319 ConsoleTools::acquireSelfIPAddress();
323 // Now get it from configuration
324 $serverAddress = $this->getServerAddress();
327 return $serverAddress;
331 * Setter for SERVER_ADDR
333 * @param $serverAddress New SERVER_ADDR value to set
336 public function setServerAddress ($serverAddress) {
337 $this->setConfigEntry('server_addr', (string) $serverAddress);
341 * Getter for SERVER_ADDR
343 * @return $serverAddress New SERVER_ADDR value to set
345 public function getServerAddress () {
346 return $this->getConfigEntry('server_addr');
350 * Detects the HTTPS flag
352 * @return $isSecured The detected HTTPS flag or null if failed
354 public function detectHttpSecured () {
359 if ($this->isHttpSecured()) {
361 $isSecured = $_SERVER['HTTPS'];
369 * Checks whether HTTPS is set in $_SERVER
371 * @return $isset Whether HTTPS is set
373 public function isHttpSecured () {
374 return (isset($_SERVER['HTTPS']));
378 * Dectect and return the base URL for all URLs and forms
380 * @return $baseUrl Detected base URL
382 public function detectBaseUrl () {
383 // Initialize the URL
387 if ($this->isHttpSecured()) {
388 // Add the >s< for HTTPS
392 // Construct the full URL and secure it against CSRF attacks
393 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
400 * Detect safely and return the full domain where this script is installed
402 * @return $fullDomain The detected full domain
404 public function detectDomain () {
405 // Full domain is localnet.invalid by default
406 $fullDomain = 'localnet.invalid';
408 // Is the server name there?
409 if (isset($_SERVER['SERVER_NAME'])) {
410 // Detect the full domain
411 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
419 * Detect safely the script path without trailing slash which is the glue
420 * between "http://your-domain.invalid/" and "script-name.php"
422 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
424 public function detectScriptPath () {
428 // Is the scriptname set?
429 if (isset($_SERVER['SCRIPT_NAME'])) {
430 // Get dirname from it and replace back-slashes with slashes for lame OSes...
431 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
439 * Getter for field name
441 * @param $fieldName Field name which we shall get
442 * @return $fieldValue Field value from the user
443 * @throws NullPointerException If the result instance is null
445 public final function getField ($fieldName) {
446 // The super interface "FrameworkInterface" requires this
447 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
451 * Checks if given field is set
453 * @param $fieldName Field name to check
454 * @return $isSet Whether the given field name is set
455 * @throws NullPointerException If the result instance is null
457 public function isFieldSet ($fieldName) {
458 // The super interface "FrameworkInterface" requires this
459 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
463 * Generates a code for hashes from this class
465 * @return $hashCode The hash code respresenting this class
467 public function hashCode () {
468 return crc32($this->__toString());
472 * Checks whether an object equals this object. You should overwrite this
473 * method to implement own equality checks
475 * @param $objectInstance An instance of a FrameworkInterface object
476 * @return $equals Whether both objects equals
478 public function equals (FrameworkInterface $objectInstance) {
481 $this->__toString() === $objectInstance->__toString()
483 $this->hashCode() === $objectInstance->hashCode()
491 * Setter for call-back instance
493 * @param $callbackInstance An instance of a FrameworkInterface class
496 public function setCallbackInstance (FrameworkInterface $callbackInstance) {
497 $this->callbackInstance = $callbackInstance;