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\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          * Getter for whole configuration array
214          *
215          * @return      $config         Configuration array
216          */
217         public final function getConfigurationArray () {
218                 // Return it
219                 return $this->config;
220         }
221
222         /**
223          * Unset a configuration key, the entry must be there or else an
224          * exception is thrown.
225          *
226          * @param       $configKey      Configuration key to unset
227          * @return      void
228          * @throws      NoConfigEntryException  If a configuration element was not found
229          */
230         public final function unsetConfigEntry ($configKey) {
231                 // Convert dashes to underscore
232                 $configKey = self::convertDashesToUnderscores($configKey);
233
234                 // Is the configuration key there?
235                 if (!$this->isConfigurationEntrySet($configKey)) {
236                         // Entry was not found!
237                         throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
238                 } // END - if
239
240                 // Unset it
241                 unset($this->config[$configKey]);
242         }
243
244         /**
245          * Detects the server address (SERVER_ADDR) and set it in configuration
246          *
247          * @return      $serverAddress  The detected server address
248          * @todo        We have to add some more entries from $_SERVER here
249          */
250         public function detectServerAddress () {
251                 // Is the entry set?
252                 if (!$this->isConfigurationEntrySet('server_addr')) {
253                         // Is it set in $_SERVER?
254                         if (isset($_SERVER['SERVER_ADDR'])) {
255                                 // Set it from $_SERVER
256                                 $this->setServerAddress($_SERVER['SERVER_ADDR']);
257                         } elseif (class_exists('ConsoleTools')) {
258                                 // Run auto-detecting through console tools lib
259                                 ConsoleTools::acquireSelfIPAddress();
260                         }
261                 } // END - if
262
263                 // Now get it from configuration
264                 $serverAddress = $this->getServerAddress();
265
266                 // Return it
267                 return $serverAddress;
268         }
269
270         /**
271          * Setter for SERVER_ADDR
272          *
273          * @param       $serverAddress  New SERVER_ADDR value to set
274          * @return      void
275          */
276         public function setServerAddress ($serverAddress) {
277                 $this->setConfigEntry('server_addr', (string) $serverAddress);
278         }
279
280         /**
281          * Getter for SERVER_ADDR
282          *
283          * @return      $serverAddress  New SERVER_ADDR value to set
284          */
285         public function getServerAddress () {
286                 return $this->getConfigEntry('server_addr');
287         }
288
289         /**
290          * Detects the HTTPS flag
291          *
292          * @return      $https  The detected HTTPS flag or null if failed
293          */
294         public function detectHttpSecured () {
295                 // Default is null
296                 $https = NULL;
297
298                 // Is HTTPS set?
299                 if ($this->isHttpSecured()) {
300                         // Then use it
301                         $https = $_SERVER['HTTPS'];
302                 } // END - if
303
304                 // Return it
305                 return $https;
306         }
307
308         /**
309          * Checks whether HTTPS is set in $_SERVER
310          *
311          * @return $isset       Whether HTTPS is set
312          */
313         public function isHttpSecured () {
314                 return (isset($_SERVER['HTTPS']));
315         }
316
317         /**
318          * Dectect and return the base URL for all URLs and forms
319          *
320          * @return      $baseUrl        Detected base URL
321          */
322         public function detectBaseUrl () {
323                 // Initialize the URL
324                 $baseUrl = 'http';
325
326                 // Do we have HTTPS?
327                 if ($this->isHttpSecured()) {
328                         // Add the >s< for HTTPS
329                         $baseUrl .= 's';
330                 } // END - if
331
332                 // Construct the full URL and secure it against CSRF attacks
333                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
334
335                 // Return the URL
336                 return $baseUrl;
337         }
338
339         /**
340          * Detect safely and return the full domain where this script is installed
341          *
342          * @return      $fullDomain             The detected full domain
343          */
344         public function detectDomain () {
345                 // Full domain is localnet.invalid by default
346                 $fullDomain = 'localnet.invalid';
347
348                 // Is the server name there?
349                 if (isset($_SERVER['SERVER_NAME'])) {
350                         // Detect the full domain
351                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
352                 } // END - if
353
354                 // Return it
355                 return $fullDomain;
356         }
357
358         /**
359          * Detect safely the script path without trailing slash which is the glue
360          * between "http://your-domain.invalid/" and "script-name.php"
361          *
362          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
363          */
364         public function detectScriptPath () {
365                 // Default is empty
366                 $scriptPath = '';
367
368                 // Is the scriptname set?
369                 if (isset($_SERVER['SCRIPT_NAME'])) {
370                         // Get dirname from it and replace back-slashes with slashes for lame OSes...
371                         $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
372                 } // END - if
373
374                 // Return it
375                 return $scriptPath;
376         }
377
378         /**
379          * Getter for field name
380          *
381          * @param       $fieldName              Field name which we shall get
382          * @return      $fieldValue             Field value from the user
383          * @throws      NullPointerException    If the result instance is null
384          */
385         public final function getField ($fieldName) {
386                 // Our super interface "FrameworkInterface" requires this
387                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
388         }
389
390         /**
391          * Checks if given field is set
392          *
393          * @param       $fieldName      Field name to check
394          * @return      $isSet          Whether the given field name is set
395          * @throws      NullPointerException    If the result instance is null
396          */
397         public function isFieldSet ($fieldName) {
398                 // Our super interface "FrameworkInterface" requires this
399                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
400         }
401
402         /**
403          * Generates a code for hashes from this class
404          *
405          * @return      $hashCode       The hash code respresenting this class
406          */
407         public function hashCode () {
408                 return crc32($this->__toString());
409         }
410
411         /**
412          * Checks whether an object equals this object. You should overwrite this
413          * method to implement own equality checks
414          *
415          * @param       $objectInstance         An instance of a FrameworkInterface object
416          * @return      $equals                         Whether both objects equals
417          */
418         public function equals (FrameworkInterface $objectInstance) {
419                 // Now test it
420                 $equals = ((
421                         $this->__toString() == $objectInstance->__toString()
422                 ) && (
423                         $this->hashCode() == $objectInstance->hashCode()
424                 ));
425
426                 // Return the result
427                 return $equals;
428         }
429
430 }