6bfdfbf7c1efab379a9cb45a1c0a2bd9e4d0b6ad
[shipsimu.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)
6  * in the 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, this is free software
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 $cfgInstance = 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          * "Create" a configuration instance
56          *
57          * @param       $enableDebug    Wether enable debug mode (default: off)
58          * @return      $cfgInstance    An instance of this configuration class
59          */
60         public final static function createFrameworkConfiguration ($enableDebug = false) {
61                 /**
62                  * For singleton design pattern because we only need a one-time-run
63                  * through the initial configuration.
64                  */
65                 if (is_null(self::$cfgInstance))  {
66                         // CFG: ERROR-REPORTING
67                         @error_reporting(E_ALL | E_STRICT);
68
69                         /**
70                          * Shall we enable the debug mode?
71                          */
72                         if ($enableDebug) {
73                                 define('DEBUG_MODE', true);
74                         }
75
76                         /**
77                          * Crate a config instance
78                          */
79                         self::$cfgInstance = new FrameworkConfiguration();
80                 }
81
82                 /**
83                  * Return the instance
84                  */
85                 return self::$cfgInstance;
86         }
87
88         /**
89          * Getter for an instance of this class
90          *
91          * @return      $cfgInstance    An instance of this class
92          */
93         public final static function getInstance () {
94                 return self::$cfgInstance;
95         }
96
97         /**
98          * Setter for default time zone (must be correct!)
99          *
100          * @param               $zone   The time-zone string (e.g. Europe/Berlin)
101          * @return      void
102          */
103         public final function setDefaultTimezone ($zone) {
104                 // At least 5.1.0 is required for this!
105                 if (version_compare(phpversion(), "5.1.0")) {
106                         @date_default_timezone_set($zone);
107                 } // END - if
108         }
109
110         /**
111          * Setter for runtime magic quotes
112          */
113         public final function setMagicQuotesRuntime ($enableQuotes) {
114                 // Cast it to boolean
115                 $enableQuotes = (boolean) $enableQuotes;
116
117                 // Set it
118                 @set_magic_quotes_runtime($enableQuotes);
119         }
120
121         /**
122          * A private include loader
123          *
124          * @param       $arrayObject    The array object with all include files
125          * @return      void
126          */
127         private function loadIncludes (ArrayObject $arrayObject) {
128                 // Load only if there are includes defined
129                 if (!is_null($arrayObject)) {
130                         for ($idx = $arrayObject->getIterator(); $idx->valid(); $idx->next()) {
131                                 // Get include file
132                                 $inc = $idx->current();
133
134                                 // Is the file name really set?
135                                 if (!empty($inc)) {
136                                         // Base path is by default added
137                                         $fqfn = $inc;
138
139                                         // Base path added? (Uni* / Windows)
140                                         if ((substr($inc, 0, 1) != "/") && (substr($inc, 1, 1) != ":")) {
141                                                 // Generate FQFN
142                                                 $fqfn = sprintf("%s/inc/extra/%s", PATH, $inc);
143                                         } // END - if
144                                 } // END - if
145
146                                 // Include them all here
147                                 require($fqfn);
148                         }
149                 } // END - if
150         }
151
152         /**
153          * Define the database type which must be valid and will not be verified.
154          *
155          * @param               $type   The database type. See path inc/database/.
156          * @return      void
157          */
158         public function defineDatabaseType ($type) {
159                 // Is it defined or not?
160                 if (defined('_DB_TYPE')) {
161                         // Already defined! But we cannot throw an exception here... :(
162                         ApplicationEntryPoint::app_die(sprintf("[%s:] Please define the database type only once in your application!",
163                                 __CLASS__
164                         ));
165                 }
166
167                 // Set the constant
168                 define('_DB_TYPE', (string) $type);
169         }
170
171         /**
172          * Define the local file path
173          *
174          * @param               $path   Local file path for include files.
175          * @return      void
176          */
177         public function definePath ($path) {
178                 // Cast to string
179                 $path = (string) $path;
180
181                 // Replace backslashes with slashes
182                 $path = str_replace("\\", "/", $path);
183
184                 // Is it defined or not?
185                 if ((!is_dir($path)) || (!is_readable($path))) {
186                         // Is not a valid path
187                         ApplicationEntryPoint::app_die(sprintf("[%s:] Invalid path (not found) specified. Please make sure it is created.",
188                                 __CLASS__
189                         ));
190                 } elseif (defined('PATH')) {
191                         // Already defined! But we cannot throw an exception here... :(
192                         ApplicationEntryPoint::app_die(sprintf("[%s:] Please define the local file path only once in your application.",
193                                 __CLASS__
194                         ));
195                 }
196
197                 // Define path here
198                 define('PATH', $path);
199         }
200
201         /**
202          * Read a configuration element.
203          *
204          * @param               $cfgEntry       The configuration element
205          * @return      $cfgValue       The fetched configuration value
206          * @throws      ConfigEntryIsEmptyException     If $cfgEntry is empty
207          * @throws      ConfigEntryNotFoundException    If a configuration element
208          *                                                                      was not found
209          */
210         public function readConfig ($cfgEntry) {
211                 // Cast to string
212                 $cfgEntry = (string) $cfgEntry;
213
214                 // Is a valid configuration entry provided?
215                 if (empty($cfgEntry)) {
216                         // Entry is empty
217                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_ENTRY_IS_EMPTY);
218                 } elseif (!isset($this->config[$cfgEntry])) {
219                         // Entry was not found!
220                         throw new ConfigEntryNotFoundException(array(__CLASS__, $cfgEntry), self::EXCEPTION_CONFIG_ENTRY_WAS_NOT_FOUND);
221                 }
222
223                 // Debug message
224                 if ((defined('DEBUG_CONFIG')) || (defined('DEBUG_ALL'))) {
225                         echo "[".__METHOD__."] Configuration entry ".$cfgEntry." requested.<br />\n";
226                 } // END - if
227
228                 // Return the requested value
229                 return $this->config[$cfgEntry];
230         }
231
232         /**
233          * Set a configuration entry.
234          *
235          * @param               $cfgEntry       The configuration entry we want to add/change
236          * @param               $cfgValue       The configuration value we want to set
237          * @return      void
238          * @throws      ConfigEntryIsEmptyException     If $cfgEntry is empty
239          */
240         public final function setConfigEntry ($cfgEntry, $cfgValue) {
241                 // Cast to string
242                 $cfgEntry = (string) $cfgEntry;
243                 $cfgValue = (string) $cfgValue;
244
245                 // Is a valid configuration entry provided?
246                 if (empty($cfgEntry)) {
247                         // Entry is empty
248                         throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_ENTRY_IS_EMPTY);
249                 } // END - if
250
251                 // Set the configuration value
252                 $this->config[$cfgEntry] = $cfgValue;
253
254                 // Resort the array
255                 ksort($this->config);
256         }
257
258         /**
259          * Compatiblity method to return this class' name
260          *
261          * @return      __CLASS__               This class' name
262          */
263         public function __toString () {
264                 return get_class($this);
265         }
266
267         /**
268          * Dectect and return the base URL for all URLs and forms
269          *
270          * @return      $baseUrl        Detected base URL
271          */
272         public function detectBaseUrl() {
273                 // Initialize the URL
274                 $baseUrl = "http";
275
276                 // Do we have HTTPS?
277                 if (isset($_SERVER['HTTPS'])) {
278                         // Add the >s< for HTTPS
279                         $baseUrl .= "s";
280                 } // END - if
281
282                 // Construct the full URL now and secure it against CSRF attacks
283                 $baseUrl = $baseUrl . "://" . $this->detectDomain() . dirname($_SERVER['SCRIPT_NAME']);
284
285                 // Return the URL
286                 return $baseUrl;
287         }
288
289         /**
290          * Detect safely and return the full domain where this script is installed
291          *
292          * @return      $fullDomain             The detected full domain
293          */
294         public function detectDomain () {
295                 // Full domain is localnet.invalid by default
296                 $fullDomain = "localnet.invalid";
297
298                 // Is the server name there?
299                 if (isset($_SERVER['SERVER_NAME'])) {
300                         // Detect the full domain
301                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
302                 } // END - if
303
304                 // Return it
305                 return $fullDomain;
306         }
307
308         /**
309          * Getter for field name
310          *
311          * @param       $fieldName              Field name which we shall get
312          * @return      $fieldValue             Field value from the user
313          */
314         function getField ($fieldName) {
315                 // Dummy method!
316         }
317
318         /**
319          * Updates a given field with new value
320          *
321          * @param       $fieldName              Field to update
322          * @param       $fieldValue             New value to store
323          * @return      void
324          */
325         public function updateDatabaseField ($fieldName, $fieldValue) {
326                 // Dummy method!
327         }
328 }
329
330 // [EOF]
331 ?>