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\ObjectFactory;
12 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
13 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
14 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
15 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
16 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
17 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
18 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
19 use Org\Mxchange\CoreFramework\Request\Requestable;
20 use Org\Mxchange\CoreFramework\Response\Responseable;
21 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
24 use \BadMethodCallException;
25 use \InvalidArgumentException;
29 * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
31 * @author Roland Haeder <webmaster@ship-simu.org>
33 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
34 * @license GNU GPL 3.0 or any newer version
35 * @link http://www.ship-simu.org
37 * This program is free software: you can redistribute it and/or modify
38 * it under the terms of the GNU General Public License as published by
39 * the Free Software Foundation, either version 3 of the License, or
40 * (at your option) any later version.
42 * This program is distributed in the hope that it will be useful,
43 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 * GNU General Public License for more details.
47 * You should have received a copy of the GNU General Public License
48 * along with this program. If not, see <http://www.gnu.org/licenses/>.
50 final class FrameworkBootstrap {
53 * Detected server address
55 private static $serverAddress = NULL;
58 * Instance of a Requestable class
60 private static $requestInstance = NULL;
63 * Instance of a Responseable class
65 private static $responseInstance = NULL;
68 * Instance of a FrameworkConfiguration class
70 private static $configurationInstance = NULL;
75 private static $databaseInstance = NULL;
78 * Includes applications may have. They will be tried in the given order,
79 * some will become soon deprecated.
81 private static $configAppIncludes = array(
82 // The ApplicationHelper class (required)
83 'class_ApplicationHelper' => 'required',
84 // Some debugging stuff (optional but can be committed)
85 'debug' => 'optional',
86 // Application's exception handler (optional but can be committed)
87 'exceptions' => 'optional',
88 // Application's configuration file (committed, non-local specific)
89 'config' => 'required',
90 // Local configuration file (optional, not committed, listed in .gitignore)
91 'config-local' => 'optional',
92 // Application data (deprecated)
93 'data' => 'deprecated',
94 // Application loader (deprecated)
95 'loader' => 'deprecated',
96 // Application initializer (deprecated)
97 'init' => 'deprecated',
98 // Application starter (deprecated)
99 'starter' => 'deprecated',
103 * Private constructor, no instance is needed from this class as only
104 * static methods exist.
106 private function __construct () {
107 // Prevent making instances from this "utilities" class
111 * Some "getter" for a configuration instance, making sure, it is unique
113 * @return $configurationInstance An instance of a FrameworkConfiguration class
115 public static function getConfigurationInstance () {
116 // Is the instance there?
117 if (is_null(self::$configurationInstance)) {
119 self::$configurationInstance = new FrameworkConfiguration();
123 return self::$configurationInstance;
127 * "Getter" to get response/request type from analysis of the system.
129 * @return $requestType Analyzed request type
131 public static function getRequestTypeFromSystem () {
132 // Default is console
133 $requestType = 'console';
135 // Is 'HTTP_HOST' set?
136 if (isset($_SERVER['HTTP_HOST'])) {
137 // Then it is a HTML response/request.
138 $requestType = 'html';
146 * Checks whether the given file/path is in open_basedir(). This does not
147 * gurantee that the file is actually readable and/or writeable. If you need
148 * such gurantee then please use isReadableFile() instead.
150 * @param $fileInstance An instance of a SplFileInfo class
151 * @return $isReachable Whether it is within open_basedir()
153 public static function isReachableFilePath (SplFileInfo $fileInstance) {
154 // Is not reachable by default
155 $isReachable = false;
157 // Get open_basedir parameter
158 $openBaseDir = trim(ini_get('open_basedir'));
161 if (!empty($openBaseDir)) {
163 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
164 // Check on existence
165 if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
169 // Abort lookup as it has been found in open_basedir
174 // If open_basedir is not set, all is allowed
183 * Checks whether the give file is within open_basedir() (done by
184 * isReachableFilePath()), is actually a file and is readable.
186 * @param $fileInstance An instance of a SplFileInfo class
187 * @return $isReadable Whether the file is readable (and therefor exists)
189 public static function isReadableFile (SplFileInfo $fileInstance) {
190 // Default is not readable
193 // Check if it is a file and readable
196 self::isReachableFilePath($fileInstance)
198 $fileInstance->isFile()
200 $fileInstance->isReadable()
209 * Loads given include file
211 * @param $fileInstance An instance of a SplFileInfo class
213 * @throws InvalidArgumentException If file was not found or not readable or deprecated
215 public static function loadInclude (SplFileInfo $fileInstance) {
217 //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
219 // Should be there ...
220 if (!self::isReadableFile($fileInstance)) {
222 throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
226 require_once $fileInstance->getPathname();
229 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
233 * Does the actual bootstrap
237 public static function doBootstrap () {
238 // Load basic include files to continue bootstrapping
239 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
240 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sclass_BaseFrameworkSystem.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
241 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sutils%sstring%sclass_StringUtils.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
242 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
243 self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
245 // Load global configuration
246 self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
250 * Initializes the framework by scanning for all framework-relevant
251 * classes, interfaces and exception. Then determine the request type and
252 * initialize a Requestable instance which will then contain all request
253 * parameter, also from CLI. Next step is to validate the application
258 public static function initFramework () {
260 * 1) Load class loader and scan framework classes, interfaces and
263 self::scanFrameworkClasses();
266 * 2) Determine the request type, console or web and store request and
267 * response here. This also initializes the request instance will
268 * all given parameters (see doc-tag for possible sources of
271 self::determineRequestType();
274 * 3) Now, that there are all request parameters being available, check
275 * if 'application' is supplied. If it is not found, abort execution, if
276 * found, continue below with next step.
278 self::validateApplicationParameter();
282 * Initializes the detected application. This may fail if required files
283 * are not found in the application's base path (not to be confused with
284 * 'application_base_path' which only points to /some/foo/application/.
288 public static function prepareApplication () {
289 // Configuration entry 'detected_app_name' must be set, get it here, including full path
290 $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
291 $fullPath = self::getConfigurationInstance()->getConfigEntry('detected_full_app_path');
294 * Now check and load all files, found deprecated files will throw a
295 * warning at the user.
297 foreach (self::$configAppIncludes as $fileName => $status) {
298 // Construct file instance
299 $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
301 // Determine if this file is wanted/readable/deprecated
302 if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
303 // Nope, required file cannot be found/read from
304 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
305 } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
306 // Found, not readable file
307 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
308 } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
309 // Not found but optional/deprecated file, skip it
313 // Is the file deprecated?
314 if ($status == 'deprecated') {
316 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, $application), E_USER_WARNING);
318 // Skip loading deprecated file
323 self::loadInclude($fileInstance);
326 // Scan for application's classes, exceptions and interfaces
327 ClassLoader::scanApplicationClasses();
331 * Starts a fully initialized application, the class ApplicationHelper must
332 * be loaded at this point.
336 public static function startApplication () {
337 // Configuration entry 'detected_app_name' must be set, get it here
338 $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
340 // Is there an application helper instance?
341 $applicationInstance = call_user_func_array(
343 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
347 // Some sanity checks
348 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
349 // Something went wrong!
350 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.',
352 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper'
354 } elseif (!is_object($applicationInstance)) {
356 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is not an object (%s).',
358 gettype($applicationInstance)
360 } elseif (!($applicationInstance instanceof ManageableApplication)) {
362 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.',
367 // Now call all methods in one go
368 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
370 //*NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
373 call_user_func(array($applicationInstance, $methodName));
378 * Initializes database instance, no need to double-call this method
382 public static function initDatabaseInstance () {
383 // Get application instance
384 $applicationInstance = ApplicationHelper::getSelfInstance();
386 // Is the database instance already set?
387 if (self::getDatabaseInstance() instanceof DatabaseConnector) {
388 // Yes, then abort here
389 throw new BadMethodCallException('Method called twice.');
392 // Initialize database layer
393 $databaseInstance = ObjectFactory::createObjectByConfiguredName(self::getConfigurationInstance()->getConfigEntry('database_type') . '_class');
395 // Prepare database instance
396 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
398 // Set it in application helper
399 self::setDatabaseInstance($connectionInstance);
403 * Detects the server address (SERVER_ADDR) and set it in configuration
405 * @return $serverAddress The detected server address
406 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
407 * @todo Have to check some more entries from $_SERVER here
409 public static function detectServerAddress () {
411 if (!isset(self::$serverAddress)) {
412 // Is it set in $_SERVER?
413 if (!empty($_SERVER['SERVER_ADDR'])) {
414 // Set it from $_SERVER
415 self::$serverAddress = $_SERVER['SERVER_ADDR'];
416 } elseif (isset($_SERVER['SERVER_NAME'])) {
417 // Resolve IP address
418 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
421 if ($serverIp === false) {
423 * Why is gethostbyname() returning the host name and not
424 * false as many other PHP functions are doing? ;-(
426 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
430 self::$serverAddress = $serverIp;
432 // Run auto-detecting through console tools lib
433 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
438 return self::$serverAddress;
442 * Setter for default time zone (must be correct!)
444 * @param $timezone The timezone string (e.g. Europe/Berlin)
445 * @return $success If timezone was accepted
446 * @throws NullPointerException If $timezone is NULL
447 * @throws InvalidArgumentException If $timezone is empty
449 public static function setDefaultTimezone ($timezone) {
451 if (is_null($timezone)) {
453 throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
454 } elseif (!is_string($timezone)) {
456 throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
457 } elseif ((is_string($timezone)) && (empty($timezone))) {
459 throw new InvalidArgumentException('timezone is empty');
466 * Set desired time zone to prevent date() and related functions to
467 * issue an E_WARNING.
469 $success = date_default_timezone_set($timezone);
476 * Checks whether HTTPS is set in $_SERVER
478 * @return $isset Whether HTTPS is set
479 * @todo Test more fields
481 public static function isHttpSecured () {
485 isset($_SERVER['HTTPS'])
487 strtolower($_SERVER['HTTPS']) == 'on'
491 isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
493 strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
500 * Dectect and return the base URL for all URLs and forms
502 * @return $baseUrl Detected base URL
504 public static function detectBaseUrl () {
505 // Initialize the URL
509 if (self::isHttpSecured()) {
510 // Add the >s< for HTTPS
514 // Construct the full URL and secure it against CSRF attacks
515 $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
522 * Detect safely and return the full domain where this script is installed
524 * @return $fullDomain The detected full domain
526 public static function detectDomain () {
527 // Full domain is localnet.invalid by default
528 $fullDomain = 'localnet.invalid';
530 // Is the server name there?
531 if (isset($_SERVER['SERVER_NAME'])) {
532 // Detect the full domain
533 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
541 * Detect safely the script path without trailing slash which is the glue
542 * between "http://your-domain.invalid/" and "script-name.php"
544 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
546 public static function detectScriptPath () {
550 // Is the scriptname set?
551 if (isset($_SERVER['SCRIPT_NAME'])) {
552 // Get dirname from it and replace back-slashes with slashes for lame OSes...
553 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
561 * 1) Loads class scanner and scans all framework's classes and interfaces.
562 * This method also registers the class loader's method autoLoad() for the
563 * SPL auto-load feature. Remember that you can register additional methods
564 * (not functions, please) for other libraries.
566 * Yes, I know about Composer, but I like to keep my class loader around.
567 * You can always use mine as long as your classes have a namespace
568 * according naming-convention: Vendor\Project\Group[\SubGroup]
572 private static function scanFrameworkClasses () {
573 // Include the class loader function
574 require self::getConfigurationInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
576 // Register auto-load function with the SPL
577 spl_autoload_register('Org\Mxchange\CoreFramework\Loader\ClassLoader::autoLoad');
579 // Scan for all framework classes, exceptions and interfaces
580 ClassLoader::scanFrameworkClasses();
584 * 2) Determines request/response type and stores the created
585 * request/response instances in this object for later usage.
589 private static function determineRequestType () {
590 // Determine request type
591 $request = self::getRequestTypeFromSystem();
592 $requestType = self::getRequestTypeFromSystem();
594 // Create a new request object
595 $requestInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Request\%sRequest', StringUtils::convertToClassName($request)));
597 // Remember request instance here
598 self::setRequestInstance($requestInstance);
600 // Do we have another response?
601 if ($requestInstance->isRequestElementSet('request')) {
603 $request = strtolower($requestInstance->getRequestElement('request'));
604 $requestType = $request;
607 // ... and a new response object
608 $responseClass = sprintf('Org\Mxchange\CoreFramework\Response\%sResponse', StringUtils::convertToClassName($request));
609 $responseInstance = ObjectFactory::createObjectByName($responseClass);
611 // Remember response instance here
612 self::setResponseInstance($responseInstance);
616 * 3) Validate parameter 'application' if it is set and the application is there.
620 private static function validateApplicationParameter () {
621 // Is the parameter set?
622 if (!self::getRequestInstance()->isRequestElementSet('app')) {
624 * Don't continue here, the application 'selector' is no longer
625 * supported and only existed as an idea to select the proper
626 * application (by user).
628 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
631 // Get it for local usage
632 $application = self::getRequestInstance()->getRequestElement('app');
634 // Secure it, by keeping out tags
635 $application = htmlentities(strip_tags($application), ENT_QUOTES);
637 // Secure it a little more with a reg.exp.
638 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
640 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
641 $applicationPath = sprintf(
643 self::getConfigurationInstance()->getConfigEntry('application_base_path'),
648 // Full path for application
649 // Is the path there? This secures a bit the parameter (from untrusted source).
650 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
651 // Not found or not readable
652 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
655 // Set the detected application's name and full path for later usage
656 self::getConfigurationInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
657 self::getConfigurationInstance()->setConfigEntry('detected_app_name' , $application);
661 * Getter for request instance
663 * @return $requestInstance An instance of a Requestable class
665 public static function getRequestInstance () {
666 return self::$requestInstance;
670 * Getter for response instance
672 * @return $responseInstance An instance of a Responseable class
674 public static function getResponseInstance () {
675 return self::$responseInstance;
679 * Setter for request instance
681 * @param $requestInstance An instance of a Requestable class
684 private static function setRequestInstance (Requestable $requestInstance) {
685 self::$requestInstance = $requestInstance;
689 * Setter for response instance
691 * @param $responseInstance An instance of a Responseable class
694 private static function setResponseInstance (Responseable $responseInstance) {
695 self::$responseInstance = $responseInstance;
699 * Setter for database instance
701 * @param $databaseInstance An instance of a DatabaseConnection class
704 public static function setDatabaseInstance (DatabaseConnection $databaseInstance) {
705 self::$databaseInstance = $databaseInstance;
709 * Getter for database instance
711 * @return $databaseInstance An instance of a DatabaseConnection class
713 public static function getDatabaseInstance () {
715 return self::$databaseInstance;