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\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             1.0.1
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          * Checks whether the given configuration key is set
129          *
130          * @param       $configKey      The configuration key we shall check
131          * @return      $isset          Whether the given configuration key is set
132          */
133         public function isConfigurationEntrySet ($configKey) {
134                 // Is it set?
135                 $isset = isset($this->config[$configKey]);
136
137                 // Return the result
138                 return $isset;
139         }
140
141         /**
142          * Read a configuration element.
143          *
144          * @param       $configKey              The configuration element
145          * @return      $configValue    The fetched configuration value
146          * @throws      ConfigEntryIsEmptyException             If $configKey is empty
147          * @throws      NoConfigEntryException                  If a configuration element was not found
148          */
149         public function getConfigEntry ($configKey) {
150                 // Convert dashes to underscore
151                 $configKey = self::convertDashesToUnderscores($configKey);
152
153                 // Is a valid configuration key provided?
154                 if (empty($configKey)) {
155                         // Entry is empty
156                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
157                 } elseif (!$this->isConfigurationEntrySet($configKey)) {
158                         // Entry was not found!
159                         throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
160                 }
161
162                 // Return the requested value
163                 return $this->config[$configKey];
164         }
165
166         /**
167          * Set a configuration key
168          *
169          * @param       $configKey      The configuration key we want to add/change
170          * @param       $configValue    The configuration value we want to set
171          * @return      void
172          * @throws      ConfigEntryIsEmptyException                     If $configKey is empty
173          * @throws      ConfigValueTypeUnsupportedException     If $configValue has an unsupported variable type
174          */
175         public final function setConfigEntry ($configKey, $configValue) {
176                 // Cast to string
177                 $configKey = self::convertDashesToUnderscores($configKey);
178
179                 // Is a valid configuration key key provided?
180                 if (is_null($configKey)) {
181                         // Configuration key is null
182                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
183                 } elseif ((empty($configKey)) || (!is_string($configKey))) {
184                         // Entry is empty
185                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
186                 } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
187                         // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
188                         throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
189                 }
190
191                 // Set the configuration value
192                 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
193                 $this->config[$configKey] = $configValue;
194
195                 // Resort the array
196                 ksort($this->config);
197         }
198
199         /**
200          * Getter for whole configuration array
201          *
202          * @return      $config         Configuration array
203          */
204         public final function getConfigurationArray () {
205                 // Return it
206                 return $this->config;
207         }
208
209         /**
210          * Unset a configuration key, the entry must be there or else an
211          * exception is thrown.
212          *
213          * @param       $configKey      Configuration key to unset
214          * @return      void
215          * @throws      NoConfigEntryException  If a configuration element was not found
216          */
217         public final function unsetConfigEntry ($configKey) {
218                 // Convert dashes to underscore
219                 $configKey = self::convertDashesToUnderscores($configKey);
220
221                 // Is the configuration key there?
222                 if (!$this->isConfigurationEntrySet($configKey)) {
223                         // Entry was not found!
224                         throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
225                 } // END - if
226
227                 // Unset it
228                 unset($this->config[$configKey]);
229         }
230
231         /**
232          * Detects the server address (SERVER_ADDR) and set it in configuration
233          *
234          * @return      $serverAddress  The detected server address
235          * @throws      UnknownHostnameException        If SERVER_NAME cannot be resolved to an IP address
236          * @todo        Have to check some more entries from $_SERVER here
237          */
238         public function detectServerAddress () {
239                 // Is the entry set?
240                 if (!$this->isConfigurationEntrySet('server_addr')) {
241                         // Is it set in $_SERVER?
242                         if (isset($_SERVER['SERVER_ADDR'])) {
243                                 // Set it from $_SERVER
244                                 $this->setServerAddress($_SERVER['SERVER_ADDR']);
245                         } elseif (isset($_SERVER['SERVER_NAME'])) {
246                                 // Resolve IP address
247                                 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
248
249                                 // Is it valid?
250                                 if ($serverIp === false) {
251                                         /*
252                                          * Why is gethostbyname() returning the host name and not
253                                          * false as many other PHP functions are doing? ;-(
254                                          */
255                                         throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
256                                 } // END - if
257
258                                 // Al fine, set it
259                                 $this->setServerAddress($serverIp);
260                         } else {
261                                 // Run auto-detecting through console tools lib
262                                 ConsoleTools::acquireSelfIPAddress();
263                         }
264                 } // END - if
265
266                 // Now get it from configuration
267                 $serverAddress = $this->getServerAddress();
268
269                 // Return it
270                 return $serverAddress;
271         }
272
273         /**
274          * Setter for SERVER_ADDR
275          *
276          * @param       $serverAddress  New SERVER_ADDR value to set
277          * @return      void
278          */
279         public function setServerAddress ($serverAddress) {
280                 $this->setConfigEntry('server_addr', (string) $serverAddress);
281         }
282
283         /**
284          * Getter for SERVER_ADDR
285          *
286          * @return      $serverAddress  New SERVER_ADDR value to set
287          */
288         public function getServerAddress () {
289                 return $this->getConfigEntry('server_addr');
290         }
291
292         /**
293          * Detects the HTTPS flag
294          *
295          * @return      $isSecured      The detected HTTPS flag or null if failed
296          */
297         public function detectHttpSecured () {
298                 // Default is null
299                 $isSecured = NULL;
300
301                 // Is HTTPS set?
302                 if ($this->isHttpSecured()) {
303                         // Then use it
304                         $isSecured = $_SERVER['HTTPS'];
305                 } // END - if
306
307                 // Return it
308                 return $isSecured;
309         }
310
311         /**
312          * Checks whether HTTPS is set in $_SERVER
313          *
314          * @return $isset       Whether HTTPS is set
315          */
316         public function isHttpSecured () {
317                 return (isset($_SERVER['HTTPS']));
318         }
319
320         /**
321          * Dectect and return the base URL for all URLs and forms
322          *
323          * @return      $baseUrl        Detected base URL
324          */
325         public function detectBaseUrl () {
326                 // Initialize the URL
327                 $baseUrl = 'http';
328
329                 // Do we have HTTPS?
330                 if ($this->isHttpSecured()) {
331                         // Add the >s< for HTTPS
332                         $baseUrl .= 's';
333                 } // END - if
334
335                 // Construct the full URL and secure it against CSRF attacks
336                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
337
338                 // Return the URL
339                 return $baseUrl;
340         }
341
342         /**
343          * Detect safely and return the full domain where this script is installed
344          *
345          * @return      $fullDomain             The detected full domain
346          */
347         public function detectDomain () {
348                 // Full domain is localnet.invalid by default
349                 $fullDomain = 'localnet.invalid';
350
351                 // Is the server name there?
352                 if (isset($_SERVER['SERVER_NAME'])) {
353                         // Detect the full domain
354                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
355                 } // END - if
356
357                 // Return it
358                 return $fullDomain;
359         }
360
361         /**
362          * Detect safely the script path without trailing slash which is the glue
363          * between "http://your-domain.invalid/" and "script-name.php"
364          *
365          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
366          */
367         public function detectScriptPath () {
368                 // Default is empty
369                 $scriptPath = '';
370
371                 // Is the scriptname set?
372                 if (isset($_SERVER['SCRIPT_NAME'])) {
373                         // Get dirname from it and replace back-slashes with slashes for lame OSes...
374                         $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
375                 } // END - if
376
377                 // Return it
378                 return $scriptPath;
379         }
380
381         /**
382          * Getter for field name
383          *
384          * @param       $fieldName              Field name which we shall get
385          * @return      $fieldValue             Field value from the user
386          * @throws      NullPointerException    If the result instance is null
387          */
388         public final function getField ($fieldName) {
389                 // The super interface "FrameworkInterface" requires this
390                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
391         }
392
393         /**
394          * Checks if given field is set
395          *
396          * @param       $fieldName      Field name to check
397          * @return      $isSet          Whether the given field name is set
398          * @throws      NullPointerException    If the result instance is null
399          */
400         public function isFieldSet ($fieldName) {
401                 // The super interface "FrameworkInterface" requires this
402                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
403         }
404
405         /**
406          * Generates a code for hashes from this class
407          *
408          * @return      $hashCode       The hash code respresenting this class
409          */
410         public function hashCode () {
411                 return crc32($this->__toString());
412         }
413
414         /**
415          * Checks whether an object equals this object. You should overwrite this
416          * method to implement own equality checks
417          *
418          * @param       $objectInstance         An instance of a FrameworkInterface object
419          * @return      $equals                         Whether both objects equals
420          */
421         public function equals (FrameworkInterface $objectInstance) {
422                 // Now test it
423                 $equals = ((
424                         $this->__toString() === $objectInstance->__toString()
425                 ) && (
426                         $this->hashCode() === $objectInstance->hashCode()
427                 ));
428
429                 // Return the result
430                 return $equals;
431         }
432
433         /**
434          * Setter for call-back instance
435          *
436          * @param       $callbackInstance       An instance of a FrameworkInterface class
437          * @return      void
438          */
439         public function setCallbackInstance (FrameworkInterface $callbackInstance) {
440                 $this->callbackInstance = $callbackInstance;
441         }
442
443 }