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\Loader\ClassLoader;
12 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
13
14 // Import SPL stuff
15 use \Exception;
16
17 /**
18  * The main class with the entry point to the whole application. This class
19  * "emulates" Java's entry point call. Additionally it covers local
20  * variables from outside access to prevent possible attacks on uninitialized
21  * local variables.
22  *
23  * But good little boys and girls would always initialize their variables... ;-)
24  *
25  * @author              Roland Haeder <webmaster@shipsimu.org>
26  * @version             0.0.0
27  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
28  * @license             GNU GPL 3.0 or any newer version
29  * @link                http://www.shipsimu.org
30  *
31  * This program is free software: you can redistribute it and/or modify
32  * it under the terms of the GNU General Public License as published by
33  * the Free Software Foundation, either version 3 of the License, or
34  * (at your option) any later version.
35  *
36  * This program is distributed in the hope that it will be useful,
37  * but WITHOUT ANY WARRANTY; without even the implied warranty of
38  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
39  * GNU General Public License for more details.
40  *
41  * You should have received a copy of the GNU General Public License
42  * along with this program. If not, see <http://www.gnu.org/licenses/>.
43  */
44 final class ApplicationEntryPoint {
45         /**
46          * Framework path
47          */
48         private static $frameworkPath = '';
49
50         /**
51          * The application's emergency exit
52          *
53          * @param       $message                The optional message we shall output on exit
54          * @param       $code                   Error code from exception
55          * @param       $extraData              Extra information from exceptions
56          * @param       $silentMode             Whether silent mode is turned on
57          * @return      void
58          * @todo        This method is old code and needs heavy rewrite and should be moved to ApplicationHelper
59          */
60         public static final function exitApplication (string $message = '', int $code = -1, string $extraData = '', bool $silentMode = false) {
61                 // Is this method already called?
62                 if (isset($GLOBALS['app_die_called'])) {
63                         // Then output the text directly
64                         exit($message);
65                 }
66
67                 // This method shall not be called twice
68                 $GLOBALS['app_die_called'] = true;
69
70                 // Is a message set?
71                 if (empty($message)) {
72                         // No message provided
73                         $message = 'No message provided.';
74                 }
75
76                 // Get config instance
77                 $configInstance = FrameworkBootstrap::getConfigurationInstance();
78
79                 // Do we have debug installation?
80                 if (($configInstance->getConfigEntry('product_install_mode') == 'productive') || ($silentMode === true)) {
81                         // Abort here
82                         exit;
83                 }
84
85                 // Get some instances
86                 $tpl = $configInstance->getConfigEntry('html_template_class');
87                 $languageInstance = LanguageSystem::getSelfInstance();
88
89                 // Initialize template instance here to avoid warnings in IDE
90                 $templateInstance = NULL;
91
92                 // Get response instance
93                 $responseInstance = FrameworkBootstrap::getResponseInstance();
94
95                 // Is the template engine loaded?
96                 if ((class_exists($tpl)) && (is_object($languageInstance))) {
97                         // Use the template engine for putting out (nicer look) the message
98                         try {
99                                 // Get the template instance from our object factory
100                                 $templateInstance = ObjectFactory::createObjectByName($tpl);
101                         } catch (FrameworkException $e) {
102                                 exit(sprintf('[Main:] Could not initialize template engine for reason: <span class="exception_reason">%s</span>',
103                                         $e->getMessage()
104                                 ));
105                         }
106
107                         // Get and prepare backtrace for output
108                         $backtrace = '';
109                         foreach (debug_backtrace() as $key => $trace) {
110                                 // Set missing array elements
111                                 if (!isset($trace['file'])) {
112                                         $trace['file'] = __FILE__;
113                                 }
114                                 if (!isset($trace['line'])) {
115                                         $trace['line'] = __LINE__;
116                                 }
117                                 if (!isset($trace['args'])) {
118                                         $trace['args'] = array();
119                                 }
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 />' . PHP_EOL,
123                                         basename($trace['file']),
124                                         $trace['line'],
125                                         $trace['function'],
126                                         count($trace['args'])
127                                 );
128                         }
129
130                         // Init application instance
131                         $applicationInstance = NULL;
132
133                         // Is the class there?
134                         if (class_exists('Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper')) {
135                                 // Get application instance
136                                 $applicationInstance = ApplicationHelper::getSelfInstance();
137
138                                 // Assign application data
139                                 $templateInstance->assignApplicationData();
140                         }
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                         die(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', __DIR__, '/usr/local/share/php/core', '/usr/share/php/core') as $possiblePath) {
195                                 // Create full path for testing
196                                 $realPath = realpath($possiblePath);
197
198                                 // Is it false?
199                                 //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
200                                 if ($realPath === false) {
201                                         // Then, not found.
202                                         continue;
203                                 }
204
205                                 // Append framework path
206                                 $frameworkPath = sprintf('%s%sframework%s', $realPath, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
207
208                                 // First create full-qualified file name (FQFN) to framework/config-global.php
209                                 $configFile = $frameworkPath . 'config-global.php';
210
211                                 // Is it readable?
212                                 //* NOISY-DEBUG: */ printf('[%s:%d]: configFile=%s' . PHP_EOL, __METHOD__, __LINE__, $configFile);
213                                 if (is_readable($configFile)) {
214                                         // Found one
215                                         self::$frameworkPath = $frameworkPath;
216
217                                         // Abort here
218                                         break;
219                                 }
220                         }
221
222                         // Able to find?
223                         if (!is_dir(self::$frameworkPath)) {
224                                 // Is no directory
225                                 throw new Exception('Cannot find framework.');
226                         }
227                 }
228
229                 // Return it
230                 return self::$frameworkPath;
231         }
232
233         /**
234          * Getter for root path
235          *
236          * @return      $rootPath       Root path
237          */
238         public static function getRootPath () {
239                 // Get __DIR__, really simple and no detection
240                 return __DIR__;
241         }
242
243         /**
244          * The framework's main entry point. This class isolates some local
245          * variables which shall not become visible to outside because of security
246          * concerns. This is done here to "emulate" the well-known entry point in
247          * Java.
248          *
249          * @return      void
250          */
251         public static final function main () {
252                 // Load bootstrap file
253                 require sprintf('%sbootstrap%sbootstrap.inc.php', self::detectFrameworkPath(), DIRECTORY_SEPARATOR);
254
255                 /*
256                  * Initial bootstrap is done, continue with initialization of
257                  * framework.
258                  */
259                 FrameworkBootstrap::initFramework();
260
261                 // Next initialize the detected application
262                 FrameworkBootstrap::prepareApplication();
263
264                 /*
265                  * Last step is to start the application, this will also initialize and
266                  * register the application instance in registry.
267                  */
268                 FrameworkBootstrap::startApplication();
269         }
270 }
271
272 // Log all exceptions (only debug! This option can create large error logs)
273 //define('LOG_EXCEPTIONS', true);
274
275 //xdebug_start_trace();
276
277 // Call above main() method
278 ApplicationEntryPoint::main();