Continued:
[shipsimu.git] / index.php
index 658d70ade8c82ceeeec99f9df1041907a4a23fa4..37fa261279410afe592905650fe6afaa2af5454c 100644 (file)
--- a/index.php
+++ b/index.php
@@ -1,21 +1,33 @@
 <?php
-// Developer mode active? Comment out if no dev!
-//define('DEVELOPER', true);
+// Own namespace (watch out: core)
+namespace Org\Mxchange\CoreFramework\EntryPoint;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Localization\LanguageSystem;
+use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
+use Org\Mxchange\CoreFramework\Loader\ClassLoader;
+use Org\Mxchange\CoreFramework\Generic\FrameworkException;
+
+// Import SPL stuff
+use \Exception;
 
-//xdebug_start_trace();
 /**
  * The main class with the entry point to the whole application. This class
- * "emulates" Java(tm)'s entry point call. Additionally it covers local
+ * "emulates" Java's entry point call. Additionally it covers local
  * variables from outside access to prevent possible attacks on uninitialized
  * local variables.
  *
  * But good little boys and girls would always initialize their variables... ;-)
  *
- * @author             Roland Haeder <webmaster@mxchange.org>
+ * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
- * @link               http://www.ship-simu.org
+ * @link               http://www.shipsimu.org
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * You should have received a copy of the GNU General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
-class ApplicationEntryPoint {
+final class ApplicationEntryPoint {
        /**
-        * The instances we want to remove after all is done
-        *
-        * @return      void
+        * Framework path
         */
-       private static $instances = array (
-               'cfg',    // The configuration system
-               'loader', // The class loader system
-               'debug',  // Debug output
-               'db',     // Database layer
-               'io',     // Base I/O system (local file [or network])
-               'engine', // Template engine ( for ApplicationEntryPoint::app_die() )
-               'lang',   // Language sub-system
-               'app',    // The ApplicationHelper instance
-       );
+       private static $frameworkPath = '';
 
        /**
         * The application's emergency exit
         *
-        * @param               $message        The optional message we shall output on exit
+        * @param       $message                The optional message we shall output on exit
+        * @param       $code                   Error code from exception
+        * @param       $extraData              Extra information from exceptions
+        * @param       $silentMode             Whether silent mode is turned on
         * @return      void
+        * @todo        This method is old code and needs heavy rewrite and should be moved to ApplicationHelper
         */
-       public static function app_die ($message = "") {
+       public static final function exitApplication (string $message = '', int $code = -1, string $extraData = '', bool $silentMode = false) {
                // Is this method already called?
-               if (defined('EMERGENCY_EXIT_CALLED')) {
+               //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,code=%d,extraData=%s,silentMode=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, $code, $extraData, intval($silentMode));
+               if (isset($GLOBALS['app_die_called'])) {
                        // Then output the text directly
-                       die($message);
+                       print $message . PHP_EOL;
+                       exit(255);
                }
 
                // This method shall not be called twice
-               define('EMERGENCY_EXIT_CALLED', true);
+               $GLOBALS['app_die_called'] = true;
 
                // Is a message set?
                if (empty($message)) {
                        // No message provided
-                       $message = "No message provided!";
+                       $message = 'No message provided.';
+               }
+
+               // Get config instance
+               $configInstance = FrameworkBootstrap::getConfigurationInstance();
+
+               // Do we have debug installation?
+               if (($configInstance->getConfigEntry('product_install_mode') == 'productive') || ($silentMode === true)) {
+                       // Abort here
+                       //* NOISY-DEBUG: */ printf('[%s:%d]: product_install_mode=%d,silentMode=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $configInstance->getConfigEntry('product_install_mode'), intval($silentMode));
+                       exit(255);
                }
 
                // Get some instances
-               $tpl = FrameworkConfiguration::getInstance()->readConfig('tpl_engine');
-               $lang = LanguageSystem::getInstance();
-               $io = FileIoHandler::getInstance();
+               $templateClassName = $configInstance->getConfigEntry('html_template_class');
+               $languageInstance = LanguageSystem::getSelfInstance();
+
+               // Initialize template instance here to avoid warnings in IDE
+               $templateInstance = NULL;
+
+               // Get response instance
+               $responseInstance = FrameworkBootstrap::getResponseInstance();
 
                // Is the template engine loaded?
-               if ((class_exists($tpl)) && (is_object($lang)) && (is_object($io))) {
+               if ((class_exists($templateClassName)) && ($languageInstance instanceof ManageableLanguage)) {
                        // Use the template engine for putting out (nicer look) the message
                        try {
                                // Get the template instance from our object factory
-                               $tplEngine = ObjectFactory::createObjectByConfiguredName('tpl_engine', array(FrameworkConfiguration::getInstance()->readConfig('tpl_base_path'), $lang, $io));
-                       } catch (BasePathIsEmptyException $e) {
-                               die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
-                                       $e->getMessage()
-                               ));
-                       } catch (InvalidBasePathStringException $e) {
-                               die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
-                                       $e->getMessage()
-                               ));
-                       } catch (BasePathIsNoDirectoryException $e) {
-                               die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
-                                       $e->getMessage()
-                               ));
-                       } catch (BasePathReadProtectedException $e) {
-                               die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
+                               $templateInstance = ObjectFactory::createObjectByName($templateClassName);
+                       } catch (FrameworkException $e) {
+                               exit(sprintf('[Main:] Could not initialize template engine for reason: <span class="exception_reason">%s</span>',
                                        $e->getMessage()
                                ));
                        }
 
