c63775517ff9f65608d30123b7f2b59cf34cd8f3
[core.git] / inc / config / class_FrameworkConfiguration.php
1 <?php
2 /**
3  * A class for the configuration stuff implemented in a singleton design paddern
4  *
5  * NOTE: We cannot put this in inc/main/ because it would be loaded (again) in
6  * class loader. See inc/loader/class_ClassLoader.php for instance
7  *
8  * @see                 ClassLoader
9  * @author              Roland Haeder <webmaster@shipsimu.org>
10  * @version             0.0.0
11  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
12  * @license             GNU GPL 3.0 or any newer version
13  * @link                http://www.shipsimu.org
14  *
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.
19  *
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.
24  *
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/>.
27  */
28 class FrameworkConfiguration implements Registerable {
29         /**
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.
33          */
34         private $config = array();
35
36         /**
37          * The configuration instance itself
38          */
39         private static $configInstance = NULL;
40
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;
45
46         /**
47          * Protected constructor
48          *
49          * @return      void
50          */
51         protected function __construct () {
52                 // Empty for now
53         }
54
55         /**
56          * Compatiblity method to return this class' name
57          *
58          * @return      __CLASS__       This class' name
59          */
60         public function __toString () {
61                 return get_class($this);
62         }
63
64         /**
65          * Getter for a singleton instance of this class
66          *
67          * @return      $configInstance         A singleton instance of this class
68          */
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();
74                 } // END - if
75
76                 // Return singleton instance
77                 return self::$configInstance;
78         }
79
80         /**
81          * Converts dashes to underscores, e.g. useable for configuration entries
82          *
83          * @param       $str    The string with maybe dashes inside
84          * @return      $str    The converted string with no dashed, but underscores
85          */
86         private final function convertDashesToUnderscores ($str) {
87                 // Convert them all
88                 $str = str_replace('-', '_', $str);
89
90                 // Return converted string
91                 return $str;
92         }
93
94         /**
95          * Setter for default time zone (must be correct!)
96          *
97          * @param       $zone   The time-zone string (e.g. Europe/Berlin)
98          * @return      void
99          */
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', '>=')) {
103                         /*
104                          * Set desired time zone to prevent date() and related functions to
105                          * issue a E_WARNING.
106                          */
107                         date_default_timezone_set($zone);
108                 } // END - if
109         }
110
111         /**
112          * Setter for runtime magic quotes
113          *
114          * @param       $enableQuotes   Whether enable magic runtime quotes (should be disabled for security reasons)
115          * @return      void
116          * @todo        This method encapsulates a deprecated PHP function and should be deprecated, too.
117          */
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
122                         return;
123                 } // END - if
124
125                 // Cast it to boolean
126                 $enableQuotes = (boolean) $enableQuotes;
127
128                 // Set it
129                 set_magic_quotes_runtime($enableQuotes);
130         }
131
132         /**
133          * Checks whether the given configuration key is set
134          *
135          * @param       $configKey      The configuration key we shall check
136          * @return      $isset          Whether the given configuration key is set
137          */
138         public function isConfigurationEntrySet ($configKey) {
139                 // Is it set?
140                 $isset = isset($this->config[$configKey]);
141
142                 // Return the result
143                 return $isset;
144         }
145
146         /**
147          * Read a configuration element.
148          *
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
153          */
154         public function getConfigEntry ($configKey) {
155                 // Convert dashes to underscore
156                 $configKey = self::convertDashesToUnderscores($configKey);
157
158                 // Is a valid configuration key provided?
159                 if (empty($configKey)) {
160                         // Entry is empty
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);
165                 }
166
167                 // Return the requested value
168                 return $this->config[$configKey];
169         }
170
171         /**
172          * Set a configuration key
173          *
174          * @param       $configKey      The configuration key we want to add/change
175          * @param       $configValue    The configuration value we want to set
176          * @return      void
177          * @throws      ConfigEntryIsEmptyException                     If $configKey is empty
178          * @throws      ConfigValueTypeUnsupportedException     If $configValue has an unsupported variable type
179          */
180         public final function setConfigEntry ($configKey, $configValue) {
181                 // Cast to string
182                 $configKey = self::convertDashesToUnderscores($configKey);
183
184                 // Is a valid configuration key key provided?
185                 if (is_null($configKey)) {
186                         // Configuration key is null
187                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
188                 } elseif ((empty($configKey)) || (!is_string($configKey))) {
189                         // Entry is empty
190                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
191                 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
192                         // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
193                         throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
194                 }
195
196                 // Set the configuration value
197                 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
198                 $this->config[$configKey] = $configValue;
199
200                 // Resort the array
201                 ksort($this->config);
202         }
203
204         /**
205          * Unset a configuration key, the entry must be there or else an
206          * exception is thrown.
207          *
208          * @param       $configKey      Configuration key to unset
209          * @return      void
210          * @throws      NoConfigEntryException  If a configuration element was not found
211          */
212         public final function unsetConfigEntry ($configKey) {
213                 // Convert dashes to underscore
214                 $configKey = self::convertDashesToUnderscores($configKey);
215
216                 // Is the configuration key there?
217                 if (!$this->isConfigurationEntrySet($configKey)) {
218                         // Entry was not found!
219                         throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
220                 } // END - if
221
222                 // Unset it
223                 unset($this->config[$configKey]);
224         }
225
226         /**
227          * Detects the server address (SERVER_ADDR) and set it in configuration
228          *
229          * @return      $serverAddress  The detected server address
230          * @todo        We have to add some more entries from $_SERVER here
231          */
232         public function detectServerAddress () {
233                 // Is the entry set?
234                 if (!$this->isConfigurationEntrySet('server_addr')) {
235                         // Is it set in $_SERVER?
236                         if (isset($_SERVER['SERVER_ADDR'])) {
237                                 // Set it from $_SERVER
238                                 $this->setServerAddress($_SERVER['SERVER_ADDR']);
239                         } elseif (class_exists('ConsoleTools')) {
240                                 // Run auto-detecting through console tools lib
241                                 ConsoleTools::acquireSelfIPAddress();
242                         }
243                 } // END - if
244
245                 // Now get it from configuration
246                 $serverAddress = $this->getServerAddress();
247
248                 // Return it
249                 return $serverAddress;
250         }
251
252         /**
253          * Setter for SERVER_ADDR
254          *
255          * @param       $serverAddress  New SERVER_ADDR value to set
256          * @return      void
257          */
258         public function setServerAddress ($serverAddress) {
259                 $this->setConfigEntry('server_addr', (string) $serverAddress);
260         }
261
262         /**
263          * Getter for SERVER_ADDR
264          *
265          * @return      $serverAddress  New SERVER_ADDR value to set
266          */
267         public function getServerAddress () {
268                 return $this->getConfigEntry('server_addr');
269         }
270
271         /**
272          * Detects the HTTPS flag
273          *
274          * @return      $https  The detected HTTPS flag or null if failed
275          */
276         public function detectHttpSecured () {
277                 // Default is null
278                 $https = NULL;
279
280                 // Is HTTPS set?
281                 if ($this->isHttpSecured()) {
282                         // Then use it
283                         $https = $_SERVER['HTTPS'];
284                 } // END - if
285
286                 // Return it
287                 return $https;
288         }
289
290         /**
291          * Checks whether HTTPS is set in $_SERVER
292          *
293          * @return $isset       Whether HTTPS is set
294          */
295         public function isHttpSecured () {
296                 return (isset($_SERVER['HTTPS']));
297         }
298
299         /**
300          * Dectect and return the base URL for all URLs and forms
301          *
302          * @return      $baseUrl        Detected base URL
303          */
304         public function detectBaseUrl () {
305                 // Initialize the URL
306                 $baseUrl = 'http';
307
308                 // Do we have HTTPS?
309                 if ($this->isHttpSecured()) {
310                         // Add the >s< for HTTPS
311                         $baseUrl .= 's';
312                 } // END - if
313
314                 // Construct the full URL and secure it against CSRF attacks
315                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
316
317                 // Return the URL
318                 return $baseUrl;
319         }
320
321         /**
322          * Detect safely and return the full domain where this script is installed
323          *
324          * @return      $fullDomain             The detected full domain
325          */
326         public function detectDomain () {
327                 // Full domain is localnet.invalid by default
328                 $fullDomain = 'localnet.invalid';
329
330                 // Is the server name there?
331                 if (isset($_SERVER['SERVER_NAME'])) {
332                         // Detect the full domain
333                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
334                 } // END - if
335
336                 // Return it
337                 return $fullDomain;
338         }
339
340         /**
341          * Detect safely the script path without trailing slash which is the glue
342          * between "http://your-domain.invalid/" and "script-name.php"
343          *
344          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
345          */
346         public function detectScriptPath () {
347                 // Default is empty
348                 $scriptPath = '';
349
350                 // Is the scriptname set?
351                 if (isset($_SERVER['SCRIPT_NAME'])) {
352                         // Get dirname from it and replace back-slashes with slashes for lame OSes...
353                         $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
354                 } // END - if
355
356                 // Return it
357                 return $scriptPath;
358         }
359
360         /**
361          * Getter for field name
362          *
363          * @param       $fieldName              Field name which we shall get
364          * @return      $fieldValue             Field value from the user
365          * @throws      NullPointerException    If the result instance is null
366          */
367         public final function getField ($fieldName) {
368                 // Our super interface "FrameworkInterface" requires this
369                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
370         }
371
372         /**
373          * Checks if given field is set
374          *
375          * @param       $fieldName      Field name to check
376          * @return      $isSet          Whether the given field name is set
377          * @throws      NullPointerException    If the result instance is null
378          */
379         public function isFieldSet ($fieldName) {
380                 // Our super interface "FrameworkInterface" requires this
381                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
382         }
383
384         /**
385          * Generates a code for hashes from this class
386          *
387          * @return      $hashCode       The hash code respresenting this class
388          */
389         public function hashCode () {
390                 return crc32($this->__toString());
391         }
392
393         /**
394          * Checks whether an object equals this object. You should overwrite this
395          * method to implement own equality checks
396          *
397          * @param       $objectInstance         An instance of a FrameworkInterface object
398          * @return      $equals                         Whether both objects equals
399          */
400         public function equals (FrameworkInterface $objectInstance) {
401                 // Now test it
402                 $equals = ((
403                         $this->__toString() == $objectInstance->__toString()
404                 ) && (
405                         $this->hashCode() == $objectInstance->hashCode()
406                 ));
407
408                 // Return the result
409                 return $equals;
410         }
411 }
412
413 // [EOF]
414 ?>