3 namespace CoreFramework\Configuration;
5 // Import framework stuff
6 use CoreFramework\Generic\FrameworkInterface;
7 use CoreFramework\Generic\NullPointerException;
8 use CoreFramework\Registry\Registerable;
11 * A class for the configuration stuff implemented in a singleton design paddern
13 * NOTE: We cannot put this in framework/main/ because it would be loaded (again) in
14 * class loader. See framework/loader/class_ClassLoader.php for instance
17 * @author Roland Haeder <webmaster@shipsimu.org>
19 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
20 * @license GNU GPL 3.0 or any newer version
21 * @link http://www.shipsimu.org
23 * This program is free software: you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation, either version 3 of the License, or
26 * (at your option) any later version.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 class FrameworkConfiguration implements Registerable {
38 * The framework's main configuration array which will be initialized with
39 * hard-coded configuration data and might be overwritten/extended by
40 * config data from the database.
42 private $config = array();
45 * The configuration instance itself
47 private static $configInstance = NULL;
49 // Some constants for the configuration system
50 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
51 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
52 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
55 * Protected constructor
59 protected function __construct () {
64 * Compatiblity method to return this class' name
66 * @return __CLASS__ This class' name
68 public function __toString () {
69 return get_class($this);
73 * Getter for a singleton instance of this class
75 * @return $configInstance A singleton instance of this class
77 public static final function getSelfInstance () {
78 // is the instance there?
79 if (is_null(self::$configInstance)) {
80 // Create a config instance
81 self::$configInstance = new FrameworkConfiguration();
84 // Return singleton instance
85 return self::$configInstance;
89 * Converts dashes to underscores, e.g. useable for configuration entries
91 * @param $str The string with maybe dashes inside
92 * @return $str The converted string with no dashed, but underscores
94 private final function convertDashesToUnderscores ($str) {
96 $str = str_replace('-', '_', $str);
98 // Return converted string
103 * Setter for default time zone (must be correct!)
105 * @param $zone The time-zone string (e.g. Europe/Berlin)
108 public final function setDefaultTimezone ($zone) {
109 // Is PHP version 5.1.0 or higher? Older versions are being ignored
110 if (version_compare(phpversion(), '5.1.0', '>=')) {
112 * Set desired time zone to prevent date() and related functions to
115 date_default_timezone_set($zone);
120 * Setter for runtime magic quotes
122 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
124 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
126 public final function setMagicQuotesRuntime ($enableQuotes) {
127 // Is the PHP version < 5.4?
128 if (version_compare(phpversion(), '5.4', '>=')) {
129 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
133 // Cast it to boolean
134 $enableQuotes = (boolean) $enableQuotes;
137 set_magic_quotes_runtime($enableQuotes);
141 * Checks whether the given configuration key is set
143 * @param $configKey The configuration key we shall check
144 * @return $isset Whether the given configuration key is set
146 public function isConfigurationEntrySet ($configKey) {
148 $isset = isset($this->config[$configKey]);
155 * Read a configuration element.
157 * @param $configKey The configuration element
158 * @return $configValue The fetched configuration value
159 * @throws ConfigEntryIsEmptyException If $configKey is empty
160 * @throws NoConfigEntryException If a configuration element was not found
162 public function getConfigEntry ($configKey) {
163 // Convert dashes to underscore
164 $configKey = self::convertDashesToUnderscores($configKey);
166 // Is a valid configuration key provided?
167 if (empty($configKey)) {
169 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
170 } elseif (!$this->isConfigurationEntrySet($configKey)) {
171 // Entry was not found!
172 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
175 // Return the requested value
176 return $this->config[$configKey];
180 * Set a configuration key
182 * @param $configKey The configuration key we want to add/change
183 * @param $configValue The configuration value we want to set
185 * @throws ConfigEntryIsEmptyException If $configKey is empty
186 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
188 public final function setConfigEntry ($configKey, $configValue) {
190 $configKey = self::convertDashesToUnderscores($configKey);
192 // Is a valid configuration key key provided?
193 if (is_null($configKey)) {
194 // Configuration key is null
195 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
196 } elseif ((empty($configKey)) || (!is_string($configKey))) {
198 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
199 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
200 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
201 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
204 // Set the configuration value
205 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
206 $this->config[$configKey] = $configValue;
209 ksort($this->config);
213 * Unset a configuration key, the entry must be there or else an
214 * exception is thrown.
216 * @param $configKey Configuration key to unset
218 * @throws NoConfigEntryException If a configuration element was not found
220 public final function unsetConfigEntry ($configKey) {
221 // Convert dashes to underscore
222 $configKey = self::convertDashesToUnderscores($configKey);
224 // Is the configuration key there?
225 if (!$this->isConfigurationEntrySet($configKey)) {
226 // Entry was not found!
227 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
231 unset($this->config[$configKey]);
235 * Detects the server address (SERVER_ADDR) and set it in configuration
237 * @return $serverAddress The detected server address
238 * @todo We have to add some more entries from $_SERVER here
240 public function detectServerAddress () {
242 if (!$this->isConfigurationEntrySet('server_addr')) {
243 // Is it set in $_SERVER?
244 if (isset($_SERVER['SERVER_ADDR'])) {
245 // Set it from $_SERVER
246 $this->setServerAddress($_SERVER['SERVER_ADDR']);
247 } elseif (class_exists('ConsoleTools')) {
248 // Run auto-detecting through console tools lib
249 ConsoleTools::acquireSelfIPAddress();
253 // Now get it from configuration
254 $serverAddress = $this->getServerAddress();
257 return $serverAddress;
261 * Setter for SERVER_ADDR
263 * @param $serverAddress New SERVER_ADDR value to set
266 public function setServerAddress ($serverAddress) {
267 $this->setConfigEntry('server_addr', (string) $serverAddress);
271 * Getter for SERVER_ADDR
273 * @return $serverAddress New SERVER_ADDR value to set
275 public function getServerAddress () {
276 return $this->getConfigEntry('server_addr');
280 * Detects the HTTPS flag
282 * @return $https The detected HTTPS flag or null if failed
284 public function detectHttpSecured () {
289 if ($this->isHttpSecured()) {
291 $https = $_SERVER['HTTPS'];
299 * Checks whether HTTPS is set in $_SERVER
301 * @return $isset Whether HTTPS is set
303 public function isHttpSecured () {
304 return (isset($_SERVER['HTTPS']));
308 * Dectect and return the base URL for all URLs and forms
310 * @return $baseUrl Detected base URL
312 public function detectBaseUrl () {
313 // Initialize the URL
317 if ($this->isHttpSecured()) {
318 // Add the >s< for HTTPS
322 // Construct the full URL and secure it against CSRF attacks
323 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
330 * Detect safely and return the full domain where this script is installed
332 * @return $fullDomain The detected full domain
334 public function detectDomain () {
335 // Full domain is localnet.invalid by default
336 $fullDomain = 'localnet.invalid';
338 // Is the server name there?
339 if (isset($_SERVER['SERVER_NAME'])) {
340 // Detect the full domain
341 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
349 * Detect safely the script path without trailing slash which is the glue
350 * between "http://your-domain.invalid/" and "script-name.php"
352 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
354 public function detectScriptPath () {
358 // Is the scriptname set?
359 if (isset($_SERVER['SCRIPT_NAME'])) {
360 // Get dirname from it and replace back-slashes with slashes for lame OSes...
361 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
369 * Getter for field name
371 * @param $fieldName Field name which we shall get
372 * @return $fieldValue Field value from the user
373 * @throws NullPointerException If the result instance is null
375 public final function getField ($fieldName) {
376 // Our super interface "FrameworkInterface" requires this
377 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
381 * Checks if given field is set
383 * @param $fieldName Field name to check
384 * @return $isSet Whether the given field name is set
385 * @throws NullPointerException If the result instance is null
387 public function isFieldSet ($fieldName) {
388 // Our super interface "FrameworkInterface" requires this
389 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
393 * Generates a code for hashes from this class
395 * @return $hashCode The hash code respresenting this class
397 public function hashCode () {
398 return crc32($this->__toString());
402 * Checks whether an object equals this object. You should overwrite this
403 * method to implement own equality checks
405 * @param $objectInstance An instance of a FrameworkInterface object
406 * @return $equals Whether both objects equals
408 public function equals (FrameworkInterface $objectInstance) {
411 $this->__toString() == $objectInstance->__toString()
413 $this->hashCode() == $objectInstance->hashCode()