renamed deprecated exception name to a more common one
[core.git] / index.php
1 <?php
2 // Own namespace (watch out: core)
3 namespace CoreFramework\EntryPoint;
4
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Helper\Application\ApplicationHelper;
9 use CoreFramework\Localization\LanguageSystem;
10 use CoreFramework\Loader\ClassLoader;
11 use CoreFramework\Generic\FrameworkException;
12
13 /**
14  * The main class with the entry point to the whole application. This class
15  * "emulates" Java's entry point call. Additionally it covers local
16  * variables from outside access to prevent possible attacks on uninitialized
17  * local variables.
18  *
19  * But good little boys and girls would always initialize their variables... ;-)
20  *
21  * @author              Roland Haeder <webmaster@shipsimu.org>
22  * @version             0.0.0
23  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
24  * @license             GNU GPL 3.0 or any newer version
25  * @link                http://www.shipsimu.org
26  *
27  * This program is free software: you can redistribute it and/or modify
28  * it under the terms of the GNU General Public License as published by
29  * the Free Software Foundation, either version 3 of the License, or
30  * (at your option) any later version.
31  *
32  * This program is distributed in the hope that it will be useful,
33  * but WITHOUT ANY WARRANTY; without even the implied warranty of
34  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35  * GNU General Public License for more details.
36  *
37  * You should have received a copy of the GNU General Public License
38  * along with this program. If not, see <http://www.gnu.org/licenses/>.
39  */
40 final class ApplicationEntryPoint {
41         /**
42          * Core path
43          */
44         private static $corePath = '';
45
46         /**
47          * The application's emergency exit
48          *
49          * @param       $message                The optional message we shall output on exit
50          * @param       $code                   Error code from exception
51          * @param       $extraData              Extra information from exceptions
52          * @param       $silentMode             Whether silent mode is turned on
53          * @return      void
54          * @todo        This method is old code and needs heavy rewrite and should be moved to ApplicationHelper
55          */
56         public static final function app_exit ($message = '', $code = FALSE, $extraData = '', $silentMode = FALSE) {
57                 // Is this method already called?
58                 if (isset($GLOBALS['app_die_called'])) {
59                         // Then output the text directly
60                         exit($message);
61                 } // END - if
62
63                 // This method shall not be called twice
64                 $GLOBALS['app_die_called'] = TRUE;
65
66                 // Is a message set?
67                 if (empty($message)) {
68                         // No message provided
69                         $message = 'No message provided.';
70                 } // END - if
71
72                 // Get config instance
73                 $configInstance = FrameworkConfiguration::getSelfInstance();
74
75                 // Do we have debug installation?
76                 if (($configInstance->getConfigEntry('product_install_mode') == 'productive') || ($silentMode === TRUE)) {
77                         // Abort here
78                         exit();
79                 } // END - if
80
81                 // Get some instances
82                 $tpl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('html_template_class');
83                 $languageInstance = LanguageSystem::getSelfInstance();
84
85                 // Initialize template instance here to avoid warnings in IDE
86                 $templateInstance = NULL;
87
88                 // Get response instance
89                 $responseInstance = ApplicationHelper::getSelfInstance()->getResponseInstance();
90
91                 // Is the template engine loaded?
92                 if ((class_exists($tpl)) && (is_object($languageInstance))) {
93                         // Use the template engine for putting out (nicer look) the message
94                         try {
95                                 // Get the template instance from our object factory
96                                 $templateInstance = ObjectFactory::createObjectByName($tpl);
97                         } catch (FrameworkException $e) {
98                                 exit(sprintf("[Main:] Could not initialize template engine for reason: <span class=\"exception_reason\">%s</span>",
99                                         $e->getMessage()
100                                 ));
101                         }
102
103                         // Get and prepare backtrace for output
104                         $backtraceArray = debug_backtrace();
105                         $backtrace = '';
106                         foreach ($backtraceArray as $key => $trace) {
107                                 // Set missing array elements
108                                 if (!isset($trace['file'])) {
109                                         $trace['file'] = __FILE__;
110                                 } // END - if
111                                 if (!isset($trace['line'])) {
112                                         $trace['line'] = __LINE__;
113                                 } // END - if
114                                 if (!isset($trace['args'])) {
115                                         $trace['args'] = array();
116                                 } // END - if
117
118                                 // Add the traceback path to the final output
119                                 $backtrace .= sprintf("<span class=\"backtrace_file\">%s</span>:%d, <span class=\"backtrace_function\">%s(%d)</span><br />\n",
120                                         basename($trace['file']),
121                                         $trace['line'],
122                                         $trace['function'],
123                                         count($trace['args'])
124                                 );
125                         } // END - foreach
126
127                         // Init application instance
128                         $applicationInstance = NULL;
129
130                         // Is the class there?
131                         if (class_exists('CoreFramework\Helper\Application\ApplicationHelper')) {
132                                 // Get application instance
133                                 $applicationInstance = ApplicationHelper::getSelfInstance();
134
135                                 // Assign application data
136                                 $templateInstance->assignApplicationData($applicationInstance);
137                         } // END - if
138
139                         // We only try this
140                         try {
141                                 // Assign variables
142                                 $templateInstance->assignVariable('message', $message);
143                                 $templateInstance->assignVariable('code', $code);
144                                 $templateInstance->assignVariable('extra', $extraData);
145                                 $templateInstance->assignVariable('backtrace', $backtrace);
146                                 $templateInstance->assignVariable('total_includes', ClassLoader::getSelfInstance()->getTotal());
147                                 $templateInstance->assignVariable('total_objects', ObjectFactory::getTotal());
148                                 $templateInstance->assignVariable('title', $languageInstance->getMessage('emergency_exit_title'));
149
150                                 // Load the template
151                                 $templateInstance->loadCodeTemplate('emergency_exit');
152
153                                 // Compile the template
154                                 $templateInstance->compileTemplate();
155
156                                 // Compile all variables
157                                 $templateInstance->compileVariables();
158
159                                 // Transfer data to response
160                                 $templateInstance->transferToResponse($responseInstance);
161
162                                 // Flush the response
163                                 $responseInstance->flushBuffer();
164                         } catch (FileNotFoundException $e) {
165                                 // Even the template 'emergency_exit' wasn't found so output both message
166                                 exit($message . ', exception: ' . $e->getMessage());
167                         }
168
169                         // Good bye...
170                         exit();
171                 } else {
172                         // Output message and die
173                         exit(sprintf('[Main:] Emergency exit reached: <span class="emergency_span">%s</span>',
174                                 $message
175                         ));
176                 }
177         }
178
179         /**
180          * Determines the correct absolute path for all includes only once per run.
181          * Other calls of this method are being "cached". This is done by checking
182          * a small list of common paths where the framework can reside and check if
183          * framework/config.php can be found.
184          *
185          * @return      $corePath       Base path (core) for all includes
186          */
187         protected static final function detectCorePath () {
188                 // Is it not set?
189                 if (empty(self::$corePath)) {
190                         // Auto-detect core path (first application-common)
191                         foreach (array('core', '.') as $possiblePath) {
192                                 // Create full path for testing
193                                 $realPath = realpath($possiblePath);
194
195                                 // Debug message
196                                 //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
197
198                                 // Is it FALSE?
199                                 if ($realPath === FALSE) {
200                                         // Then, not found.
201                                         continue;
202                                 } // END - if
203
204                                 // First create full-qualified file name (FQFN) to framework/config.php
205                                 $fqfn = sprintf(
206                                         '%s%sframework%sconfig.php',
207                                         $realPath,
208                                         DIRECTORY_SEPARATOR,
209                                         DIRECTORY_SEPARATOR,
210                                         $possiblePath
211                                 );
212
213                                 // Debug message
214                                 //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
215
216                                 // Is it readable?
217                                 if (is_readable($fqfn)) {
218                                         // Found one
219                                         self::$corePath = $realPath;
220
221                                         // Abort here
222                                         break;
223                                 } // END - if
224                         } // END - foreach
225                 } // END - if
226
227                 // Return it
228                 return self::$corePath;
229         }
230
231         /**
232          * The framework's main entry point. This class isolates some local
233          * variables which shall not become visible to outside because of security
234          * concerns. This is done here to "emulate" the well-known entry point in
235          * Java.
236          *
237          * @return      void
238          */
239         public static final function main () {
240                 // Load config file, this no longer provides $cfg
241                 require(self::detectCorePath() . '/framework/config.php');
242
243                 // Get a new configuration instance
244                 $cfg = FrameworkConfiguration::getSelfInstance();
245
246                 // Load bootstrap class
247                 require($cfg->getConfigEntry('base_path') . 'framework/bootstrap/class_BootstrapFramework.php');
248
249                 // ----- Below is deprecated -----
250
251                 // Load all include files
252                 require($cfg->getConfigEntry('base_path') . 'framework/includes.php');
253
254                 // Include the application selector
255                 require($cfg->getConfigEntry('base_path') . 'framework/selector.php');
256         }
257 }
258
259 // Developer mode active? Comment out if no dev!
260 define('DEVELOPER', TRUE);
261
262 // Log all exceptions (only debug! This option can create large error logs)
263 //define('LOG_EXCEPTIONS', TRUE);
264
265 //xdebug_start_trace();
266
267 // Call above main() method
268 ApplicationEntryPoint::main();