-                       // Backtrace holen und aufbereiten
-                       $backtraceArray = debug_backtrace();
-                       $backtrace = "";
-                       foreach ($backtraceArray as $key=>$trace) {
-                               if (!isset($trace['file'])) $trace['file'] = __FILE__;
-                               if (!isset($trace['line'])) $trace['line'] = 5;
-                               if (!isset($trace['args'])) $trace['args'] = array();
-                               $backtrace .= "<span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span><br />";
+                       // Get and prepare backtrace for output
+                       $backtrace = '';
+                       foreach (debug_backtrace() as $key => $trace) {
+                               // Set missing array elements
+                               if (!isset($trace['file'])) {
+                                       $trace['file'] = __FILE__;
+                               }
+                               if (!isset($trace['line'])) {
+                                       $trace['line'] = __LINE__;
+                               }
+                               if (!isset($trace['args'])) {
+                                       $trace['args'] = array();
+                               }
+
+                               // Add the traceback path to the final output
+                               $backtrace .= sprintf('<span class="backtrace_file">%s</span>:%d, <span class="backtrace_function">%s(%d)</span><br />' . PHP_EOL,
+                                       basename($trace['file']),
+                                       $trace['line'],
+                                       $trace['function'],
+                                       count($trace['args'])
+                               );
+                       }
+
+                       // Init application instance
+                       $applicationInstance = NULL;
+
+                       /*
+                        * The following class may NOT be loaded at all times. For example,
+                        * it might be the (rare) case that an error has happened BEFORE
+                        * that class had been loaded and cannot be loaded or else an
+                        * infinte loop in invoking this method will take place resulting in
+                        * a stack-overflow error.
+                        */
+                       if (class_exists('Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper')) {
+                               // Get application instance
+                               $applicationInstance = ApplicationHelper::getSelfInstance();
+
+                               // Assign application data
+                               $templateInstance->assignApplicationData();
                        }
 
-                       // Assign variables
-                       $tplEngine->assignVariable('message', $message);
-                       $tplEngine->assignVariable('backtrace', $backtrace);
-                       $tplEngine->assignVariable('total_objects', ObjectFactory::getTotal());
+                       // We only try this
+                       try {
+                               // Assign variables
+                               $templateInstance->assignVariable('message'       , $message);
+                               $templateInstance->assignVariable('code'          , $code);
+                               $templateInstance->assignVariable('extra'         , $extraData);
+                               $templateInstance->assignVariable('backtrace'     , $backtrace);
+                               $templateInstance->assignVariable('total_includes', ClassLoader::getSelfInstance()->getTotal());
+                               $templateInstance->assignVariable('total_objects' , ObjectFactory::getTotal());
+                               $templateInstance->assignVariable('title'         , $languageInstance->getMessage('emergency_exit_title'));
+
+                               // Load the template
+                               $templateInstance->loadCodeTemplate('emergency_exit');
 
-                       // Load the template
-                       $tplEngine->loadCodeTemplate('emergency_exit');
+                               // Compile the template
+                               $templateInstance->compileTemplate();
 
-                       // Compile the template
-                       $tplEngine->compileTemplate();
+                               // Compile all variables
+                               $templateInstance->compileVariables();
 
-                       // Compile all variables
-                       $tplEngine->compileVariables();
+                               // Transfer data to response
+                               $templateInstance->transferToResponse($responseInstance);
 
-                       // Output all
-                       $tplEngine->output();
+                               // Flush the response
+                               $responseInstance->flushBuffer();
+                       } catch (FileNotFoundException $e) {
+                               // Even the template 'emergency_exit' wasn't found so output both message
+                               print ($message . ', exception: ' . $e->getMessage() . PHP_EOL);
+                               exit($e->getCode());
+                       }
 
                        // Good bye...
-                       exit();
+                       exit(255);
                } else {
                        // Output message and die
-                       die(sprintf("[Main:] Emergency exit reached: <span class=\"emergency_span\">%s</span>",
-                               $message
-                       ));
+                       printf('[Main:] Emergency exit reached: <span class="emergency_span">%s</span>', $message);
+                       exit(255);
                }
