Make it public now :(
[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@ship-simu.org>
10  * @version             0.0.0
11  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
12  * @license             GNU GPL 3.0 or any newer version
13  * @link                http://www.ship-simu.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                 // At least 5.1.0 is required for this!
101                 if (version_compare(phpversion(), '5.1.0')) {
102                         date_default_timezone_set($zone);
103                 } // END - if
104         }
105
106         /**
107          * Setter for runtime magic quotes
108          *
109          * @param       $enableQuotes   Whether enable magic runtime quotes (should be disabled for security reasons)
110          * @return      void
111          */
112         public final function setMagicQuotesRuntime ($enableQuotes) {
113                 // Cast it to boolean
114                 $enableQuotes = (boolean) $enableQuotes;
115
116                 // Set it
117                 set_magic_quotes_runtime($enableQuotes);
118         }
119
120         /**
121          * Checks whether the given configuration entry is set
122          *
123          * @param       $configEntry    The configuration entry we shall check
124          * @return      $isset                  Whether the given configuration entry is set
125          */
126         public function isConfigurationEntrySet ($configEntry) {
127                 // Is it set?
128                 $isset = isset($this->config[$configEntry]);
129
130                 // Return the result
131                 return $isset;
132         }
133
134         /**
135          * Read a configuration element.
136          *
137          * @param       $configEntry    The configuration element
138          * @return      $configValue    The fetched configuration value
139          * @throws      ConfigEntryIsEmptyException             If $configEntry is empty
140          * @throws      NoConfigEntryException  If a configuration element was not found
141          */
142         public function getConfigEntry ($configEntry) {
143                 // Convert dashes to underscore
144                 $configEntry = $this->convertDashesToUnderscores($configEntry);
145
146                 // Is a valid configuration entry provided?
147                 if (empty($configEntry)) {
148                         // Entry is empty
149                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_ENTRY_IS_EMPTY);
150                 } elseif (!$this->isConfigurationEntrySet($configEntry)) {
151                         // Entry was not found!
152                         throw new NoConfigEntryException(array(__CLASS__, $configEntry), self::EXCEPTION_CONFIG_ENTRY_WAS_NOT_FOUND);
153                 }
154
155                 // Return the requested value
156                 return $this->config[$configEntry];
157         }
158
159         /**
160          * Set a configuration entry
161          *
162          * @param       $configEntry    The configuration entry we want to add/change
163          * @param       $configValue    The configuration value we want to set
164          * @return      void
165          * @throws      ConfigEntryIsEmptyException             If $configEntry is empty
166          */
167         public final function setConfigEntry ($configEntry, $configValue) {
168                 // Cast to string
169                 $configEntry = $this->convertDashesToUnderscores($configEntry);
170                 $configValue = (string) $configValue;
171
172                 // Is a valid configuration entry provided?
173                 if (empty($configEntry)) {
174                         // Entry is empty
175                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_ENTRY_IS_EMPTY);
176                 } // END - if
177
178                 // Set the configuration value
179                 //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configEntry . ',configValue=' . $configValue . PHP_EOL);
180                 $this->config[$configEntry] = $configValue;
181
182                 // Resort the array
183                 ksort($this->config);
184         }
185
186         /**
187          * Unset a configuration entry, the entry must be there or else an
188          * exception is thrown.
189          *
190          * @param       $configEntry    Configuration entry to unset
191          * @return      void
192          * @throws      NoConfigEntryException  If a configuration element was not found
193          */
194         public final function unsetConfigEntry ($configEntry) {
195                 // Convert dashes to underscore
196                 $configEntry = $this->convertDashesToUnderscores($configEntry);
197
198                 // Is the configuration entry there?
199                 if (!$this->isConfigurationEntrySet($configEntry)) {
200                         // Entry was not found!
201                         throw new NoConfigEntryException(array(__CLASS__, $configEntry), self::EXCEPTION_CONFIG_ENTRY_WAS_NOT_FOUND);
202                 } // END - if
203
204                 // Unset it
205                 unset($this->config[$configEntry]);
206         }
207
208         /**
209          * Detects the server address (SERVER_ADDR) and set it in configuration
210          *
211          * @return      $serverAddress  The detected server address
212          * @todo        We have to add some more entries from $_SERVER here
213          */
214         public function detectServerAddress () {
215                 // Is the entry set?
216                 if (!$this->isConfigurationEntrySet('server_addr')) {
217                         // Is it set in $_SERVER?
218                         if (isset($_SERVER['SERVER_ADDR'])) {
219                                 // Set it from $_SERVER
220                                 $this->setServerAddress($_SERVER['SERVER_ADDR']);
221                         } elseif (class_exists('ConsoleTools')) {
222                                 // Run auto-detecting through console tools lib
223                                 ConsoleTools::acquireSelfIPAddress();
224                         }
225                 } // END - if
226
227                 // Now get it from configuration
228                 $serverAddress = $this->getServerAddress();
229
230                 // Return it
231                 return $serverAddress;
232         }
233
234         /**
235          * Setter for SERVER_ADDR
236          *
237          * @param       $serverAddress  New SERVER_ADDR value to set
238          * @return      void
239          */
240         public function setServerAddress ($serverAddress) {
241                 $this->setConfigEntry('server_addr', (string) $serverAddress);
242         }
243
244         /**
245          * Getter for SERVER_ADDR
246          *
247          * @return      $serverAddress  New SERVER_ADDR value to set
248          */
249         public function getServerAddress () {
250                 return $this->getConfigEntry('server_addr');
251         }
252
253         /**
254          * Detects the HTTPS flag
255          *
256          * @return      $https  The detected HTTPS flag or null if failed
257          */
258         public function detectHttpSecured () {
259                 // Default is null
260                 $https = NULL;
261
262                 // Is HTTPS set?
263                 if ($this->isHttpSecured()) {
264                         // Then use it
265                         $https = $_SERVER['HTTPS'];
266                 } // END - if
267
268                 // Return it
269                 return $https;
270         }
271
272         /**
273          * Checks whether HTTPS is set in $_SERVER
274          *
275          * @return $isset       Whether HTTPS is set
276          */
277         public function isHttpSecured () {
278                 return (isset($_SERVER['HTTPS']));
279         }
280
281         /**
282          * Dectect and return the base URL for all URLs and forms
283          *
284          * @return      $baseUrl        Detected base URL
285          */
286         public function detectBaseUrl () {
287                 // Initialize the URL
288                 $baseUrl = 'http';
289
290                 // Do we have HTTPS?
291                 if ($this->isHttpSecured()) {
292                         // Add the >s< for HTTPS
293                         $baseUrl .= 's';
294                 } // END - if
295
296                 // Construct the full URL and secure it against CSRF attacks
297                 $baseUrl = $baseUrl . '://' . $this->detectDomain() . $this->detectScriptPath();
298
299                 // Return the URL
300                 return $baseUrl;
301         }
302
303         /**
304          * Detect safely and return the full domain where this script is installed
305          *
306          * @return      $fullDomain             The detected full domain
307          */
308         public function detectDomain () {
309                 // Full domain is localnet.invalid by default
310                 $fullDomain = 'localnet.invalid';
311
312                 // Is the server name there?
313                 if (isset($_SERVER['SERVER_NAME'])) {
314                         // Detect the full domain
315                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
316                 } // END - if
317
318                 // Return it
319                 return $fullDomain;
320         }
321
322         /**
323          * Detect safely the script path without trailing slash which is the glue
324          * between "http://your-domain.invalid/" and "script-name.php"
325          *
326          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
327          */
328         public function detectScriptPath () {
329                 // Default is empty
330                 $scriptPath = '';
331
332                 // Is the scriptname set?
333                 if (isset($_SERVER['SCRIPT_NAME'])) {
334                         // Get dirname from it and replace back-slashes with slashes for lame OSes...
335                         $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
336                 } // END - if
337
338                 // Return it
339                 return $scriptPath;
340         }
341
342         /**
343          * Getter for field name
344          *
345          * @param       $fieldName              Field name which we shall get
346          * @return      $fieldValue             Field value from the user
347          * @throws      NullPointerException    If the result instance is null
348          */
349         public final function getField ($fieldName) {
350                 // Our super interface "FrameworkInterface" requires this
351         }
352
353         /**
354          * Generates a code for hashes from this class
355          *
356          * @return      $hashCode       The hash code respresenting this class
357          */
358         public function hashCode () {
359                 return crc32($this->__toString());
360         }
361
362         /**
363          * Checks whether an object equals this object. You should overwrite this
364          * method to implement own equality checks
365          *
366          * @param       $objectInstance         An instance of a FrameworkInterface object
367          * @return      $equals                         Whether both objects equals
368          */
369         public function equals (FrameworkInterface $objectInstance) {
370                 // Now test it
371                 $equals = ((
372                         $this->__toString() == $objectInstance->__toString()
373                 ) && (
374                         $this->hashCode() == $objectInstance->hashCode()
375                 ));
376
377                 // Return the result
378                 return $equals;
379         }
380 }
381
382 // [EOF]
383 ?>