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