Imported HelpableTemplate
[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\Helper\Application\ApplicationHelper;
10 use CoreFramework\Localization\LanguageSystem;
11 use CoreFramework\Loader\ClassLoader;
12 use 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 - 2015 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 app_exit ($message = '', $code = false, $extraData = '', $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                 } // END - if
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                 } // END - if
75
76                 // Get config instance
77                 $configInstance = FrameworkConfiguration::getSelfInstance();
78
79                 // Do we have debug installation?
80                 if (($configInstance->getConfigEntry('product_install_mode') == 'productive') || ($silentMode === true)) {
81                         // Abort here
82                         exit();
83                 } // END - if
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 = ApplicationHelper::getSelfInstance()->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                         $backtraceArray = debug_backtrace();
109                         $backtrace = '';
110                         foreach ($backtraceArray as $key => $trace) {
111                                 // Set missing array elements
112                                 if (!isset($trace['file'])) {
113                                         $trace['file'] = __FILE__;
114                                 } // END - if
115                                 if (!isset($trace['line'])) {
116                                         $trace['line'] = __LINE__;
117                                 } // END - if
118                                 if (!isset($trace['args'])) {
119                                         $trace['args'] = array();
120                                 } // END - if
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                         } // END - foreach
130
131                         // Init application instance
132                         $applicationInstance = NULL;
133
134                         // Is the class there?
135                         if (class_exists('CoreFramework\Helper\Application\ApplicationHelper')) {
136                                 // Get application instance
137                                 $applicationInstance = ApplicationHelper::getSelfInstance();
138
139                                 // Assign application data
140                                 $templateInstance->assignApplicationData($applicationInstance);
141                         } // END - if
142
143                         // We only try this
144                         try {
145                                 // Assign variables
146                                 $templateInstance->assignVariable('message', $message);
147                                 $templateInstance->assignVariable('code', $code);
148                                 $templateInstance->assignVariable('extra', $extraData);
149                                 $templateInstance->assignVariable('backtrace', $backtrace);
150                                 $templateInstance->assignVariable('total_includes', ClassLoader::getSelfInstance()->getTotal());
151                                 $templateInstance->assignVariable('total_objects', ObjectFactory::getTotal());
152                                 $templateInstance->assignVariable('title', $languageInstance->getMessage('emergency_exit_title'));
153
154                                 // Load the template
155                                 $templateInstance->loadCodeTemplate('emergency_exit');
156
157                                 // Compile the template
158                                 $templateInstance->compileTemplate();
159
160                                 // Compile all variables
161                                 $templateInstance->compileVariables();
162
163                                 // Transfer data to response
164                                 $templateInstance->transferToResponse($responseInstance);
165
166                                 // Flush the response
167                                 $responseInstance->flushBuffer();
168                         } catch (FileNotFoundException $e) {
169                                 // Even the template 'emergency_exit' wasn't found so output both message
170                                 exit($message . ', exception: ' . $e->getMessage());
171                         }
172
173                         // Good bye...
174                         exit();
175                 } else {
176                         // Output message and die
177                         exit(sprintf('[Main:] Emergency exit reached: <span class="emergency_span">%s</span>',
178                                 $message
179                         ));
180                 }
181         }
182
183         /**
184          * Determines the correct absolute path for the framework. A set of common
185          * paths is being tested (first most common for applications, second when
186          * core tests are being executed and third/forth if the framework has been
187          * cloned there).
188          *
189          * @return      $frameworkPath  Path for framework
190          */
191         public static final function detectFrameworkPath () {
192                 // Is it not set?
193                 if (empty(self::$frameworkPath)) {
194                         // Auto-detect core path (first application-common)
195                         foreach (array('core', '.', '/usr/local/share/php/core', '/usr/share/php/core') as $possiblePath) {
196                                 // Create full path for testing
197                                 $realPath = realpath($possiblePath);
198
199                                 // Debug message
200                                 //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
201
202                                 // Is it false?
203                                 if ($realPath === false) {
204                                         // Then, not found.
205                                         continue;
206                                 } // END - if
207
208                                 // First create full-qualified file name (FQFN) to framework/config-global.php
209                                 $fqfn = sprintf(
210                                         '%s%sframework%sconfig-global.php',
211                                         $realPath,
212                                         DIRECTORY_SEPARATOR,
213                                         DIRECTORY_SEPARATOR,
214                                         $possiblePath
215                                 );
216
217                                 // Debug message
218                                 //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
219
220                                 // Is it readable?
221                                 if (is_readable($fqfn)) {
222                                         // Found one
223                                         self::$frameworkPath = $realPath . '/framework/';
224
225                                         // Abort here
226                                         break;
227                                 } // END - if
228                         } // END - foreach
229
230                         // Able to find?
231                         if (!is_dir(self::$frameworkPath)) {
232                                 // Is no directory
233                                 throw new Exception('Cannot find framework.');
234                         } // END - if
235                 } // END - if
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 // Developer mode active? Comment out if no dev!
281 define('DEVELOPER', true);
282
283 // Log all exceptions (only debug! This option can create large error logs)
284 //define('LOG_EXCEPTIONS', true);
285
286 //xdebug_start_trace();
287
288 // Call above main() method
289 ApplicationEntryPoint::main();