3 namespace Org\Mxchange\CoreFramework\Bootstrap;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
7 use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
8 use Org\Mxchange\CoreFramework\Connector\Database\DatabaseConnector;
9 use Org\Mxchange\CoreFramework\Console\Tools\ConsoleTools;
10 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
11 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
12 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
13 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
14 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
15 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
16 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
17 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
18 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
19 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
20 use Org\Mxchange\CoreFramework\Request\Requestable;
21 use Org\Mxchange\CoreFramework\Response\Responseable;
22 use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
25 use \BadMethodCallException;
26 use \InvalidArgumentException;
30 * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
32 * @author Roland Haeder <webmaster@ship-simu.org>
34 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
35 * @license GNU GPL 3.0 or any newer version
36 * @link http://www.ship-simu.org
38 * This program is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or
41 * (at your option) any later version.
43 * This program is distributed in the hope that it will be useful,
44 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 * GNU General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see <http://www.gnu.org/licenses/>.
51 final class FrameworkBootstrap {
54 * Detected server address
56 private static $serverAddress = NULL;
59 * Instance of a Requestable class
61 private static $requestInstance = NULL;
64 * Instance of a Responseable class
66 private static $responseInstance = NULL;
69 * Instance of a FrameworkConfiguration class
71 private static $configurationInstance = NULL;
76 private static $databaseInstance = NULL;
79 * Language system instance
81 private static $languageInstance = NULL;
84 * Includes applications may have. They will be tried in the given order,
85 * some will become soon deprecated.
87 private static $configAppIncludes = [
88 // The ApplicationHelper class (required)
89 'class_ApplicationHelper' => 'required',
90 // Some debugging stuff (optional but can be committed)
91 'debug' => 'optional',
92 // Application's exception handler (optional but can be committed)
93 'exceptions' => 'optional',
94 // Application's configuration file (committed, non-local specific)
95 'config' => 'required',
96 // Local configuration file (optional, not committed, listed in .gitignore)
97 'config-local' => 'optional',
98 // Application data (deprecated)
99 'data' => 'deprecated',
100 // Application loader (deprecated)
101 'loader' => 'deprecated',
102 // Application initializer (deprecated)
103 'init' => 'deprecated',
104 // Application starter (deprecated)
105 'starter' => 'deprecated',
109 * Detected application's name
111 private static $detectedApplicationName;
114 * Detected application's full path
116 private static $detectedApplicationPath;
119 * Private constructor, no instance is needed from this class as only
120 * static methods exist.
122 private function __construct () {
123 // Prevent making instances from this "utilities" class
127 * Some "getter" for a configuration instance, making sure, it is unique
129 * @return $configurationInstance An instance of a FrameworkConfiguration class
131 public static function getConfigurationInstance () {
132 // Is the instance there?
133 if (is_null(self::$configurationInstance)) {
135 self::$configurationInstance = new FrameworkConfiguration();
139 return self::$configurationInstance;
143 * Getter for detected application name
145 * @return $detectedApplicationName Detected name of application
147 public static function getDetectedApplicationName () {
148 return self::$detectedApplicationName;
152 * Getter for detected application's full path
154 * @return $detectedApplicationPath Detected full path of application
156 public static function getDetectedApplicationPath () {
157 return self::$detectedApplicationPath;
161 * "Getter" to get response/request type from analysis of the system.
163 * @return $requestType Analyzed request type
165 public static function getRequestTypeFromSystem () {
166 // Default is console
167 $requestType = 'console';
169 // Is 'HTTP_HOST' set?
170 if (isset($_SERVER['HTTP_HOST'])) {
171 // Then it is a HTML response/request.
172 $requestType = 'html';
180 * Checks whether the given file/path is in open_basedir(). This does not
181 * gurantee that the file is actually readable and/or writeable. If you need
182 * such gurantee then please use isReadableFile() instead.
184 * @param $fileInstance An instance of a SplFileInfo class
185 * @return $isReachable Whether it is within open_basedir()
187 public static function isReachableFilePath (SplFileInfo $fileInstance) {
188 // Is not reachable by default
189 $isReachable = false;
191 // Get open_basedir parameter
192 $openBaseDir = trim(ini_get('open_basedir'));
195 if (!empty($openBaseDir)) {
197 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
198 // Check on existence
199 if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
203 // Abort lookup as it has been found in open_basedir
208 // If open_basedir is not set, all is allowed
217 * Checks whether the give file is within open_basedir() (done by
218 * isReachableFilePath()), is actually a file and is readable.
220 * @param $fileInstance An instance of a SplFileInfo class
221 * @return $isReadable Whether the file is readable (and therefor exists)
223 public static function isReadableFile (SplFileInfo $fileInstance) {
224 // Default is not readable
227 // Check if it is a file and readable
230 self::isReachableFilePath($fileInstance)
232 $fileInstance->isFile()
234 $fileInstance->isReadable()
243 * Loads given include file
245 * @param $fileInstance An instance of a SplFileInfo class
247 * @throws InvalidArgumentException If file was not found or not readable or deprecated
249 public static function loadInclude (SplFileInfo $fileInstance) {
250 // Should be there ...
251 //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
252 if (!self::isReadableFile($fileInstance)) {
254 throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
258 require_once $fileInstance->getPathname();
261 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
265 * Does the actual bootstrap. I think the amount of statically loaded
266 * include files cannot be reduced here as those files are need to early
267 * in the bootstrap phase. If you can find an other solution than this, with
268 * lesser "static includes" (means not loaded by the class loader), please
273 public static function doBootstrap () {
274 // Load basic include files to continue bootstrapping
275 //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
276 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
277 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sclass_BaseFrameworkSystem.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
278 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sutils%sstrings%sclass_StringUtils.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
279 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
280 self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
282 // Load global configuration
283 self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
286 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
290 * Initializes the framework by scanning for all framework-relevant
291 * classes, interfaces and exception. Then determine the request type and
292 * initialize a Requestable instance which will then contain all request
293 * parameter, also from CLI. Next step is to validate the application
298 public static function initFramework () {
300 * 1) Load class loader and scan framework classes, interfaces and
303 self::scanFrameworkClasses();
306 * 2) Determine the request type, console or web and store request and
307 * response here. This also initializes the request instance with
308 * all given parameters (see doc-tag for possible sources of
311 self::determineRequestType();
314 * 3) Now, that there are all request parameters being available, check
315 * if 'application' is supplied. If it is not found, abort execution, if
316 * found, continue below with next step.
318 self::validateApplicationParameter();
322 * Initializes the detected application. This may fail if required files
323 * are not found in the application's base path (not to be confused with
324 * 'application_base_path' which only points to /some/foo/application/.
328 public static function prepareApplication () {
330 * Now check and load all files, found deprecated files will throw a
331 * warning at the user.
333 foreach (self::$configAppIncludes as $fileName => $status) {
334 // Construct file instance
335 $fileInstance = new SplFileInfo(sprintf('%s%s.php', self::getDetectedApplicationPath(), $fileName));
337 // Determine if this file is wanted/readable/deprecated
338 if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
339 // Nope, required file cannot be found/read from
340 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', self::getDetectedApplicationName(), $fileInstance->getBasename()));
341 } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
342 // Found, not readable file
343 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), self::getDetectedApplicationName()));
344 } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
345 // Not found but optional/deprecated file, skip it
349 // Is the file deprecated?
350 if ($status == 'deprecated') {
352 trigger_error(sprintf('Deprecated file "%s.php" found, will not load it to avoid problems. Please remove it from your application "%s" to avoid this warning.', $fileName, self::getDetectedApplicationName()), E_USER_WARNING);
354 // Skip loading deprecated file
359 self::loadInclude($fileInstance);
362 // After this, sort the configuration array
363 self::getConfigurationInstance()->sortConfigurationArray();
365 // Scan for application's classes, exceptions and interfaces
366 ClassLoader::scanApplicationClasses();
370 * Starts a fully initialized application, the class ApplicationHelper must
371 * be loaded at this point.
375 public static function startApplication () {
376 // Is there an application helper instance?
377 $applicationInstance = call_user_func_array(
379 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
383 // Some sanity checks
384 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
385 // Something went wrong!
386 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because the helper class <span class="class_name">%s</span> is not loaded.',
387 self::getDetectedApplicationName(),
388 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper'
390 } elseif (!is_object($applicationInstance)) {
392 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is not an object (%s).',
393 self::getDetectedApplicationName(),
394 gettype($applicationInstance)
396 } elseif (!($applicationInstance instanceof ManageableApplication)) {
398 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.',
399 self::getDetectedApplicationName()
403 // Now call all methods in one go
404 foreach (['setupApplicationData', 'initApplication', 'launchApplication'] as $methodName) {
406 //*NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
407 call_user_func([$applicationInstance, $methodName]);
412 * Initializes database instance, no need to double-call this method
416 public static function initDatabaseInstance () {
417 // Get application instance
418 $applicationInstance = ApplicationHelper::getSelfInstance();
420 // Is the database instance already set?
421 if (self::getDatabaseInstance() instanceof DatabaseConnector) {
422 // Yes, then abort here
423 throw new BadMethodCallException('Method called twice.');
426 // Initialize database layer
427 $databaseInstance = ObjectFactory::createObjectByConfiguredName(self::getConfigurationInstance()->getConfigEntry('database_type') . '_class');
429 // Prepare database instance
430 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
432 // Set it in application helper
433 self::setDatabaseInstance($connectionInstance);
437 * Detects the server address (SERVER_ADDR) and set it in configuration
439 * @return $serverAddress The detected server address
440 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
441 * @todo Have to check some more entries from $_SERVER here
443 public static function detectServerAddress () {
445 if (!isset(self::$serverAddress)) {
446 // Is it set in $_SERVER?
447 if (!empty($_SERVER['SERVER_ADDR'])) {
448 // Set it from $_SERVER
449 self::$serverAddress = $_SERVER['SERVER_ADDR'];
450 } elseif (isset($_SERVER['SERVER_NAME'])) {
451 // Resolve IP address
452 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
455 if ($serverIp === false) {
457 * Why is gethostbyname() returning the host name and not
458 * false as many other PHP functions are doing? ;-(
460 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
464 self::$serverAddress = $serverIp;
466 // Run auto-detecting through console tools lib
467 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
472 return self::$serverAddress;
476 * Setter for default time zone (must be correct!)
478 * @param $timezone The timezone string (e.g. Europe/Berlin)
479 * @return $success If timezone was accepted
480 * @throws InvalidArgumentException If $timezone is empty
482 public static function setDefaultTimezone (string $timezone) {
484 if (empty($timezone)) {
486 throw new InvalidArgumentException('timezone is empty');
493 * Set desired time zone to prevent date() and related functions to
494 * issue an E_WARNING.
496 $success = date_default_timezone_set($timezone);
503 * Checks whether HTTPS is set in $_SERVER
505 * @return $isset Whether HTTPS is set
506 * @todo Test more fields
508 public static function isHttpSecured () {
512 isset($_SERVER['HTTPS'])
514 strtolower($_SERVER['HTTPS']) == 'on'
518 isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
520 strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
527 * Dectect and return the base URL for all URLs and forms
529 * @return $baseUrl Detected base URL
531 public static function detectBaseUrl () {
532 // Initialize the URL
536 if (self::isHttpSecured()) {
537 // Add the >s< for HTTPS
541 // Construct the full URL and secure it against CSRF attacks
542 $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
549 * Detect safely and return the full domain where this script is installed
551 * @return $fullDomain The detected full domain
553 public static function detectDomain () {
554 // Full domain is localnet.invalid by default
555 $fullDomain = 'localnet.invalid';
557 // Is the server name there?
558 if (isset($_SERVER['SERVER_NAME'])) {
559 // Detect the full domain
560 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
568 * Detect safely the script path without trailing slash which is the glue
569 * between "http://your-domain.invalid/" and "script-name.php"
571 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
573 public static function detectScriptPath () {
577 // Is the scriptname set?
578 if (isset($_SERVER['SCRIPT_NAME'])) {
579 // Get dirname from it and replace back-slashes with slashes for lame OSes...
580 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
588 * 1) Loads class scanner and scans all framework's classes and interfaces.
589 * This method also registers the class loader's method autoLoad() for the
590 * SPL auto-load feature. Remember that you can register additional methods
591 * (not functions, please) for other libraries.
593 * Yes, I know about Composer, but I like to keep my class loader around.
594 * You can always use mine as long as your classes have a namespace
595 * according naming-convention: Vendor\Project\Group[\SubGroup]
599 private static function scanFrameworkClasses () {
600 // Include class loader
601 require self::getConfigurationInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
603 // Register auto-load function with the SPL
604 spl_autoload_register('Org\Mxchange\CoreFramework\Loader\ClassLoader::autoLoad');
606 // Scan for all framework classes, exceptions and interfaces
607 ClassLoader::scanFrameworkClasses();
611 * 2) Determines request/response type and stores the created
612 * request/response instances in this object for later usage.
616 private static function determineRequestType () {
617 // Determine request type
618 $request = self::getRequestTypeFromSystem();
619 $requestType = self::getRequestTypeFromSystem();
621 // Create a new request object
622 $requestInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Request\%sRequest', StringUtils::convertToClassName($request)));
624 // Remember request instance here
625 self::setRequestInstance($requestInstance);
627 // Do we have another response?
628 if ($requestInstance->isRequestElementSet('request')) {
630 $request = strtolower($requestInstance->getRequestElement('request'));
631 $requestType = $request;
634 // ... and a new response object
635 $responseInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Response\%sResponse', StringUtils::convertToClassName($request)));
637 // Remember response instance here
638 self::setResponseInstance($responseInstance);
642 * 3) Validate parameter 'application' if it is set and the application is there.
646 private static function validateApplicationParameter () {
647 // Is the parameter set?
648 if (!self::getRequestInstance()->isRequestElementSet('app')) {
650 * Don't continue here, the application 'selector' is no longer
651 * supported and only existed as an idea to select the proper
652 * application (by user).
654 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
657 // Get it for local usage
658 $applicationName = self::getRequestInstance()->getRequestElement('app');
660 // Secure it, by keeping out tags
661 $applicationName = htmlentities(strip_tags($applicationName), ENT_QUOTES);
663 // Secure it a little more with a reg.exp.
664 $applicationName = preg_replace('/([^a-z0-9_-])+/i', '', $applicationName);
666 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
667 $applicationPath = sprintf(
669 self::getConfigurationInstance()->getConfigEntry('application_base_path'),
674 // Full path for application
675 // Is the path there? This secures a bit the parameter (from untrusted source).
676 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
677 // Not found or not readable
678 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $applicationName));
681 // Set the detected application's name and full path for later usage
682 self::$detectedApplicationPath = $applicationPath;
683 self::$detectedApplicationName = $applicationName;
687 * Getter for request instance
689 * @return $requestInstance An instance of a Requestable class
691 public static function getRequestInstance () {
692 return self::$requestInstance;
696 * Getter for response instance
698 * @return $responseInstance An instance of a Responseable class
700 public static function getResponseInstance () {
701 return self::$responseInstance;
705 * Setter for request instance
707 * @param $requestInstance An instance of a Requestable class
710 private static function setRequestInstance (Requestable $requestInstance) {
711 self::$requestInstance = $requestInstance;
715 * Setter for response instance
717 * @param $responseInstance An instance of a Responseable class
720 private static function setResponseInstance (Responseable $responseInstance) {
721 self::$responseInstance = $responseInstance;
725 * Setter for database instance
727 * @param $databaseInstance An instance of a DatabaseConnection class
730 public static function setDatabaseInstance (DatabaseConnection $databaseInstance) {
731 self::$databaseInstance = $databaseInstance;
735 * Getter for database instance
737 * @return $databaseInstance An instance of a DatabaseConnection class
739 public static function getDatabaseInstance () {
741 return self::$databaseInstance;
745 * Private getter for language instance
747 * @return $languageInstance An instance of a ManageableLanguage class
749 public static function getLanguageInstance () {
750 return self::$languageInstance;
754 * Setter for language instance
756 * @param $languageInstance An instance of a ManageableLanguage class
759 public static function setLanguageInstance (ManageableLanguage $languageInstance) {
760 self::$languageInstance = $languageInstance;