Rewrite continued:
[core.git] / framework / config / class_FrameworkConfiguration.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Configuration;
4
5 // Import framework stuff
6 use CoreFramework\Console\Tools\ConsoleTools;
7 use CoreFramework\Dns\UnknownHostnameException;
8 use CoreFramework\Generic\FrameworkInterface;
9 use CoreFramework\Generic\NullPointerException;
10 use CoreFramework\Registry\Registerable;
11
12 /**
13  * A class for the configuration stuff implemented in a singleton design paddern
14  *
15  * NOTE: We cannot put this in framework/main/ because it would be loaded (again) in
16  * class loader. See framework/loader/class_ClassLoader.php for instance
17  *
18  * @see                 ClassLoader
19  * @author              Roland Haeder <webmaster@shipsimu.org>
20  * @version             0.0.0
21  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
22  * @license             GNU GPL 3.0 or any newer version
23  * @link                http://www.shipsimu.org
24  *
25  * This program is free software: you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation, either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program. If not, see <http://www.gnu.org/licenses/>.
37  */
38 class FrameworkConfiguration implements Registerable {
39         /**
40          * The framework's main configuration array which will be initialized with
41          * hard-coded configuration data and might be overwritten/extended by
42          * config data from the database.
43          */
44         private $config = array();
45
46         /**
47          * The configuration instance itself
48          */
49         private static $configInstance = NULL;
50
51         // Some constants for the configuration system
52         const EXCEPTION_CONFIG_KEY_IS_EMPTY           = 0x130;
53         const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND      = 0x131;
54         const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
55
56         /**
57          * Protected constructor
58          *
59          * @return      void
60          */
61         protected function __construct () {
62                 // Empty for now
63         }
64
65         /**
66          * Compatiblity method to return this class' name
67          *
68          * @return      __CLASS__       This class' name
69          */
70         public function __toString () {
71                 return get_class($this);
72         }
73
74         /**
75          * Getter for a singleton instance of this class
76          *
77          * @return      $configInstance         A singleton instance of this class
78          */
79         public static final function getSelfInstance () {
80                 // is the instance there?
81                 if (is_null(self::$configInstance))  {
82                         // Create a config instance
83                         self::$configInstance = new FrameworkConfiguration();
84                 } // END - if
85
86                 // Return singleton instance
87                 return self::$configInstance;
88         }
89
90         /**
91          * Converts dashes to underscores, e.g. useable for configuration entries
92          *
93          * @param       $str    The string with maybe dashes inside
94          * @return      $str    The converted string with no dashed, but underscores
95          */
96         private final function convertDashesToUnderscores ($str) {
97                 // Convert them all
98                 $str = str_replace('-', '_', $str);
99
100                 // Return converted string
101                 return $str;
102         }
103
104         /**
105          * Setter for default time zone (must be correct!)
106          *
107          * @param       $zone   The time-zone string (e.g. Europe/Berlin)
108          * @return      void
109          */
110         public final function setDefaultTimezone ($zone) {
111                 // Is PHP version 5.1.0 or higher? Older versions are being ignored
112                 if (version_compare(phpversion(), '5.1.0', '>=')) {
113                         /*
114                          * Set desired time zone to prevent date() and related functions to
115                          * issue a E_WARNING.
116                          */
117                         date_default_timezone_set($zone);
118                 } // END - if
119         }
120
121         /**
122          * Setter for runtime magic quotes
123          *
124          * @param       $enableQuotes   Whether enable magic runtime quotes (should be disabled for security reasons)
125          * @return      void
126          * @todo        This method encapsulates a deprecated PHP function and should be deprecated, too.
127          */
128         public final function setMagicQuotesRuntime ($enableQuotes) {
129                 // Is the PHP version < 5.4?
130                 if (version_compare(phpversion(), '5.4', '>=')) {
131                         // Then silently skip this part as set_magic_quotes_runtime() is deprecated
132                         return;
133                 } // END - if
134
135                 // Cast it to boolean
136                 $enableQuotes = (boolean) $enableQuotes;
137
138                 // Set it
139                 set_magic_quotes_runtime($enableQuotes);
140         }
141
142         /**
143          * Checks whether the given configuration key is set
144          *
145          * @param       $configKey      The configuration key we shall check
146          * @return      $isset          Whether the given configuration key is set
147          */
148         public function isConfigurationEntrySet ($configKey) {
149                 // Is it set?
150                 $isset = isset($this->config[$configKey]);
151
152                 // Return the result
153                 return $isset;
154         }
155
156         /**
157          * Read a configuration element.
158          *
159          * @param       $configKey              The configuration element
160          * @return      $configValue    The fetched configuration value
161          * @throws      ConfigEntryIsEmptyException             If $configKey is empty
162          * @throws      NoConfigEntryException                  If a configuration element was not found
163          */
164         public function getConfigEntry ($configKey) {
165                 // Convert dashes to underscore
166                 $configKey = self::convertDashesToUnderscores($configKey);
167
168                 // Is a valid configuration key provided?
169                 if (empty($configKey)) {
170                         // Entry is empty
171                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
172                 } elseif (!$this->isConfigurationEntrySet($configKey)) {
173                         // Entry was not found!
174                         throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
175                 }
176
177                 // Return the requested value
178                 return $this->config[$configKey];
179         }
180
181         /**
182          * Set a configuration key
183          *
184          * @param       $configKey      The configuration key we want to add/change
185          * @param       $configValue    The configuration value we want to set
186          * @return      void
187          * @throws      ConfigEntryIsEmptyException                     If $configKey is empty
188          * @throws      ConfigValueTypeUnsupportedException     If $configValue has an unsupported variable type
189          */
190         public final function setConfigEntry ($configKey, $configValue) {
191                 // Cast to string
192                 $configKey = self::convertDashesToUnderscores($configKey);
193
194                 // Is a valid configuration key key provided?
195                 if (is_null($configKey)) {
196                         // Configuration key is null
197                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
198                 } elseif ((empty($configKey)) || (!is_string($configKey))) {
199                         // Entry is empty
200                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
201                 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
202                         // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
203                         throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
204                 }
205
206                 // Set the configuration value
207                 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
208                 $this->config[$configKey] = $configValue;
209
210                 // Resort the array
211                 ksort($this->config);
212         }
213
214         /**
215          * Getter for whole configuration array
216          *
217          * @return      $config         Configuration array
218          */
219         public final function getConfigurationArray () {
220                 // Return it
221                 return $this->config;
222         }
223
224         /**
225          * Unset a configuration key, the entry must be there or else an
226          * exception is thrown.
227          *
228          * @param       $configKey      Configuration key to unset
229          * @return      void
230          * @throws      NoConfigEntryException  If a configuration element was not found
231          */
232         public final function unsetConfigEntry ($configKey) {
233                 // Convert dashes to underscore
234                 $configKey = self::convertDashesToUnderscores($configKey);
235
236                 // Is the configuration key there?
237                 if (!$this->isConfigurationEntrySet($configKey)) {
238                         // Entry was not found!
239                         throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
240                 } // END - if
241
242                 // Unset it
243                 unset($this->config[$configKey]);
244         }
245
246         /**
247          * Detects the server address (SERVER_ADDR) and set it in configuration
248          *
249          * @return      $serverAddress  The detected server address
250          * @throws      UnknownHostnameException        If SERVER_NAME cannot be resolved to an IP address
251          * @todo        Have to check some more entries from $_SERVER here
252          */
253         public function detectServerAddress () {
254                 // Is the entry set?
255                 if (!$this->isConfigurationEntrySet('server_addr')) {
256                         // Is it set in $_SERVER?
257                         if (isset($_SERVER['SERVER_ADDR'])) {
258                                 // Set it from $_SERVER
259                                 $this->setServerAddress($_SERVER['SERVER_ADDR']);
260                         } elseif (isset($_SERVER['SERVER_NAME'])) {
261                                 // Resolve IP address
262                                 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
263
264                                 // Is it valid?
265                                 if ($serverIp === false) {
266                                         /*
267                                          * Why is gethostbyname() returning the host name and not
268                                          * false as many other PHP functions are doing? ;-(
269                                          */
270                                         throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
271                                 } // END - if
272
273                                 // Al fine, set it
274                                 $this->setServerAddress($serverIp);
275                         } elseif (class_exists('ConsoleTools')) {
276                                 // Run auto-detecting through console tools lib
277                                 ConsoleTools::acquireSelfIPAddress();
278                         }
279                 } // END - if
280
281                 // Now get it from configuration
282                 $serverAddress = $this->getServerAddress();
283
284                 // Return it
285                 return $serverAddress;
286         }
287
288         /**
289          * Setter for SERVER_ADDR
290          *
291          * @param       $serverAddress  New SERVER_ADDR value to set
292          * @return      void
293          */
294         public function setServerAddress ($serverAddress) {
295                 $this->setConfigEntry('server_addr', (string) $serverAddress);
296         }
297
298         /**
299          * Getter for SERVER_ADDR
300          *
301          * @return      $serverAddress  New SERVER_ADDR value to set
302          */
303         public function getServerAddress () {
304                 return $this->getConfigEntry('server_addr');
305         }
306
307         /**
308          * Detects the HTTPS flag
309          *
310          * @return      $isSecured      The detected HTTPS flag or null if failed
311          */
312         public function detectHttpSecured () {
313                 // Default is null
314                 $isSecured = NULL;
315
316                 // Is HTTPS set?
317                 if ($this->isHttpSecured()) {
318                         // Then use it
319                         $isSecured = $_SERVER['HTTPS'];
320                 } // END - if
321
322                 // Return it
323                 return $isSecured;
324         }
325
326         /**
327          * Checks whether HTTPS is set in $_SERVER
328          *
329          * @return $isset       Whether HTTPS is set
330          */
331         public function isHttpSecured () {
332                 return (isset($_SERVER['HTTPS']));
333         }
334
335         /**
336          * Dectect and return the base URL for all URLs and forms
337          *
338          * @return      $baseUrl        Detected base URL
339          */
340         public function detectBaseUrl () {
341                 // Initialize the URL
342                 $baseUrl = 'http';
343
344                 // Do we have HTTPS?
345                 if ($this->isHttpSecured()) {
346                         // Add the >s< for HTTPS
347                         $baseUrl .= 's';
348                 } // END - if
349
350                 // Construct the full URL and secure it against CSRF attacks
351                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
352
353                 // Return the URL
354                 return $baseUrl;
355         }
356
357         /**
358          * Detect safely and return the full domain where this script is installed
359          *
360          * @return      $fullDomain             The detected full domain
361          */
362         public function detectDomain () {
363                 // Full domain is localnet.invalid by default
364                 $fullDomain = 'localnet.invalid';
365
366                 // Is the server name there?
367                 if (isset($_SERVER['SERVER_NAME'])) {
368                         // Detect the full domain
369                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
370                 } // END - if
371
372                 // Return it
373                 return $fullDomain;
374         }
375
376         /**
377          * Detect safely the script path without trailing slash which is the glue
378          * between "http://your-domain.invalid/" and "script-name.php"
379          *
380          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
381          */
382         public function detectScriptPath () {
383                 // Default is empty
384                 $scriptPath = '';
385
386                 // Is the scriptname set?
387                 if (isset($_SERVER['SCRIPT_NAME'])) {
388                         // Get dirname from it and replace back-slashes with slashes for lame OSes...
389                         $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
390                 } // END - if
391
392                 // Return it
393                 return $scriptPath;
394         }
395
396         /**
397          * Getter for field name
398          *
399          * @param       $fieldName              Field name which we shall get
400          * @return      $fieldValue             Field value from the user
401          * @throws      NullPointerException    If the result instance is null
402          */
403         public final function getField ($fieldName) {
404                 // The super interface "FrameworkInterface" requires this
405                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
406         }
407
408         /**
409          * Checks if given field is set
410          *
411          * @param       $fieldName      Field name to check
412          * @return      $isSet          Whether the given field name is set
413          * @throws      NullPointerException    If the result instance is null
414          */
415         public function isFieldSet ($fieldName) {
416                 // The super interface "FrameworkInterface" requires this
417                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
418         }
419
420         /**
421          * Generates a code for hashes from this class
422          *
423          * @return      $hashCode       The hash code respresenting this class
424          */
425         public function hashCode () {
426                 return crc32($this->__toString());
427         }
428
429         /**
430          * Checks whether an object equals this object. You should overwrite this
431          * method to implement own equality checks
432          *
433          * @param       $objectInstance         An instance of a FrameworkInterface object
434          * @return      $equals                         Whether both objects equals
435          */
436         public function equals (FrameworkInterface $objectInstance) {
437                 // Now test it
438                 $equals = ((
439                         $this->__toString() === $objectInstance->__toString()
440                 ) && (
441                         $this->hashCode() === $objectInstance->hashCode()
442                 ));
443
444                 // Return the result
445                 return $equals;
446         }
447
448 }