Introduced ConfigValueTypeUnsupportedException
[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/classes/ 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 - 2015 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 = $this->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 = $this->convertDashesToUnderscores($configKey);
183
184                 // Is a valid configuration key key provided?
185                 if ((empty($configKey)) || (!is_string($configKey))) {
186                         // Entry is empty
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);
191                 }
192
193                 // Set the configuration value
194                 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
195                 $this->config[$configKey] = $configValue;
196
197                 // Resort the array
198                 ksort($this->config);
199         }
200
201         /**
202          * Unset a configuration key, the entry must be there or else an
203          * exception is thrown.
204          *
205          * @param       $configKey      Configuration key to unset
206          * @return      void
207          * @throws      NoConfigEntryException  If a configuration element was not found
208          */
209         public final function unsetConfigEntry ($configKey) {
210                 // Convert dashes to underscore
211                 $configKey = $this->convertDashesToUnderscores($configKey);
212
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);
217                 } // END - if
218
219                 // Unset it
220                 unset($this->config[$configKey]);
221         }
222
223         /**
224          * Detects the server address (SERVER_ADDR) and set it in configuration
225          *
226          * @return      $serverAddress  The detected server address
227          * @todo        We have to add some more entries from $_SERVER here
228          */
229         public function detectServerAddress () {
230                 // Is the entry set?
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();
239                         }
240                 } // END - if
241
242                 // Now get it from configuration
243                 $serverAddress = $this->getServerAddress();
244
245                 // Return it
246                 return $serverAddress;
247         }
248
249         /**
250          * Setter for SERVER_ADDR
251          *
252          * @param       $serverAddress  New SERVER_ADDR value to set
253          * @return      void
254          */
255         public function setServerAddress ($serverAddress) {
256                 $this->setConfigEntry('server_addr', (string) $serverAddress);
257         }
258
259         /**
260          * Getter for SERVER_ADDR
261          *
262          * @return      $serverAddress  New SERVER_ADDR value to set
263          */
264         public function getServerAddress () {
265                 return $this->getConfigEntry('server_addr');
266         }
267
268         /**
269          * Detects the HTTPS flag
270          *
271          * @return      $https  The detected HTTPS flag or null if failed
272          */
273         public function detectHttpSecured () {
274                 // Default is null
275                 $https = NULL;
276
277                 // Is HTTPS set?
278                 if ($this->isHttpSecured()) {
279                         // Then use it
280                         $https = $_SERVER['HTTPS'];
281                 } // END - if
282
283                 // Return it
284                 return $https;
285         }
286
287         /**
288          * Checks whether HTTPS is set in $_SERVER
289          *
290          * @return $isset       Whether HTTPS is set
291          */
292         public function isHttpSecured () {
293                 return (isset($_SERVER['HTTPS']));
294         }
295
296         /**
297          * Dectect and return the base URL for all URLs and forms
298          *
299          * @return      $baseUrl        Detected base URL
300          */
301         public function detectBaseUrl () {
302                 // Initialize the URL
303                 $baseUrl = 'http';
304
305                 // Do we have HTTPS?
306                 if ($this->isHttpSecured()) {
307                         // Add the >s< for HTTPS
308                         $baseUrl .= 's';
309                 } // END - if
310
311                 // Construct the full URL and secure it against CSRF attacks
312                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
313
314                 // Return the URL
315                 return $baseUrl;
316         }
317
318         /**
319          * Detect safely and return the full domain where this script is installed
320          *
321          * @return      $fullDomain             The detected full domain
322          */
323         public function detectDomain () {
324                 // Full domain is localnet.invalid by default
325                 $fullDomain = 'localnet.invalid';
326
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);
331                 } // END - if
332
333                 // Return it
334                 return $fullDomain;
335         }
336
337         /**
338          * Detect safely the script path without trailing slash which is the glue
339          * between "http://your-domain.invalid/" and "script-name.php"
340          *
341          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
342          */
343         public function detectScriptPath () {
344                 // Default is empty
345                 $scriptPath = '';
346
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']));
351                 } // END - if
352
353                 // Return it
354                 return $scriptPath;
355         }
356
357         /**
358          * Getter for field name
359          *
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
363          */
364         public final function getField ($fieldName) {
365                 // Our super interface "FrameworkInterface" requires this
366         }
367
368         /**
369          * Checks if given field is set
370          *
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
374          */
375         public function isFieldSet ($fieldName) {
376                 // Our super interface "FrameworkInterface" requires this
377         }
378
379         /**
380          * Generates a code for hashes from this class
381          *
382          * @return      $hashCode       The hash code respresenting this class
383          */
384         public function hashCode () {
385                 return crc32($this->__toString());
386         }
387
388         /**
389          * Checks whether an object equals this object. You should overwrite this
390          * method to implement own equality checks
391          *
392          * @param       $objectInstance         An instance of a FrameworkInterface object
393          * @return      $equals                         Whether both objects equals
394          */
395         public function equals (FrameworkInterface $objectInstance) {
396                 // Now test it
397                 $equals = ((
398                         $this->__toString() == $objectInstance->__toString()
399                 ) && (
400                         $this->hashCode() == $objectInstance->hashCode()
401                 ));
402
403                 // Return the result
404                 return $equals;
405         }
406 }
407
408 // [EOF]
409 ?>