Continued:
[core.git] / inc / config / class_FrameworkConfiguration.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Configuration;
4
5 // Load framework stuff
6 use CoreFramework\Generic\FrameworkInterface;
7 use CoreFramework\Registry\Registerable;
8
9 /**
10  * A class for the configuration stuff implemented in a singleton design paddern
11  *
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
14  *
15  * @see                 ClassLoader
16  * @author              Roland Haeder <webmaster@shipsimu.org>
17  * @version             0.0.0
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
21  *
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.
26  *
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.
31  *
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/>.
34  */
35 class FrameworkConfiguration implements Registerable {
36         /**
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.
40          */
41         private $config = array();
42
43         /**
44          * The configuration instance itself
45          */
46         private static $configInstance = NULL;
47
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;
52
53         /**
54          * Protected constructor
55          *
56          * @return      void
57          */
58         protected function __construct () {
59                 // Empty for now
60         }
61
62         /**
63          * Compatiblity method to return this class' name
64          *
65          * @return      __CLASS__       This class' name
66          */
67         public function __toString () {
68                 return get_class($this);
69         }
70
71         /**
72          * Getter for a singleton instance of this class
73          *
74          * @return      $configInstance         A singleton instance of this class
75          */
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();
81                 } // END - if
82
83                 // Return singleton instance
84                 return self::$configInstance;
85         }
86
87         /**
88          * Converts dashes to underscores, e.g. useable for configuration entries
89          *
90          * @param       $str    The string with maybe dashes inside
91          * @return      $str    The converted string with no dashed, but underscores
92          */
93         private final function convertDashesToUnderscores ($str) {
94                 // Convert them all
95                 $str = str_replace('-', '_', $str);
96
97                 // Return converted string
98                 return $str;
99         }
100
101         /**
102          * Setter for default time zone (must be correct!)
103          *
104          * @param       $zone   The time-zone string (e.g. Europe/Berlin)
105          * @return      void
106          */
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', '>=')) {
110                         /*
111                          * Set desired time zone to prevent date() and related functions to
112                          * issue a E_WARNING.
113                          */
114                         date_default_timezone_set($zone);
115                 } // END - if
116         }
117
118         /**
119          * Setter for runtime magic quotes
120          *
121          * @param       $enableQuotes   Whether enable magic runtime quotes (should be disabled for security reasons)
122          * @return      void
123          * @todo        This method encapsulates a deprecated PHP function and should be deprecated, too.
124          */
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
129                         return;
130                 } // END - if
131
132                 // Cast it to boolean
133                 $enableQuotes = (boolean) $enableQuotes;
134
135                 // Set it
136                 set_magic_quotes_runtime($enableQuotes);
137         }
138
139         /**
140          * Checks whether the given configuration key is set
141          *
142          * @param       $configKey      The configuration key we shall check
143          * @return      $isset          Whether the given configuration key is set
144          */
145         public function isConfigurationEntrySet ($configKey) {
146                 // Is it set?
147                 $isset = isset($this->config[$configKey]);
148
149                 // Return the result
150                 return $isset;
151         }
152
153         /**
154          * Read a configuration element.
155          *
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
160          */
161         public function getConfigEntry ($configKey) {
162                 // Convert dashes to underscore
163                 $configKey = self::convertDashesToUnderscores($configKey);
164
165                 // Is a valid configuration key provided?
166                 if (empty($configKey)) {
167                         // Entry is empty
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);
172                 }
173
174                 // Return the requested value
175                 return $this->config[$configKey];
176         }
177
178         /**
179          * Set a configuration key
180          *
181          * @param       $configKey      The configuration key we want to add/change
182          * @param       $configValue    The configuration value we want to set
183          * @return      void
184          * @throws      ConfigEntryIsEmptyException                     If $configKey is empty
185          * @throws      ConfigValueTypeUnsupportedException     If $configValue has an unsupported variable type
186          */
187         public final function setConfigEntry ($configKey, $configValue) {
188                 // Cast to string
189                 $configKey = self::convertDashesToUnderscores($configKey);
190
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))) {
196                         // Entry is empty
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);
201                 }
202
203                 // Set the configuration value
204                 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
205                 $this->config[$configKey] = $configValue;
206
207                 // Resort the array
208                 ksort($this->config);
209         }
210
211         /**
212          * Unset a configuration key, the entry must be there or else an
213          * exception is thrown.
214          *
215          * @param       $configKey      Configuration key to unset
216          * @return      void
217          * @throws      NoConfigEntryException  If a configuration element was not found
218          */
219         public final function unsetConfigEntry ($configKey) {
220                 // Convert dashes to underscore
221                 $configKey = self::convertDashesToUnderscores($configKey);
222
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);
227                 } // END - if
228
229                 // Unset it
230                 unset($this->config[$configKey]);
231         }
232
233         /**
234          * Detects the server address (SERVER_ADDR) and set it in configuration
235          *
236          * @return      $serverAddress  The detected server address
237          * @todo        We have to add some more entries from $_SERVER here
238          */
239         public function detectServerAddress () {
240                 // Is the entry set?
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();
249                         }
250                 } // END - if
251
252                 // Now get it from configuration
253                 $serverAddress = $this->getServerAddress();
254
255                 // Return it
256                 return $serverAddress;
257         }
258
259         /**
260          * Setter for SERVER_ADDR
261          *
262          * @param       $serverAddress  New SERVER_ADDR value to set
263          * @return      void
264          */
265         public function setServerAddress ($serverAddress) {
266                 $this->setConfigEntry('server_addr', (string) $serverAddress);
267         }
268
269         /**
270          * Getter for SERVER_ADDR
271          *
272          * @return      $serverAddress  New SERVER_ADDR value to set
273          */
274         public function getServerAddress () {
275                 return $this->getConfigEntry('server_addr');
276         }
277
278         /**
279          * Detects the HTTPS flag
280          *
281          * @return      $https  The detected HTTPS flag or null if failed
282          */
283         public function detectHttpSecured () {
284                 // Default is null
285                 $https = NULL;
286
287                 // Is HTTPS set?
288                 if ($this->isHttpSecured()) {
289                         // Then use it
290                         $https = $_SERVER['HTTPS'];
291                 } // END - if
292
293                 // Return it
294                 return $https;
295         }
296
297         /**
298          * Checks whether HTTPS is set in $_SERVER
299          *
300          * @return $isset       Whether HTTPS is set
301          */
302         public function isHttpSecured () {
303                 return (isset($_SERVER['HTTPS']));
304         }
305
306         /**
307          * Dectect and return the base URL for all URLs and forms
308          *
309          * @return      $baseUrl        Detected base URL
310          */
311         public function detectBaseUrl () {
312                 // Initialize the URL
313                 $baseUrl = 'http';
314
315                 // Do we have HTTPS?
316                 if ($this->isHttpSecured()) {
317                         // Add the >s< for HTTPS
318                         $baseUrl .= 's';
319                 } // END - if
320
321                 // Construct the full URL and secure it against CSRF attacks
322                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
323
324                 // Return the URL
325                 return $baseUrl;
326         }
327
328         /**
329          * Detect safely and return the full domain where this script is installed
330          *
331          * @return      $fullDomain             The detected full domain
332          */
333         public function detectDomain () {
334                 // Full domain is localnet.invalid by default
335                 $fullDomain = 'localnet.invalid';
336
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);
341                 } // END - if
342
343                 // Return it
344                 return $fullDomain;
345         }
346
347         /**
348          * Detect safely the script path without trailing slash which is the glue
349          * between "http://your-domain.invalid/" and "script-name.php"
350          *
351          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
352          */
353         public function detectScriptPath () {
354                 // Default is empty
355                 $scriptPath = '';
356
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']));
361                 } // END - if
362
363                 // Return it
364                 return $scriptPath;
365         }
366
367         /**
368          * Getter for field name
369          *
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
373          */
374         public final function getField ($fieldName) {
375                 // Our super interface "FrameworkInterface" requires this
376                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
377         }
378
379         /**
380          * Checks if given field is set
381          *
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
385          */
386         public function isFieldSet ($fieldName) {
387                 // Our super interface "FrameworkInterface" requires this
388                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
389         }
390
391         /**
392          * Generates a code for hashes from this class
393          *
394          * @return      $hashCode       The hash code respresenting this class
395          */
396         public function hashCode () {
397                 return crc32($this->__toString());
398         }
399
400         /**
401          * Checks whether an object equals this object. You should overwrite this
402          * method to implement own equality checks
403          *
404          * @param       $objectInstance         An instance of a FrameworkInterface object
405          * @return      $equals                         Whether both objects equals
406          */
407         public function equals (FrameworkInterface $objectInstance) {
408                 // Now test it
409                 $equals = ((
410                         $this->__toString() == $objectInstance->__toString()
411                 ) && (
412                         $this->hashCode() == $objectInstance->hashCode()
413                 ));
414
415                 // Return the result
416                 return $equals;
417         }
418
419 }