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