3 namespace CoreFramework\Bootstrap;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Connection\Database\DatabaseConnection;
8 use CoreFramework\Connector\Database\DatabaseConnector;
9 use CoreFramework\Console\Tools\ConsoleTools;
10 use CoreFramework\EntryPoint\ApplicationEntryPoint;
11 use CoreFramework\Factory\ObjectFactory;
12 use CoreFramework\Generic\NullPointerException;
13 use CoreFramework\Helper\Application\ApplicationHelper;
14 use CoreFramework\Loader\ClassLoader;
15 use CoreFramework\Manager\ManageableApplication;
16 use CoreFramework\Middleware\Debug\DebugMiddleware;
17 use CoreFramework\Object\BaseFrameworkSystem;
18 use CoreFramework\Registry\Registry;
19 use CoreFramework\Request\Requestable;
20 use 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 - 2017 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 * Includes applications may have. They will be tried in the given order,
68 * some will become soon deprecated.
70 private static $configAppIncludes = array(
71 // The ApplicationHelper class (required)
72 'class_ApplicationHelper' => 'required',
73 // Some debugging stuff (optional but can be committed)
74 'debug' => 'optional',
75 // Application's exception handler (optional but can be committed)
76 'exceptions' => 'optional',
77 // Application's configuration file (committed, non-local specific)
78 'config' => 'required',
79 // Local configuration file (optional, not committed, listed in .gitignore)
80 'config-local' => 'optional',
81 // Application data (deprecated)
82 'data' => 'deprecated',
83 // Application loader (deprecated)
84 'loader' => 'deprecated',
85 // Application initializer (deprecated)
86 'init' => 'deprecated',
87 // Application starter (deprecated)
88 'starter' => 'deprecated',
92 * Private constructor, no instance is needed from this class as only
93 * static methods exist.
95 private function __construct () {
96 // Prevent making instances from this "utilities" class
100 * Getter for request instance
102 * @return $requestInstance An instance of a Requestable class
104 public static function getRequestInstance () {
105 return self::$requestInstance;
109 * Getter for response instance
111 * @return $responseInstance An instance of a Responseable class
113 public static function getResponseInstance () {
114 return self::$responseInstance;
118 * "Getter" to get response/request type from analysis of the system.
120 * @return $requestType Analyzed request type
122 public static function getRequestTypeFromSystem () {
123 // Default is console
124 $requestType = 'console';
126 // Is 'HTTP_HOST' set?
127 if (isset($_SERVER['HTTP_HOST'])) {
128 // Then it is a HTML response/request.
129 $requestType = 'html';
137 * Checks whether the given file/path is in open_basedir(). This does not
138 * gurantee that the file is actually readable and/or writeable. If you need
139 * such gurantee then please use isReadableFile() instead.
141 * @param $fileInstance An instance of a SplFileInfo class
142 * @return $isReachable Whether it is within open_basedir()
144 public static function isReachableFilePath (SplFileInfo $fileInstance) {
145 // Is not reachable by default
146 $isReachable = false;
148 // Get open_basedir parameter
149 $openBaseDir = trim(ini_get('open_basedir'));
152 if (!empty($openBaseDir)) {
154 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
155 // Check on existence
156 if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
160 // Abort lookup as it has been found in open_basedir
165 // If open_basedir is not set, all is allowed
174 * Checks whether the give file is within open_basedir() (done by
175 * isReachableFilePath()), is actually a file and is readable.
177 * @param $fileInstance An instance of a SplFileInfo class
178 * @return $isReadable Whether the file is readable (and therefor exists)
180 public static function isReadableFile (SplFileInfo $fileInstance) {
181 // Default is not readable
184 // Check if it is a file and readable
187 self::isReachableFilePath($fileInstance)
189 $fileInstance->isFile()
191 $fileInstance->isReadable()
200 * Loads given include file
202 * @param $fileInstance An instance of a SplFileInfo class
204 * @throws InvalidArgumentException If file was not found or not readable or deprecated
206 public static function loadInclude (SplFileInfo $fileInstance) {
208 //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
210 // Should be there ...
211 if (!self::isReadableFile($fileInstance)) {
213 throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
217 require $fileInstance->getPathname();
220 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
224 * Does the actual bootstrap
228 public static function doBootstrap () {
229 // Load basic include files to continue bootstrapping
230 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
231 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sclass_BaseFrameworkSystem.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
232 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
233 self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
235 // Load global configuration
236 self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
240 * Initializes the framework by scanning for all framework-relevant
241 * classes, interfaces and exception. Then determine the request type and
242 * initialize a Requestable instance which will then contain all request
243 * parameter, also from CLI. Next step is to validate the application
248 public static function initFramework () {
250 * 1) Load class loader and scan framework classes, interfaces and
253 self::scanFrameworkClasses();
256 * 2) Determine the request type, console or web and store request and
257 * response here. This also initializes the request instance will
258 * all given parameters (see doc-tag for possible sources of
261 self::determineRequestType();
264 * 3) Now, that there are all request parameters being available, check
265 * if 'app' is supplied. If it is not found, abort execution, if
266 * found, continue below with next step.
268 self::validateApplicationParameter();
272 * Initializes the detected application. This may fail if required files
273 * are not found in the application's base path (not to be confused with
274 * 'application_base_path' which only points to /some/foo/application/.
278 public static function prepareApplication () {
279 // Configuration entry 'detected_app_name' must be set, get it here, including full path
280 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
281 $fullPath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
284 * Now check and load all files, found deprecated files will throw a
285 * warning at the user.
287 foreach (self::$configAppIncludes as $fileName => $status) {
288 // Construct file instance
289 $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
291 // Determine if this file is wanted/readable/deprecated
292 if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
293 // Nope, required file cannot be found/read from
294 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
295 } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
296 // Found, not readable file
297 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
298 } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
299 // Not found but optional/deprecated file, skip it
303 // Is the file deprecated?
304 if ($status == 'deprecated') {
306 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);
308 // Skip loading deprecated file
313 self::loadInclude($fileInstance);
316 // Scan for application's classes, exceptions and interfaces
317 ClassLoader::scanApplicationClasses();
321 * Starts a fully initialized application, the class ApplicationHelper must
322 * be loaded at this point.
326 public static function startApplication () {
327 // Configuration entry 'detected_app_name' must be set, get it here
328 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
330 // Is there an application helper instance?
331 $applicationInstance = call_user_func_array(
333 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
337 // Some sanity checks
338 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
339 // Something went wrong!
340 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.',
342 'CoreFramework\Helper\Application\ApplicationHelper'
344 } elseif (!is_object($applicationInstance)) {
346 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is not an object (%s).',
348 gettype($applicationInstance)
350 } elseif (!($applicationInstance instanceof ManageableApplication)) {
352 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.',
357 // Set it in registry
358 Registry::getRegistry()->addInstance('app', $applicationInstance);
360 // Now call all methods in one go
361 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
363 //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
366 call_user_func(array($applicationInstance, $methodName));
371 * Initializes database instance, no need to double-call this method
375 public static function initDatabaseInstance () {
376 // Get application instance
377 $applicationInstance = ApplicationHelper::getSelfInstance();
379 // Is the database instance already set?
380 if ($applicationInstance instanceof DatabaseConnector) {
381 // Yes, then abort here
382 throw new BadMethodCallException('Method called twice.');
385 // Initialize database layer
386 $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
388 // Prepare database instance
389 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
391 // Set it in application helper
392 $applicationInstance->setDatabaseInstance($connectionInstance);
396 * Detects the server address (SERVER_ADDR) and set it in configuration
398 * @return $serverAddress The detected server address
399 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
400 * @todo Have to check some more entries from $_SERVER here
402 public static function detectServerAddress () {
404 if (!isset(self::$serverAddress)) {
405 // Is it set in $_SERVER?
406 if (!empty($_SERVER['SERVER_ADDR'])) {
407 // Set it from $_SERVER
408 self::$serverAddress = $_SERVER['SERVER_ADDR'];
409 } elseif (isset($_SERVER['SERVER_NAME'])) {
410 // Resolve IP address
411 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
414 if ($serverIp === false) {
416 * Why is gethostbyname() returning the host name and not
417 * false as many other PHP functions are doing? ;-(
419 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
423 self::$serverAddress = $serverIp;
425 // Run auto-detecting through console tools lib
426 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
431 return self::$serverAddress;
435 * Setter for default time zone (must be correct!)
437 * @param $timezone The timezone string (e.g. Europe/Berlin)
438 * @return $success If timezone was accepted
439 * @throws NullPointerException If $timezone is NULL
440 * @throws InvalidArgumentException If $timezone is empty
442 public static function setDefaultTimezone ($timezone) {
444 if (is_null($timezone)) {
446 throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
447 } elseif (!is_string($timezone)) {
449 throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
450 } elseif ((is_string($timezone)) && (empty($timezone))) {
452 throw new InvalidArgumentException('timezone is empty');
459 * Set desired time zone to prevent date() and related functions to
460 * issue an E_WARNING.
462 $success = date_default_timezone_set($timezone);
469 * Checks whether HTTPS is set in $_SERVER
471 * @return $isset Whether HTTPS is set
472 * @todo Test more fields
474 public static function isHttpSecured () {
475 return (isset($_SERVER['HTTPS']));
479 * Dectect and return the base URL for all URLs and forms
481 * @return $baseUrl Detected base URL
483 public static function detectBaseUrl () {
484 // Initialize the URL
488 if (self::isHttpSecured()) {
489 // Add the >s< for HTTPS
493 // Construct the full URL and secure it against CSRF attacks
494 $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
501 * Detect safely and return the full domain where this script is installed
503 * @return $fullDomain The detected full domain
505 public static function detectDomain () {
506 // Full domain is localnet.invalid by default
507 $fullDomain = 'localnet.invalid';
509 // Is the server name there?
510 if (isset($_SERVER['SERVER_NAME'])) {
511 // Detect the full domain
512 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
520 * Detect safely the script path without trailing slash which is the glue
521 * between "http://your-domain.invalid/" and "script-name.php"
523 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
525 public static function detectScriptPath () {
529 // Is the scriptname set?
530 if (isset($_SERVER['SCRIPT_NAME'])) {
531 // Get dirname from it and replace back-slashes with slashes for lame OSes...
532 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
540 * 1) Loads class scanner and scans all framework's classes and interfaces.
541 * This method also registers the class loader's method autoLoad() for the
542 * SPL auto-load feature. Remember that you can register additional methods
543 * (not functions, please) for other libraries.
545 * Yes, I know about Composer, but I like to keep my class loader around.
546 * You can always use mine as long as your classes have a namespace
547 * according naming-convention: Vendor\Project\Group[\SubGroup]
551 private static function scanFrameworkClasses () {
552 // Include the class loader function
553 require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
555 // Register auto-load function with the SPL
556 spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
558 // Scan for all framework classes, exceptions and interfaces
559 ClassLoader::scanFrameworkClasses();
563 * 2) Determines request/response type and stores the created
564 * request/response instances in this object for later usage.
568 private static function determineRequestType () {
569 // Determine request type
570 $request = self::getRequestTypeFromSystem();
571 $requestType = self::getRequestTypeFromSystem();
573 // Create a new request object
574 $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
576 // Remember request instance here
577 self::setRequestInstance($requestInstance);
579 // Do we have another response?
580 if ($requestInstance->isRequestElementSet('request')) {
582 $request = strtolower($requestInstance->getRequestElement('request'));
583 $requestType = $request;
586 // ... and a new response object
587 $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
588 $responseInstance = ObjectFactory::createObjectByName($responseClass);
590 // Remember response instance here
591 self::setResponseInstance($responseInstance);
595 * 3) Validate parameter 'app' if it is set and the application is there.
599 private static function validateApplicationParameter () {
600 // Is the parameter set?
601 if (!self::getRequestInstance()->isRequestElementSet('app')) {
603 * Don't continue here, the application 'selector' is no longer
604 * supported and only existed as an idea to select the proper
605 * application (by user).
607 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
610 // Get it for local usage
611 $application = self::getRequestInstance()->getRequestElement('app');
613 // Secure it, by keeping out tags
614 $application = htmlentities(strip_tags($application), ENT_QUOTES);
616 // Secure it a little more with a reg.exp.
617 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
619 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
620 $applicationPath = sprintf(
622 FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
627 // Full path for application
628 // Is the path there? This secures a bit the parameter (from untrusted source).
629 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
630 // Not found or not readable
631 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
634 // Set the detected application's name and full path for later usage
635 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
636 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name' , $application);
639 * Setter for request instance
641 * @param $requestInstance An instance of a Requestable class
644 private static function setRequestInstance (Requestable $requestInstance) {
645 self::$requestInstance = $requestInstance;
649 * Setter for response instance
651 * @param $responseInstance An instance of a Responseable class
654 private static function setResponseInstance (Responseable $responseInstance) {
655 self::$responseInstance = $responseInstance;