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