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