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