3 namespace CoreFramework\Configuration;
5 // Load framework stuff
6 use CoreFramework\Generic\FrameworkInterface;
7 use CoreFramework\Registry\Registerable;
10 * A class for the configuration stuff implemented in a singleton design paddern
12 * NOTE: We cannot put this in inc/main/ because it would be loaded (again) in
13 * class loader. See inc/loader/class_ClassLoader.php for instance
16 * @author Roland Haeder <webmaster@shipsimu.org>
18 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
19 * @license GNU GPL 3.0 or any newer version
20 * @link http://www.shipsimu.org
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 class FrameworkConfiguration implements Registerable {
37 * The framework's main configuration array which will be initialized with
38 * hard-coded configuration data and might be overwritten/extended by
39 * config data from the database.
41 private $config = array();
44 * The configuration instance itself
46 private static $configInstance = NULL;
48 // Some constants for the configuration system
49 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
50 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
51 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
54 * Protected constructor
58 protected function __construct () {
63 * Compatiblity method to return this class' name
65 * @return __CLASS__ This class' name
67 public function __toString () {
68 return get_class($this);
72 * Getter for a singleton instance of this class
74 * @return $configInstance A singleton instance of this class
76 public static final function getSelfInstance () {
77 // is the instance there?
78 if (is_null(self::$configInstance)) {
79 // Create a config instance
80 self::$configInstance = new FrameworkConfiguration();
83 // Return singleton instance
84 return self::$configInstance;
88 * Converts dashes to underscores, e.g. useable for configuration entries
90 * @param $str The string with maybe dashes inside
91 * @return $str The converted string with no dashed, but underscores
93 private final function convertDashesToUnderscores ($str) {
95 $str = str_replace('-', '_', $str);
97 // Return converted string
102 * Setter for default time zone (must be correct!)
104 * @param $zone The time-zone string (e.g. Europe/Berlin)
107 public final function setDefaultTimezone ($zone) {
108 // Is PHP version 5.1.0 or higher? Older versions are being ignored
109 if (version_compare(phpversion(), '5.1.0', '>=')) {
111 * Set desired time zone to prevent date() and related functions to
114 date_default_timezone_set($zone);
119 * Setter for runtime magic quotes
121 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
123 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
125 public final function setMagicQuotesRuntime ($enableQuotes) {
126 // Is the PHP version < 5.4?
127 if (version_compare(phpversion(), '5.4', '>=')) {
128 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
132 // Cast it to boolean
133 $enableQuotes = (boolean) $enableQuotes;
136 set_magic_quotes_runtime($enableQuotes);
140 * Checks whether the given configuration key is set
142 * @param $configKey The configuration key we shall check
143 * @return $isset Whether the given configuration key is set
145 public function isConfigurationEntrySet ($configKey) {
147 $isset = isset($this->config[$configKey]);
154 * Read a configuration element.
156 * @param $configKey The configuration element
157 * @return $configValue The fetched configuration value
158 * @throws ConfigEntryIsEmptyException If $configKey is empty
159 * @throws NoConfigEntryException If a configuration element was not found
161 public function getConfigEntry ($configKey) {
162 // Convert dashes to underscore
163 $configKey = self::convertDashesToUnderscores($configKey);
165 // Is a valid configuration key provided?
166 if (empty($configKey)) {
168 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
169 } elseif (!$this->isConfigurationEntrySet($configKey)) {
170 // Entry was not found!
171 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
174 // Return the requested value
175 return $this->config[$configKey];
179 * Set a configuration key
181 * @param $configKey The configuration key we want to add/change
182 * @param $configValue The configuration value we want to set
184 * @throws ConfigEntryIsEmptyException If $configKey is empty
185 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
187 public final function setConfigEntry ($configKey, $configValue) {
189 $configKey = self::convertDashesToUnderscores($configKey);
191 // Is a valid configuration key key provided?
192 if (is_null($configKey)) {
193 // Configuration key is null
194 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
195 } elseif ((empty($configKey)) || (!is_string($configKey))) {
197 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
198 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
199 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
200 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
203 // Set the configuration value
204 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
205 $this->config[$configKey] = $configValue;
208 ksort($this->config);
212 * Unset a configuration key, the entry must be there or else an
213 * exception is thrown.
215 * @param $configKey Configuration key to unset
217 * @throws NoConfigEntryException If a configuration element was not found
219 public final function unsetConfigEntry ($configKey) {
220 // Convert dashes to underscore
221 $configKey = self::convertDashesToUnderscores($configKey);
223 // Is the configuration key there?
224 if (!$this->isConfigurationEntrySet($configKey)) {
225 // Entry was not found!
226 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
230 unset($this->config[$configKey]);
234 * Detects the server address (SERVER_ADDR) and set it in configuration
236 * @return $serverAddress The detected server address
237 * @todo We have to add some more entries from $_SERVER here
239 public function detectServerAddress () {
241 if (!$this->isConfigurationEntrySet('server_addr')) {
242 // Is it set in $_SERVER?
243 if (isset($_SERVER['SERVER_ADDR'])) {
244 // Set it from $_SERVER
245 $this->setServerAddress($_SERVER['SERVER_ADDR']);
246 } elseif (class_exists('ConsoleTools')) {
247 // Run auto-detecting through console tools lib
248 ConsoleTools::acquireSelfIPAddress();
252 // Now get it from configuration
253 $serverAddress = $this->getServerAddress();
256 return $serverAddress;
260 * Setter for SERVER_ADDR
262 * @param $serverAddress New SERVER_ADDR value to set
265 public function setServerAddress ($serverAddress) {
266 $this->setConfigEntry('server_addr', (string) $serverAddress);
270 * Getter for SERVER_ADDR
272 * @return $serverAddress New SERVER_ADDR value to set
274 public function getServerAddress () {
275 return $this->getConfigEntry('server_addr');
279 * Detects the HTTPS flag
281 * @return $https The detected HTTPS flag or null if failed
283 public function detectHttpSecured () {
288 if ($this->isHttpSecured()) {
290 $https = $_SERVER['HTTPS'];
298 * Checks whether HTTPS is set in $_SERVER
300 * @return $isset Whether HTTPS is set
302 public function isHttpSecured () {
303 return (isset($_SERVER['HTTPS']));
307 * Dectect and return the base URL for all URLs and forms
309 * @return $baseUrl Detected base URL
311 public function detectBaseUrl () {
312 // Initialize the URL
316 if ($this->isHttpSecured()) {
317 // Add the >s< for HTTPS
321 // Construct the full URL and secure it against CSRF attacks
322 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
329 * Detect safely and return the full domain where this script is installed
331 * @return $fullDomain The detected full domain
333 public function detectDomain () {
334 // Full domain is localnet.invalid by default
335 $fullDomain = 'localnet.invalid';
337 // Is the server name there?
338 if (isset($_SERVER['SERVER_NAME'])) {
339 // Detect the full domain
340 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
348 * Detect safely the script path without trailing slash which is the glue
349 * between "http://your-domain.invalid/" and "script-name.php"
351 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
353 public function detectScriptPath () {
357 // Is the scriptname set?
358 if (isset($_SERVER['SCRIPT_NAME'])) {
359 // Get dirname from it and replace back-slashes with slashes for lame OSes...
360 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
368 * Getter for field name
370 * @param $fieldName Field name which we shall get
371 * @return $fieldValue Field value from the user
372 * @throws NullPointerException If the result instance is null
374 public final function getField ($fieldName) {
375 // Our super interface "FrameworkInterface" requires this
376 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
380 * Checks if given field is set
382 * @param $fieldName Field name to check
383 * @return $isSet Whether the given field name is set
384 * @throws NullPointerException If the result instance is null
386 public function isFieldSet ($fieldName) {
387 // Our super interface "FrameworkInterface" requires this
388 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
392 * Generates a code for hashes from this class
394 * @return $hashCode The hash code respresenting this class
396 public function hashCode () {
397 return crc32($this->__toString());
401 * Checks whether an object equals this object. You should overwrite this
402 * method to implement own equality checks
404 * @param $objectInstance An instance of a FrameworkInterface object
405 * @return $equals Whether both objects equals
407 public function equals (FrameworkInterface $objectInstance) {
410 $this->__toString() == $objectInstance->__toString()
412 $this->hashCode() == $objectInstance->hashCode()