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