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