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;
23 use \BadMethodCallException;
24 use \InvalidArgumentException;
28 * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
30 * @author Roland Haeder <webmaster@ship-simu.org>
32 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
33 * @license GNU GPL 3.0 or any newer version
34 * @link http://www.ship-simu.org
36 * This program is free software: you can redistribute it and/or modify
37 * it under the terms of the GNU General Public License as published by
38 * the Free Software Foundation, either version 3 of the License, or
39 * (at your option) any later version.
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU General Public License for more details.
46 * You should have received a copy of the GNU General Public License
47 * along with this program. If not, see <http://www.gnu.org/licenses/>.
49 final class FrameworkBootstrap {
52 * Detected server address
54 private static $serverAddress = NULL;
57 * Instance of a Requestable class
59 private static $requestInstance = NULL;
62 * Instance of a Responseable class
64 private static $responseInstance = NULL;
67 * Instance of a FrameworkConfiguration class
69 private static $configurationInstance = NULL;
74 private static $databaseInstance = NULL;
77 * Includes applications may have. They will be tried in the given order,
78 * some will become soon deprecated.
80 private static $configAppIncludes = array(
81 // The ApplicationHelper class (required)
82 'class_ApplicationHelper' => 'required',
83 // Some debugging stuff (optional but can be committed)
84 'debug' => 'optional',
85 // Application's exception handler (optional but can be committed)
86 'exceptions' => 'optional',
87 // Application's configuration file (committed, non-local specific)
88 'config' => 'required',
89 // Local configuration file (optional, not committed, listed in .gitignore)
90 'config-local' => 'optional',
91 // Application data (deprecated)
92 'data' => 'deprecated',
93 // Application loader (deprecated)
94 'loader' => 'deprecated',
95 // Application initializer (deprecated)
96 'init' => 'deprecated',
97 // Application starter (deprecated)
98 'starter' => 'deprecated',
102 * Private constructor, no instance is needed from this class as only
103 * static methods exist.
105 private function __construct () {
106 // Prevent making instances from this "utilities" class
110 * Some "getter" for a configuration instance, making sure, it is unique
112 * @return $configurationInstance An instance of a FrameworkConfiguration class
114 public static function getConfigurationInstance () {
115 // Is the instance there?
116 if (is_null(self::$configurationInstance)) {
118 self::$configurationInstance = new FrameworkConfiguration();
122 return self::$configurationInstance;
126 * "Getter" to get response/request type from analysis of the system.
128 * @return $requestType Analyzed request type
130 public static function getRequestTypeFromSystem () {
131 // Default is console
132 $requestType = 'console';
134 // Is 'HTTP_HOST' set?
135 if (isset($_SERVER['HTTP_HOST'])) {
136 // Then it is a HTML response/request.
137 $requestType = 'html';
145 * Checks whether the given file/path is in open_basedir(). This does not
146 * gurantee that the file is actually readable and/or writeable. If you need
147 * such gurantee then please use isReadableFile() instead.
149 * @param $fileInstance An instance of a SplFileInfo class
150 * @return $isReachable Whether it is within open_basedir()
152 public static function isReachableFilePath (SplFileInfo $fileInstance) {
153 // Is not reachable by default
154 $isReachable = false;
156 // Get open_basedir parameter
157 $openBaseDir = trim(ini_get('open_basedir'));
160 if (!empty($openBaseDir)) {
162 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
163 // Check on existence
164 if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
168 // Abort lookup as it has been found in open_basedir
173 // If open_basedir is not set, all is allowed
182 * Checks whether the give file is within open_basedir() (done by
183 * isReachableFilePath()), is actually a file and is readable.
185 * @param $fileInstance An instance of a SplFileInfo class
186 * @return $isReadable Whether the file is readable (and therefor exists)
188 public static function isReadableFile (SplFileInfo $fileInstance) {
189 // Default is not readable
192 // Check if it is a file and readable
195 self::isReachableFilePath($fileInstance)
197 $fileInstance->isFile()
199 $fileInstance->isReadable()
208 * Loads given include file
210 * @param $fileInstance An instance of a SplFileInfo class
212 * @throws InvalidArgumentException If file was not found or not readable or deprecated
214 public static function loadInclude (SplFileInfo $fileInstance) {
216 //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
218 // Should be there ...
219 if (!self::isReadableFile($fileInstance)) {
221 throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
225 require_once $fileInstance->getPathname();
228 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
232 * Does the actual bootstrap
236 public static function doBootstrap () {
237 // Load basic include files to continue bootstrapping
238 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
239 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sclass_BaseFrameworkSystem.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
240 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sutils%sclass_StringUtils.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
241 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
242 self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
244 // Load global configuration
245 self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
249 * Initializes the framework by scanning for all framework-relevant
250 * classes, interfaces and exception. Then determine the request type and
251 * initialize a Requestable instance which will then contain all request
252 * parameter, also from CLI. Next step is to validate the application
257 public static function initFramework () {
259 * 1) Load class loader and scan framework classes, interfaces and
262 self::scanFrameworkClasses();
265 * 2) Determine the request type, console or web and store request and
266 * response here. This also initializes the request instance will
267 * all given parameters (see doc-tag for possible sources of
270 self::determineRequestType();
273 * 3) Now, that there are all request parameters being available, check
274 * if 'application' is supplied. If it is not found, abort execution, if
275 * found, continue below with next step.
277 self::validateApplicationParameter();
281 * Initializes the detected application. This may fail if required files
282 * are not found in the application's base path (not to be confused with
283 * 'application_base_path' which only points to /some/foo/application/.
287 public static function prepareApplication () {
288 // Configuration entry 'detected_app_name' must be set, get it here, including full path
289 $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
290 $fullPath = self::getConfigurationInstance()->getConfigEntry('detected_full_app_path');
293 * Now check and load all files, found deprecated files will throw a
294 * warning at the user.
296 foreach (self::$configAppIncludes as $fileName => $status) {
297 // Construct file instance
298 $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
300 // Determine if this file is wanted/readable/deprecated
301 if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
302 // Nope, required file cannot be found/read from
303 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
304 } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
305 // Found, not readable file
306 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
307 } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
308 // Not found but optional/deprecated file, skip it
312 // Is the file deprecated?
313 if ($status == 'deprecated') {
315 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);
317 // Skip loading deprecated file
322 self::loadInclude($fileInstance);
325 // Scan for application's classes, exceptions and interfaces
326 ClassLoader::scanApplicationClasses();
330 * Starts a fully initialized application, the class ApplicationHelper must
331 * be loaded at this point.
335 public static function startApplication () {
336 // Configuration entry 'detected_app_name' must be set, get it here
337 $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
339 // Is there an application helper instance?
340 $applicationInstance = call_user_func_array(
342 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
346 // Some sanity checks
347 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
348 // Something went wrong!
349 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.',
351 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper'
353 } elseif (!is_object($applicationInstance)) {
355 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is not an object (%s).',
357 gettype($applicationInstance)
359 } elseif (!($applicationInstance instanceof ManageableApplication)) {
361 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.',
366 // Init template engine
367 self::getResponseInstance()->initTemplateEngine($applicationInstance);
369 // Now call all methods in one go
370 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
372 //*NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
375 call_user_func(array($applicationInstance, $methodName));
380 * Initializes database instance, no need to double-call this method
384 public static function initDatabaseInstance () {
385 // Get application instance
386 $applicationInstance = ApplicationHelper::getSelfInstance();
388 // Is the database instance already set?
389 if (self::getDatabaseInstance() instanceof DatabaseConnector) {
390 // Yes, then abort here
391 throw new BadMethodCallException('Method called twice.');
394 // Initialize database layer
395 $databaseInstance = ObjectFactory::createObjectByConfiguredName(self::getConfigurationInstance()->getConfigEntry('database_type') . '_class');
397 // Prepare database instance
398 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
400 // Set it in application helper
401 self::setDatabaseInstance($connectionInstance);
405 * Detects the server address (SERVER_ADDR) and set it in configuration
407 * @return $serverAddress The detected server address
408 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
409 * @todo Have to check some more entries from $_SERVER here
411 public static function detectServerAddress () {
413 if (!isset(self::$serverAddress)) {
414 // Is it set in $_SERVER?
415 if (!empty($_SERVER['SERVER_ADDR'])) {
416 // Set it from $_SERVER
417 self::$serverAddress = $_SERVER['SERVER_ADDR'];
418 } elseif (isset($_SERVER['SERVER_NAME'])) {
419 // Resolve IP address
420 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
423 if ($serverIp === false) {
425 * Why is gethostbyname() returning the host name and not
426 * false as many other PHP functions are doing? ;-(
428 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
432 self::$serverAddress = $serverIp;
434 // Run auto-detecting through console tools lib
435 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
440 return self::$serverAddress;
444 * Setter for default time zone (must be correct!)
446 * @param $timezone The timezone string (e.g. Europe/Berlin)
447 * @return $success If timezone was accepted
448 * @throws NullPointerException If $timezone is NULL
449 * @throws InvalidArgumentException If $timezone is empty
451 public static function setDefaultTimezone ($timezone) {
453 if (is_null($timezone)) {
455 throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
456 } elseif (!is_string($timezone)) {
458 throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
459 } elseif ((is_string($timezone)) && (empty($timezone))) {
461 throw new InvalidArgumentException('timezone is empty');
468 * Set desired time zone to prevent date() and related functions to
469 * issue an E_WARNING.
471 $success = date_default_timezone_set($timezone);
478 * Checks whether HTTPS is set in $_SERVER
480 * @return $isset Whether HTTPS is set
481 * @todo Test more fields
483 public static function isHttpSecured () {
487 isset($_SERVER['HTTPS'])
489 strtolower($_SERVER['HTTPS']) == 'on'
493 isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
495 strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
502 * Dectect and return the base URL for all URLs and forms
504 * @return $baseUrl Detected base URL
506 public static function detectBaseUrl () {
507 // Initialize the URL
511 if (self::isHttpSecured()) {
512 // Add the >s< for HTTPS
516 // Construct the full URL and secure it against CSRF attacks
517 $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
524 * Detect safely and return the full domain where this script is installed
526 * @return $fullDomain The detected full domain
528 public static function detectDomain () {
529 // Full domain is localnet.invalid by default
530 $fullDomain = 'localnet.invalid';
532 // Is the server name there?
533 if (isset($_SERVER['SERVER_NAME'])) {
534 // Detect the full domain
535 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
543 * Detect safely the script path without trailing slash which is the glue
544 * between "http://your-domain.invalid/" and "script-name.php"
546 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
548 public static function detectScriptPath () {
552 // Is the scriptname set?
553 if (isset($_SERVER['SCRIPT_NAME'])) {
554 // Get dirname from it and replace back-slashes with slashes for lame OSes...
555 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
563 * 1) Loads class scanner and scans all framework's classes and interfaces.
564 * This method also registers the class loader's method autoLoad() for the
565 * SPL auto-load feature. Remember that you can register additional methods
566 * (not functions, please) for other libraries.
568 * Yes, I know about Composer, but I like to keep my class loader around.
569 * You can always use mine as long as your classes have a namespace
570 * according naming-convention: Vendor\Project\Group[\SubGroup]
574 private static function scanFrameworkClasses () {
575 // Include the class loader function
576 require self::getConfigurationInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
578 // Register auto-load function with the SPL
579 spl_autoload_register('Org\Mxchange\CoreFramework\Loader\ClassLoader::autoLoad');
581 // Scan for all framework classes, exceptions and interfaces
582 ClassLoader::scanFrameworkClasses();
586 * 2) Determines request/response type and stores the created
587 * request/response instances in this object for later usage.
591 private static function determineRequestType () {
592 // Determine request type
593 $request = self::getRequestTypeFromSystem();
594 $requestType = self::getRequestTypeFromSystem();
596 // Create a new request object
597 $requestInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
599 // Remember request instance here
600 self::setRequestInstance($requestInstance);
602 // Do we have another response?
603 if ($requestInstance->isRequestElementSet('request')) {
605 $request = strtolower($requestInstance->getRequestElement('request'));
606 $requestType = $request;
609 // ... and a new response object
610 $responseClass = sprintf('Org\Mxchange\CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
611 $responseInstance = ObjectFactory::createObjectByName($responseClass);
613 // Remember response instance here
614 self::setResponseInstance($responseInstance);
618 * 3) Validate parameter 'application' if it is set and the application is there.
622 private static function validateApplicationParameter () {
623 // Is the parameter set?
624 if (!self::getRequestInstance()->isRequestElementSet('app')) {
626 * Don't continue here, the application 'selector' is no longer
627 * supported and only existed as an idea to select the proper
628 * application (by user).
630 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
633 // Get it for local usage
634 $application = self::getRequestInstance()->getRequestElement('app');
636 // Secure it, by keeping out tags
637 $application = htmlentities(strip_tags($application), ENT_QUOTES);
639 // Secure it a little more with a reg.exp.
640 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
642 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
643 $applicationPath = sprintf(
645 self::getConfigurationInstance()->getConfigEntry('application_base_path'),
650 // Full path for application
651 // Is the path there? This secures a bit the parameter (from untrusted source).
652 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
653 // Not found or not readable
654 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
657 // Set the detected application's name and full path for later usage
658 self::getConfigurationInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
659 self::getConfigurationInstance()->setConfigEntry('detected_app_name' , $application);
663 * Getter for request instance
665 * @return $requestInstance An instance of a Requestable class
667 public static function getRequestInstance () {
668 return self::$requestInstance;
672 * Getter for response instance
674 * @return $responseInstance An instance of a Responseable class
676 public static function getResponseInstance () {
677 return self::$responseInstance;
681 * Setter for request instance
683 * @param $requestInstance An instance of a Requestable class
686 private static function setRequestInstance (Requestable $requestInstance) {
687 self::$requestInstance = $requestInstance;
691 * Setter for response instance
693 * @param $responseInstance An instance of a Responseable class
696 private static function setResponseInstance (Responseable $responseInstance) {
697 self::$responseInstance = $responseInstance;
701 * Setter for database instance
703 * @param $databaseInstance An instance of a DatabaseConnection class
706 public static function setDatabaseInstance (DatabaseConnection $databaseInstance) {
707 self::$databaseInstance = $databaseInstance;
711 * Getter for database instance
713 * @return $databaseInstance An instance of a DatabaseConnection class
715 public static function getDatabaseInstance () {
717 return self::$databaseInstance;