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