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