+
+               // Trace message
+               //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
        }
 
        /**
-        * The application's main entry point. This class isolates some local
+        * Determines the correct absolute path for the framework. A set of common
+        * paths is being tested (first most common for applications, second when
+        * core tests are being executed and third/forth if the framework has been
+        * cloned there).
+        *
+        * @return      $frameworkPath  Path for framework
+        */
+       public static final function detectFrameworkPath () {
+               // Is it not set?
+               //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
+               if (empty(self::$frameworkPath)) {
+                       // Auto-detect core path (first application-common)
+                       foreach (['core', self::getRootPath(), '/usr/local/share/php/core', '/usr/share/php/core'] as $possiblePath) {
+                               // Create full path for testing
+                               //* NOISY-DEBUG: */ printf('[%s:%d]: possiblePath=%s' . PHP_EOL, __METHOD__, __LINE__, $possiblePath);
+                               $realPath = realpath($possiblePath);
+
+                               // Is it false?
+                               //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
+                               if ($realPath === false) {
+                                       // Then, not found.
+                                       //* NOISY-DEBUG: */ printf('[%s:%d]: possiblePath=%s was not found. - SKIPPED!' . PHP_EOL, __METHOD__, __LINE__, $possiblePath);
+                                       continue;
+                               }
+
+                               // Append framework path
+                               $frameworkPath = sprintf('%s%sframework%s', $realPath, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
+
+                               // First create full-qualified file name (FQFN) to framework/config-global.php
+                               //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkPath=%s' . PHP_EOL, __METHOD__, __LINE__, $frameworkPath);
+                               $configFile = $frameworkPath . 'config-global.php';
+
+                               // Is it readable?
+                               //* NOISY-DEBUG: */ printf('[%s:%d]: configFile=%s' . PHP_EOL, __METHOD__, __LINE__, $configFile);
+                               if (is_readable($configFile)) {
+                                       // Found one
+                                       self::$frameworkPath = $frameworkPath;
+
+                                       // Abort here
+                                       //* NOISY-DEBUG: */ printf('[%s:%d]: Setting self::frameworkPath=%s - BREAK!' . PHP_EOL, __METHOD__, __LINE__, $frameworkPath);
+                                       break;
+                               }
+                       }
+
+                       // Able to find?
+                       //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - Checking ...' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
+                       if (!is_dir(self::$frameworkPath)) {
+                               // Is no directory
+                               throw new Exception('Cannot find framework.');
+                       }
+               }
+
+               // Return it
+               //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
+               return self::$frameworkPath;
+       }
+
+       /**
+        * Getter for root path
+        *
+        * @return      $rootPath       Root path
+        */
+       public static function getRootPath () {
+               // Get __DIR__, really simple and no detection
+               return __DIR__;
+       }
+
+       /**
+        * The framework's main entry point. This class isolates some local
         * variables which shall not become visible to outside because of security
-        * concerns. We are doing this here to "emulate" the well-known entry
-        * point in Java(tm).
+        * concerns. This is done here to "emulate" the well-known entry point in
+        * Java.
         *
         * @return      void
         */
-       public static function main () {
-               // Some non-global common arrays we need...
-               global $_SERVER;
-
-               // Load config file
-               require(dirname(__FILE__) . '/inc/config.php');
+       public static final function main () {
+               // Load bootstrap file
+               //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
+               require sprintf('%sbootstrap%sbootstrap.inc.php', self::detectFrameworkPath(), DIRECTORY_SEPARATOR);
 
-               // Load all include files
-               require(PATH . 'inc/includes.php');
+               /*
+                * Initial bootstrap is done, continue with initialization of
+                * framework.
+                */
+               FrameworkBootstrap::initFramework();
 
-               // Load all framework classes
-               require(PATH . 'inc/classes.php');
+               // Next initialize the detected application
+               FrameworkBootstrap::prepareApplication();
 
-               // Include the application selector
-               require(PATH . 'inc/selector.php');
+               /*
+                * Last step is to start the application, this will also initialize and
+                * register the application instance in registry.
+                */
+               FrameworkBootstrap::startApplication();
 
-       } // END - main()
+               // Trace message
+               //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+       }
+}
 
-} // END - class
+// Log all exceptions (only debug! This option can create large error logs)
+//define('LOG_EXCEPTIONS', true);
 
-// Do not remove the following line:
+// Call above main() method
 ApplicationEntryPoint::main();
-
-// [EOF]
-?>