3 * A class for the configuration stuff implemented in a singleton design paddern
5 * NOTE: We cannot put this in inc/classes/ because it would be loaded (again) in
6 * class loader. See inc/loader/class_ClassLoader.php for instance
9 * @author Roland Haeder <webmaster@shipsimu.org>
11 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
12 * @license GNU GPL 3.0 or any newer version
13 * @link http://www.shipsimu.org
15 * This program is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 class FrameworkConfiguration implements Registerable {
30 * The framework's main configuration array which will be initialized with
31 * hard-coded configuration data and might be overwritten/extended by
32 * config data from the database.
34 private $config = array();
37 * The configuration instance itself
39 private static $configInstance = NULL;
41 // Some constants for the configuration system
42 const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
43 const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
44 const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
47 * Protected constructor
51 protected function __construct () {
56 * Compatiblity method to return this class' name
58 * @return __CLASS__ This class' name
60 public function __toString () {
61 return get_class($this);
65 * Getter for a singleton instance of this class
67 * @return $configInstance A singleton instance of this class
69 public static final function getSelfInstance () {
70 // is the instance there?
71 if (is_null(self::$configInstance)) {
72 // Create a config instance
73 self::$configInstance = new FrameworkConfiguration();
76 // Return singleton instance
77 return self::$configInstance;
81 * Converts dashes to underscores, e.g. useable for configuration entries
83 * @param $str The string with maybe dashes inside
84 * @return $str The converted string with no dashed, but underscores
86 private final function convertDashesToUnderscores ($str) {
88 $str = str_replace('-', '_', $str);
90 // Return converted string
95 * Setter for default time zone (must be correct!)
97 * @param $zone The time-zone string (e.g. Europe/Berlin)
100 public final function setDefaultTimezone ($zone) {
101 // Is PHP version 5.1.0 or higher? Older versions are being ignored
102 if (version_compare(phpversion(), '5.1.0', '>=')) {
104 * Set desired time zone to prevent date() and related functions to
107 date_default_timezone_set($zone);
112 * Setter for runtime magic quotes
114 * @param $enableQuotes Whether enable magic runtime quotes (should be disabled for security reasons)
116 * @todo This method encapsulates a deprecated PHP function and should be deprecated, too.
118 public final function setMagicQuotesRuntime ($enableQuotes) {
119 // Is the PHP version < 5.4?
120 if (version_compare(phpversion(), '5.4', '>=')) {
121 // Then silently skip this part as set_magic_quotes_runtime() is deprecated
125 // Cast it to boolean
126 $enableQuotes = (boolean) $enableQuotes;
129 set_magic_quotes_runtime($enableQuotes);
133 * Checks whether the given configuration key is set
135 * @param $configKey The configuration key we shall check
136 * @return $isset Whether the given configuration key is set
138 public function isConfigurationEntrySet ($configKey) {
140 $isset = isset($this->config[$configKey]);
147 * Read a configuration element.
149 * @param $configKey The configuration element
150 * @return $configValue The fetched configuration value
151 * @throws ConfigEntryIsEmptyException If $configKey is empty
152 * @throws NoConfigEntryException If a configuration element was not found
154 public function getConfigEntry ($configKey) {
155 // Convert dashes to underscore
156 $configKey = $this->convertDashesToUnderscores($configKey);
158 // Is a valid configuration key provided?
159 if (empty($configKey)) {
161 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
162 } elseif (!$this->isConfigurationEntrySet($configKey)) {
163 // Entry was not found!
164 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
167 // Return the requested value
168 return $this->config[$configKey];
172 * Set a configuration key
174 * @param $configKey The configuration key we want to add/change
175 * @param $configValue The configuration value we want to set
177 * @throws ConfigEntryIsEmptyException If $configKey is empty
178 * @throws ConfigValueTypeUnsupportedException If $configValue has an unsupported variable type
180 public final function setConfigEntry ($configKey, $configValue) {
182 $configKey = $this->convertDashesToUnderscores($configKey);
184 // Is a valid configuration key key provided?
185 if ((empty($configKey)) || (!is_string($configKey))) {
187 throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
188 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
189 // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
190 throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
193 // Set the configuration value
194 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
195 $this->config[$configKey] = $configValue;
198 ksort($this->config);
202 * Unset a configuration key, the entry must be there or else an
203 * exception is thrown.
205 * @param $configKey Configuration key to unset
207 * @throws NoConfigEntryException If a configuration element was not found
209 public final function unsetConfigEntry ($configKey) {
210 // Convert dashes to underscore
211 $configKey = $this->convertDashesToUnderscores($configKey);
213 // Is the configuration key there?
214 if (!$this->isConfigurationEntrySet($configKey)) {
215 // Entry was not found!
216 throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
220 unset($this->config[$configKey]);
224 * Detects the server address (SERVER_ADDR) and set it in configuration
226 * @return $serverAddress The detected server address
227 * @todo We have to add some more entries from $_SERVER here
229 public function detectServerAddress () {
231 if (!$this->isConfigurationEntrySet('server_addr')) {
232 // Is it set in $_SERVER?
233 if (isset($_SERVER['SERVER_ADDR'])) {
234 // Set it from $_SERVER
235 $this->setServerAddress($_SERVER['SERVER_ADDR']);
236 } elseif (class_exists('ConsoleTools')) {
237 // Run auto-detecting through console tools lib
238 ConsoleTools::acquireSelfIPAddress();
242 // Now get it from configuration
243 $serverAddress = $this->getServerAddress();
246 return $serverAddress;
250 * Setter for SERVER_ADDR
252 * @param $serverAddress New SERVER_ADDR value to set
255 public function setServerAddress ($serverAddress) {
256 $this->setConfigEntry('server_addr', (string) $serverAddress);
260 * Getter for SERVER_ADDR
262 * @return $serverAddress New SERVER_ADDR value to set
264 public function getServerAddress () {
265 return $this->getConfigEntry('server_addr');
269 * Detects the HTTPS flag
271 * @return $https The detected HTTPS flag or null if failed
273 public function detectHttpSecured () {
278 if ($this->isHttpSecured()) {
280 $https = $_SERVER['HTTPS'];
288 * Checks whether HTTPS is set in $_SERVER
290 * @return $isset Whether HTTPS is set
292 public function isHttpSecured () {
293 return (isset($_SERVER['HTTPS']));
297 * Dectect and return the base URL for all URLs and forms
299 * @return $baseUrl Detected base URL
301 public function detectBaseUrl () {
302 // Initialize the URL
306 if ($this->isHttpSecured()) {
307 // Add the >s< for HTTPS
311 // Construct the full URL and secure it against CSRF attacks
312 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
319 * Detect safely and return the full domain where this script is installed
321 * @return $fullDomain The detected full domain
323 public function detectDomain () {
324 // Full domain is localnet.invalid by default
325 $fullDomain = 'localnet.invalid';
327 // Is the server name there?
328 if (isset($_SERVER['SERVER_NAME'])) {
329 // Detect the full domain
330 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
338 * Detect safely the script path without trailing slash which is the glue
339 * between "http://your-domain.invalid/" and "script-name.php"
341 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
343 public function detectScriptPath () {
347 // Is the scriptname set?
348 if (isset($_SERVER['SCRIPT_NAME'])) {
349 // Get dirname from it and replace back-slashes with slashes for lame OSes...
350 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
358 * Getter for field name
360 * @param $fieldName Field name which we shall get
361 * @return $fieldValue Field value from the user
362 * @throws NullPointerException If the result instance is null
364 public final function getField ($fieldName) {
365 // Our super interface "FrameworkInterface" requires this
369 * Checks if given field is set
371 * @param $fieldName Field name to check
372 * @return $isSet Whether the given field name is set
373 * @throws NullPointerException If the result instance is null
375 public function isFieldSet ($fieldName) {
376 // Our super interface "FrameworkInterface" requires this
380 * Generates a code for hashes from this class
382 * @return $hashCode The hash code respresenting this class
384 public function hashCode () {
385 return crc32($this->__toString());
389 * Checks whether an object equals this object. You should overwrite this
390 * method to implement own equality checks
392 * @param $objectInstance An instance of a FrameworkInterface object
393 * @return $equals Whether both objects equals
395 public function equals (FrameworkInterface $objectInstance) {
398 $this->__toString() == $objectInstance->__toString()
400 $this->hashCode() == $objectInstance->hashCode()