3 namespace CoreFramework\Configuration;
5 // Load framework stuff
6 use CoreFramework\Generic\FrameworkInterface;
9 * A class for the configuration stuff implemented in a singleton design paddern
11 * NOTE: We cannot put this in inc/main/ because it would be loaded (again) in
12 * class loader. See inc/loader/class_ClassLoader.php for instance
15 * @author Roland Haeder <webmaster@shipsimu.org>
17 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
18 * @license GNU GPL 3.0 or any newer version
19 * @link http://www.shipsimu.org
21 * This program is free software: you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation, either version 3 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 class FrameworkConfiguration implements Registerable {
36 * The framework's main configuration array which will be initialized with
37 * hard-coded configuration data and might be overwritten/extended by
38 * config data from the database.
40 private $config = array();
43 * The configuration instance itself
45 private static $configInstance = NULL;
47 // Some constants for the configuration system
48 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
49 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
50 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
53 * Protected constructor
57 protected function __construct () {
62 * Compatiblity method to return this class' name
64 * @return __CLASS__ This class' name
66 public function __toString () {
67 return get_class($this);
71 * Getter for a singleton instance of this class
73 * @return $configInstance A singleton instance of this class
75 public static final function getSelfInstance () {
76 // is the instance there?
77 if (is_null(self::$configInstance)) {
78 // Create a config instance
79 self::$configInstance = new FrameworkConfiguration();
82 // Return singleton instance
83 return self::$configInstance;
87 * Converts dashes to underscores, e.g. useable for configuration entries
89 * @param $str The string with maybe dashes inside
90 * @return $str The converted string with no dashed, but underscores
92 private final function convertDashesToUnderscores ($str) {
94 $str = str_replace('-', '_', $str);
96 // Return converted string
101 * Setter for default time zone (must be correct!)
103 * @param $zone The time-zone string (e.g. Europe/Berlin)
106 public final function setDefaultTimezone ($zone) {
107 // Is PHP version 5.1.0 or higher? Older versions are being ignored
108 if (version_compare(phpversion(), '5.1.0', '>=')) {
110 * Set desired time zone to prevent date() and related functions to
113 date_default_timezone_set($zone);
118 * Setter for runtime magic quotes
120 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
122 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
124 public final function setMagicQuotesRuntime ($enableQuotes) {
125 // Is the PHP version < 5.4?
126 if (version_compare(phpversion(), '5.4', '>=')) {
127 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
131 // Cast it to boolean
132 $enableQuotes = (boolean) $enableQuotes;
135 set_magic_quotes_runtime($enableQuotes);
139 * Checks whether the given configuration key is set
141 * @param $configKey The configuration key we shall check
142 * @return $isset Whether the given configuration key is set
144 public function isConfigurationEntrySet ($configKey) {
146 $isset = isset($this->config[$configKey]);
153 * Read a configuration element.
155 * @param $configKey The configuration element
156 * @return $configValue The fetched configuration value
157 * @throws ConfigEntryIsEmptyException If $configKey is empty
158 * @throws NoConfigEntryException If a configuration element was not found
160 public function getConfigEntry ($configKey) {
161 // Convert dashes to underscore
162 $configKey = self::convertDashesToUnderscores($configKey);
164 // Is a valid configuration key provided?
165 if (empty($configKey)) {
167 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
168 } elseif (!$this->isConfigurationEntrySet($configKey)) {
169 // Entry was not found!
170 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
173 // Return the requested value
174 return $this->config[$configKey];
178 * Set a configuration key
180 * @param $configKey The configuration key we want to add/change
181 * @param $configValue The configuration value we want to set
183 * @throws ConfigEntryIsEmptyException If $configKey is empty
184 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
186 public final function setConfigEntry ($configKey, $configValue) {
188 $configKey = self::convertDashesToUnderscores($configKey);
190 // Is a valid configuration key key provided?
191 if (is_null($configKey)) {
192 // Configuration key is null
193 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
194 } elseif ((empty($configKey)) || (!is_string($configKey))) {
196 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
197 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
198 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
199 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
202 // Set the configuration value
203 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
204 $this->config[$configKey] = $configValue;
207 ksort($this->config);
211 * Unset a configuration key, the entry must be there or else an
212 * exception is thrown.
214 * @param $configKey Configuration key to unset
216 * @throws NoConfigEntryException If a configuration element was not found
218 public final function unsetConfigEntry ($configKey) {
219 // Convert dashes to underscore
220 $configKey = self::convertDashesToUnderscores($configKey);
222 // Is the configuration key there?
223 if (!$this->isConfigurationEntrySet($configKey)) {
224 // Entry was not found!
225 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
229 unset($this->config[$configKey]);
233 * Detects the server address (SERVER_ADDR) and set it in configuration
235 * @return $serverAddress The detected server address
236 * @todo We have to add some more entries from $_SERVER here
238 public function detectServerAddress () {
240 if (!$this->isConfigurationEntrySet('server_addr')) {
241 // Is it set in $_SERVER?
242 if (isset($_SERVER['SERVER_ADDR'])) {
243 // Set it from $_SERVER
244 $this->setServerAddress($_SERVER['SERVER_ADDR']);
245 } elseif (class_exists('ConsoleTools')) {
246 // Run auto-detecting through console tools lib
247 ConsoleTools::acquireSelfIPAddress();
251 // Now get it from configuration
252 $serverAddress = $this->getServerAddress();
255 return $serverAddress;
259 * Setter for SERVER_ADDR
261 * @param $serverAddress New SERVER_ADDR value to set
264 public function setServerAddress ($serverAddress) {
265 $this->setConfigEntry('server_addr', (string) $serverAddress);
269 * Getter for SERVER_ADDR
271 * @return $serverAddress New SERVER_ADDR value to set
273 public function getServerAddress () {
274 return $this->getConfigEntry('server_addr');
278 * Detects the HTTPS flag
280 * @return $https The detected HTTPS flag or null if failed
282 public function detectHttpSecured () {
287 if ($this->isHttpSecured()) {
289 $https = $_SERVER['HTTPS'];
297 * Checks whether HTTPS is set in $_SERVER
299 * @return $isset Whether HTTPS is set
301 public function isHttpSecured () {
302 return (isset($_SERVER['HTTPS']));
306 * Dectect and return the base URL for all URLs and forms
308 * @return $baseUrl Detected base URL
310 public function detectBaseUrl () {
311 // Initialize the URL
315 if ($this->isHttpSecured()) {
316 // Add the >s< for HTTPS
320 // Construct the full URL and secure it against CSRF attacks
321 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
328 * Detect safely and return the full domain where this script is installed
330 * @return $fullDomain The detected full domain
332 public function detectDomain () {
333 // Full domain is localnet.invalid by default
334 $fullDomain = 'localnet.invalid';
336 // Is the server name there?
337 if (isset($_SERVER['SERVER_NAME'])) {
338 // Detect the full domain
339 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
347 * Detect safely the script path without trailing slash which is the glue
348 * between "http://your-domain.invalid/" and "script-name.php"
350 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
352 public function detectScriptPath () {
356 // Is the scriptname set?
357 if (isset($_SERVER['SCRIPT_NAME'])) {
358 // Get dirname from it and replace back-slashes with slashes for lame OSes...
359 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
367 * Getter for field name
369 * @param $fieldName Field name which we shall get
370 * @return $fieldValue Field value from the user
371 * @throws NullPointerException If the result instance is null
373 public final function getField ($fieldName) {
374 // Our super interface "FrameworkInterface" requires this
375 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
379 * Checks if given field is set
381 * @param $fieldName Field name to check
382 * @return $isSet Whether the given field name is set
383 * @throws NullPointerException If the result instance is null
385 public function isFieldSet ($fieldName) {
386 // Our super interface "FrameworkInterface" requires this
387 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
391 * Generates a code for hashes from this class
393 * @return $hashCode The hash code respresenting this class
395 public function hashCode () {
396 return crc32($this->__toString());
400 * Checks whether an object equals this object. You should overwrite this
401 * method to implement own equality checks
403 * @param $objectInstance An instance of a FrameworkInterface object
404 * @return $equals Whether both objects equals
406 public function equals (FrameworkInterface $objectInstance) {
409 $this->__toString() == $objectInstance->__toString()
411 $this->hashCode() == $objectInstance->hashCode()