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