]> git.mxchange.org Git - shipsimu.git/blob - index.php
Continued:
[shipsimu.git] / index.php
1 <?php
2 // Own namespace (watch out: core)
3 namespace Org\Mxchange\CoreFramework\EntryPoint;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
9 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
10 use Org\Mxchange\CoreFramework\Localization\LanguageSystem;
11 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
12 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
13 use Org\Mxchange\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 - 2021 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 (string $message = '', int $code = -1, string $extraData = '', bool $silentMode = false) {
62                 // Is this method already called?
63                 //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,code=%d,extraData=%s,silentMode=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, $code, $extraData, intval($silentMode));
64                 if (isset($GLOBALS['app_die_called'])) {
65                         // Then output the text directly
66                         print $message . PHP_EOL;
67                         exit(255);
68                 }
69
70                 // This method shall not be called twice
71                 $GLOBALS['app_die_called'] = true;
72
73                 // Is a message set?
74                 if (empty($message)) {
75                         // No message provided
76                         $message = 'No message provided.';
77                 }
78
79                 // Get config instance
80                 $configInstance = FrameworkBootstrap::getConfigurationInstance();
81
82                 // Do we have debug installation?
83                 if (($configInstance->getConfigEntry('product_install_mode') == 'productive') || ($silentMode === true)) {
84                         // Abort here
85                         //* NOISY-DEBUG: */ printf('[%s:%d]: product_install_mode=%d,silentMode=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $configInstance->getConfigEntry('product_install_mode'), intval($silentMode));
86                         exit(255);
87                 }
88
89                 // Get some instances
90                 $templateClassName = $configInstance->getConfigEntry('html_template_class');
91                 $languageInstance = LanguageSystem::getSelfInstance();
92
93                 // Initialize template instance here to avoid warnings in IDE
94                 $templateInstance = NULL;
95
96                 // Get response instance
97                 $responseInstance = FrameworkBootstrap::getResponseInstance();
98
99                 // Is the template engine loaded?
100                 if ((class_exists($templateClassName)) && ($languageInstance instanceof ManageableLanguage)) {
101                         // Use the template engine for putting out (nicer look) the message
102                         try {
103                                 // Get the template instance from our object factory
104                                 $templateInstance = ObjectFactory::createObjectByName($templateClassName);
105                         } catch (FrameworkException $e) {
106                                 exit(sprintf('[Main:] Could not initialize template engine for reason: <span class="exception_reason">%s</span>',
107                                         $e->getMessage()
108                                 ));
109                         }
110
111                         // Get and prepare backtrace for output
112                         $backtrace = '';
113                         foreach (debug_backtrace() as $key => $trace) {
114                                 // Set missing array elements
115                                 if (!isset($trace['file'])) {
116                                         $trace['file'] = __FILE__;
117                                 }
118                                 if (!isset($trace['line'])) {
119                                         $trace['line'] = __LINE__;
120                                 }
121                                 if (!isset($trace['args'])) {
122                                         $trace['args'] = array();
123                                 }
124
125                                 // Add the traceback path to the final output
126                                 $backtrace .= sprintf('<span class="backtrace_file">%s</span>:%d, <span class="backtrace_function">%s(%d)</span><br />' . PHP_EOL,
127                                         basename($trace['file']),
128                                         $trace['line'],
129                                         $trace['function'],
130                                         count($trace['args'])
131                                 );
132                         }
133
134                         // Init application instance
135                         $applicationInstance = NULL;
136
137                         /*
138                          * The following class may NOT be loaded at all times. For example,
139                          * it might be the (rare) case that an error has happened BEFORE
140                          * that class had been loaded and cannot be loaded or else an
141                          * infinte loop in invoking this method will take place resulting in
142                          * a stack-overflow error.
143                          */
144                         if (class_exists('Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper')) {
145                                 // Get application instance
146                                 $applicationInstance = ApplicationHelper::getSelfInstance();
147
148                                 // Assign application data
149                                 $templateInstance->assignApplicationData();
150                         }
151
152                         // We only try this
153                         try {
154                                 // Assign variables
155                                 $templateInstance->assignVariable('message'       , $message);
156                                 $templateInstance->assignVariable('code'          , $code);
157                                 $templateInstance->assignVariable('extra'         , $extraData);
158                                 $templateInstance->assignVariable('backtrace'     , $backtrace);
159                                 $templateInstance->assignVariable('total_includes', ClassLoader::getSelfInstance()->getTotal());
160                                 $templateInstance->assignVariable('total_objects' , ObjectFactory::getTotal());
161                                 $templateInstance->assignVariable('title'         , $languageInstance->getMessage('emergency_exit_title'));
162
163                                 // Load the template
164                                 $templateInstance->loadCodeTemplate('emergency_exit');
165
166                                 // Compile the template
167                                 $templateInstance->compileTemplate();
168
169                                 // Compile all variables
170                                 $templateInstance->compileVariables();
171
172                                 // Transfer data to response
173                                 $templateInstance->transferToResponse($responseInstance);
174
175                                 // Flush the response
176                                 $responseInstance->flushBuffer();
177                         } catch (FileNotFoundException $e) {
178                                 // Even the template 'emergency_exit' wasn't found so output both message
179                                 print ($message . ', exception: ' . $e->getMessage() . PHP_EOL);
180                                 exit($e->getCode());
181                         }
182
183                         // Good bye...
184                         exit(255);
185                 } else {
186                         // Output message and die
187                         printf('[Main:] Emergency exit reached: <span class="emergency_span">%s</span>', $message);
188                         exit(255);
189                 }
190
191                 // Trace message
192                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
193         }
194
195         /**
196          * Determines the correct absolute path for the framework. A set of common
197          * paths is being tested (first most common for applications, second when
198          * core tests are being executed and third/forth if the framework has been
199          * cloned there).
200          *
201          * @return      $frameworkPath  Path for framework
202          */
203         public static final function detectFrameworkPath () {
204                 // Is it not set?
205                 //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
206                 if (empty(self::$frameworkPath)) {
207                         // Auto-detect core path (first application-common)
208                         foreach (['core', self::getRootPath(), '/usr/local/share/php/core', '/usr/share/php/core'] as $possiblePath) {
209                                 // Create full path for testing
210                                 //* NOISY-DEBUG: */ printf('[%s:%d]: possiblePath=%s' . PHP_EOL, __METHOD__, __LINE__, $possiblePath);
211                                 $realPath = realpath($possiblePath);
212
213                                 // Is it false?
214                                 //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
215                                 if ($realPath === false) {
216                                         // Then, not found.
217                                         //* NOISY-DEBUG: */ printf('[%s:%d]: possiblePath=%s was not found. - SKIPPED!' . PHP_EOL, __METHOD__, __LINE__, $possiblePath);
218                                         continue;
219                                 }
220
221                                 // Append framework path
222                                 $frameworkPath = sprintf('%s%sframework%s', $realPath, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
223
224                                 // First create full-qualified file name (FQFN) to framework/config-global.php
225                                 //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkPath=%s' . PHP_EOL, __METHOD__, __LINE__, $frameworkPath);
226                                 $configFile = $frameworkPath . 'config-global.php';
227
228                                 // Is it readable?
229                                 //* NOISY-DEBUG: */ printf('[%s:%d]: configFile=%s' . PHP_EOL, __METHOD__, __LINE__, $configFile);
230                                 if (is_readable($configFile)) {
231                                         // Found one
232                                         self::$frameworkPath = $frameworkPath;
233
234                                         // Abort here
235                                         //* NOISY-DEBUG: */ printf('[%s:%d]: Setting self::frameworkPath=%s - BREAK!' . PHP_EOL, __METHOD__, __LINE__, $frameworkPath);
236                                         break;
237                                 }
238                         }
239
240                         // Able to find?
241                         //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - Checking ...' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
242                         if (!is_dir(self::$frameworkPath)) {
243                                 // Is no directory
244                                 throw new Exception('Cannot find framework.');
245                         }
246                 }
247
248                 // Return it
249                 //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
250                 return self::$frameworkPath;
251         }
252
253         /**
254          * Getter for root path
255          *
256          * @return      $rootPath       Root path
257          */
258         public static function getRootPath () {
259                 // Get __DIR__, really simple and no detection
260                 return __DIR__;
261         }
262
263         /**
264          * The framework's main entry point. This class isolates some local
265          * variables which shall not become visible to outside because of security
266          * concerns. This is done here to "emulate" the well-known entry point in
267          * Java.
268          *
269          * @return      void
270          */
271         public static final function main () {
272                 // Load bootstrap file
273                 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
274                 require sprintf('%sbootstrap%sbootstrap.inc.php', self::detectFrameworkPath(), DIRECTORY_SEPARATOR);
275
276                 /*
277                  * Initial bootstrap is done, continue with initialization of
278                  * framework.
279                  */
280                 FrameworkBootstrap::initFramework();
281
282                 // Next initialize the detected application
283                 FrameworkBootstrap::prepareApplication();
284
285                 /*
286                  * Last step is to start the application, this will also initialize and
287                  * register the application instance in registry.
288                  */
289                 FrameworkBootstrap::startApplication();
290
291                 // Trace message
292                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
293         }
294 }
295
296 // Log all exceptions (only debug! This option can create large error logs)
297 //define('LOG_EXCEPTIONS', true);
298
299 // Call above main() method
300 ApplicationEntryPoint::main();