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 * Getter for whole configuration array
215 * @return $config Configuration array
217 public final function getConfigurationArray () {
219 return $this->config;
223 * Unset a configuration key, the entry must be there or else an
224 * exception is thrown.
226 * @param $configKey Configuration key to unset
228 * @throws NoConfigEntryException If a configuration element was not found
230 public final function unsetConfigEntry ($configKey) {
231 // Convert dashes to underscore
232 $configKey = self::convertDashesToUnderscores($configKey);
234 // Is the configuration key there?
235 if (!$this->isConfigurationEntrySet($configKey)) {
236 // Entry was not found!
237 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
241 unset($this->config[$configKey]);
245 * Detects the server address (SERVER_ADDR) and set it in configuration
247 * @return $serverAddress The detected server address
248 * @todo We have to add some more entries from $_SERVER here
250 public function detectServerAddress () {
252 if (!$this->isConfigurationEntrySet('server_addr')) {
253 // Is it set in $_SERVER?
254 if (isset($_SERVER['SERVER_ADDR'])) {
255 // Set it from $_SERVER
256 $this->setServerAddress($_SERVER['SERVER_ADDR']);
257 } elseif (class_exists('ConsoleTools')) {
258 // Run auto-detecting through console tools lib
259 ConsoleTools::acquireSelfIPAddress();
263 // Now get it from configuration
264 $serverAddress = $this->getServerAddress();
267 return $serverAddress;
271 * Setter for SERVER_ADDR
273 * @param $serverAddress New SERVER_ADDR value to set
276 public function setServerAddress ($serverAddress) {
277 $this->setConfigEntry('server_addr', (string) $serverAddress);
281 * Getter for SERVER_ADDR
283 * @return $serverAddress New SERVER_ADDR value to set
285 public function getServerAddress () {
286 return $this->getConfigEntry('server_addr');
290 * Detects the HTTPS flag
292 * @return $https The detected HTTPS flag or null if failed
294 public function detectHttpSecured () {
299 if ($this->isHttpSecured()) {
301 $https = $_SERVER['HTTPS'];
309 * Checks whether HTTPS is set in $_SERVER
311 * @return $isset Whether HTTPS is set
313 public function isHttpSecured () {
314 return (isset($_SERVER['HTTPS']));
318 * Dectect and return the base URL for all URLs and forms
320 * @return $baseUrl Detected base URL
322 public function detectBaseUrl () {
323 // Initialize the URL
327 if ($this->isHttpSecured()) {
328 // Add the >s< for HTTPS
332 // Construct the full URL and secure it against CSRF attacks
333 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
340 * Detect safely and return the full domain where this script is installed
342 * @return $fullDomain The detected full domain
344 public function detectDomain () {
345 // Full domain is localnet.invalid by default
346 $fullDomain = 'localnet.invalid';
348 // Is the server name there?
349 if (isset($_SERVER['SERVER_NAME'])) {
350 // Detect the full domain
351 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
359 * Detect safely the script path without trailing slash which is the glue
360 * between "http://your-domain.invalid/" and "script-name.php"
362 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
364 public function detectScriptPath () {
368 // Is the scriptname set?
369 if (isset($_SERVER['SCRIPT_NAME'])) {
370 // Get dirname from it and replace back-slashes with slashes for lame OSes...
371 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
379 * Getter for field name
381 * @param $fieldName Field name which we shall get
382 * @return $fieldValue Field value from the user
383 * @throws NullPointerException If the result instance is null
385 public final function getField ($fieldName) {
386 // Our super interface "FrameworkInterface" requires this
387 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
391 * Checks if given field is set
393 * @param $fieldName Field name to check
394 * @return $isSet Whether the given field name is set
395 * @throws NullPointerException If the result instance is null
397 public function isFieldSet ($fieldName) {
398 // Our super interface "FrameworkInterface" requires this
399 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
403 * Generates a code for hashes from this class
405 * @return $hashCode The hash code respresenting this class
407 public function hashCode () {
408 return crc32($this->__toString());
412 * Checks whether an object equals this object. You should overwrite this
413 * method to implement own equality checks
415 * @param $objectInstance An instance of a FrameworkInterface object
416 * @return $equals Whether both objects equals
418 public function equals (FrameworkInterface $objectInstance) {
421 $this->__toString() == $objectInstance->__toString()
423 $this->hashCode() == $objectInstance->hashCode()