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