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%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
232 self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
234 // Load global configuration
235 self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
239 * Initializes the framework by scanning for all framework-relevant
240 * classes, interfaces and exception. Then determine the request type and
241 * initialize a Requestable instance which will then contain all request
242 * parameter, also from CLI. Next step is to validate the application
247 public static function initFramework () {
249 * 1) Load class loader and scan framework classes, interfaces and
252 self::scanFrameworkClasses();
255 * 2) Determine the request type, console or web and store request and
256 * response here. This also initializes the request instance will
257 * all given parameters (see doc-tag for possible sources of
260 self::determineRequestType();
263 * 3) Now, that there are all request parameters being available, check
264 * if 'app' is supplied. If it is not found, abort execution, if
265 * found, continue below with next step.
267 self::validateApplicationParameter();
271 * Initializes the detected application. This may fail if required files
272 * are not found in the application's base path (not to be confused with
273 * 'application_base_path' which only points to /some/foo/application/.
277 public static function prepareApplication () {
278 // Configuration entry 'detected_app_name' must be set, get it here, including full path
279 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
280 $fullPath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
283 * Now check and load all files, found deprecated files will throw a
284 * warning at the user.
286 foreach (self::$configAppIncludes as $fileName => $status) {
287 // Construct file instance
288 $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
290 // Determine if this file is wanted/readable/deprecated
291 if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
292 // Nope, required file cannot be found/read from
293 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
294 } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
295 // Found, not readable file
296 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
297 } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
298 // Not found but optional/deprecated file, skip it
302 // Is the file deprecated?
303 if ($status == 'deprecated') {
305 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);
307 // Skip loading deprecated file
312 self::loadInclude($fileInstance);
315 // Scan for application's classes, exceptions and interfaces
316 ClassLoader::scanApplicationClasses();
320 * Starts a fully initialized application, the class ApplicationHelper must
321 * be loaded at this point.
325 public static function startApplication () {
326 // Configuration entry 'detected_app_name' must be set, get it here
327 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
329 // Is there an application helper instance?
330 $applicationInstance = call_user_func_array(
332 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
336 // Some sanity checks
337 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
338 // Something went wrong!
339 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.',
341 'CoreFramework\Helper\Application\ApplicationHelper'
343 } elseif (!is_object($applicationInstance)) {
345 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is not an object (%s).',
347 gettype($applicationInstance)
349 } elseif (!($applicationInstance instanceof ManageableApplication)) {
351 ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.',
356 // Set it in registry
357 Registry::getRegistry()->addInstance('app', $applicationInstance);
359 // Now call all methods in one go
360 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
362 //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
365 call_user_func(array($applicationInstance, $methodName));
370 * Initializes database instance, no need to double-call this method
374 public static function initDatabaseInstance () {
375 // Get application instance
376 $applicationInstance = ApplicationHelper::getSelfInstance();
378 // Is the database instance already set?
379 if ($applicationInstance instanceof DatabaseConnector) {
380 // Yes, then abort here
381 throw new BadMethodCallException('Method called twice.');
384 // Initialize database layer
385 $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
387 // Prepare database instance
388 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
390 // Set it in application helper
391 $applicationInstance->setDatabaseInstance($connectionInstance);
395 * Detects the server address (SERVER_ADDR) and set it in configuration
397 * @return $serverAddress The detected server address
398 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
399 * @todo Have to check some more entries from $_SERVER here
401 public static function detectServerAddress () {
403 if (!isset(self::$serverAddress)) {
404 // Is it set in $_SERVER?
405 if (!empty($_SERVER['SERVER_ADDR'])) {
406 // Set it from $_SERVER
407 self::$serverAddress = $_SERVER['SERVER_ADDR'];
408 } elseif (isset($_SERVER['SERVER_NAME'])) {
409 // Resolve IP address
410 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
413 if ($serverIp === false) {
415 * Why is gethostbyname() returning the host name and not
416 * false as many other PHP functions are doing? ;-(
418 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
422 self::$serverAddress = $serverIp;
424 // Run auto-detecting through console tools lib
425 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
430 return self::$serverAddress;
434 * Setter for default time zone (must be correct!)
436 * @param $timezone The timezone string (e.g. Europe/Berlin)
437 * @return $success If timezone was accepted
438 * @throws NullPointerException If $timezone is NULL
439 * @throws InvalidArgumentException If $timezone is empty
441 public static function setDefaultTimezone ($timezone) {
443 if (is_null($timezone)) {
445 throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
446 } elseif (!is_string($timezone)) {
448 throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
449 } elseif ((is_string($timezone)) && (empty($timezone))) {
451 throw new InvalidArgumentException('timezone is empty');
458 * Set desired time zone to prevent date() and related functions to
459 * issue an E_WARNING.
461 $success = date_default_timezone_set($timezone);
468 * Checks whether HTTPS is set in $_SERVER
470 * @return $isset Whether HTTPS is set
471 * @todo Test more fields
473 public static function isHttpSecured () {
474 return (isset($_SERVER['HTTPS']));
478 * Dectect and return the base URL for all URLs and forms
480 * @return $baseUrl Detected base URL
482 public static function detectBaseUrl () {
483 // Initialize the URL
487 if (self::isHttpSecured()) {
488 // Add the >s< for HTTPS
492 // Construct the full URL and secure it against CSRF attacks
493 $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
500 * Detect safely and return the full domain where this script is installed
502 * @return $fullDomain The detected full domain
504 public static function detectDomain () {
505 // Full domain is localnet.invalid by default
506 $fullDomain = 'localnet.invalid';
508 // Is the server name there?
509 if (isset($_SERVER['SERVER_NAME'])) {
510 // Detect the full domain
511 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
519 * Detect safely the script path without trailing slash which is the glue
520 * between "http://your-domain.invalid/" and "script-name.php"
522 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
524 public static function detectScriptPath () {
528 // Is the scriptname set?
529 if (isset($_SERVER['SCRIPT_NAME'])) {
530 // Get dirname from it and replace back-slashes with slashes for lame OSes...
531 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
539 * 1) Loads class scanner and scans all framework's classes and interfaces.
540 * This method also registers the class loader's method autoLoad() for the
541 * SPL auto-load feature. Remember that you can register additional methods
542 * (not functions, please) for other libraries.
544 * Yes, I know about Composer, but I like to keep my class loader around.
545 * You can always use mine as long as your classes have a namespace
546 * according naming-convention: Vendor\Project\Group[\SubGroup]
550 private static function scanFrameworkClasses () {
551 // Include the class loader function
552 require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
554 // Register auto-load function with the SPL
555 spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
557 // Scan for all framework classes, exceptions and interfaces
558 ClassLoader::scanFrameworkClasses();
562 * 2) Determines request/response type and stores the created
563 * request/response instances in this object for later usage.
567 private static function determineRequestType () {
568 // Determine request type
569 $request = self::getRequestTypeFromSystem();
570 $requestType = self::getRequestTypeFromSystem();
572 // Create a new request object
573 $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
575 // Remember request instance here
576 self::setRequestInstance($requestInstance);
578 // Do we have another response?
579 if ($requestInstance->isRequestElementSet('request')) {
581 $request = strtolower($requestInstance->getRequestElement('request'));
582 $requestType = $request;
585 // ... and a new response object
586 $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
587 $responseInstance = ObjectFactory::createObjectByName($responseClass);
589 // Remember response instance here
590 self::setResponseInstance($responseInstance);
594 * 3) Validate parameter 'app' if it is set and the application is there.
598 private static function validateApplicationParameter () {
599 // Is the parameter set?
600 if (!self::getRequestInstance()->isRequestElementSet('app')) {
602 * Don't continue here, the application 'selector' is no longer
603 * supported and only existed as an idea to select the proper
604 * application (by user).
606 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
609 // Get it for local usage
610 $application = self::getRequestInstance()->getRequestElement('app');
612 // Secure it, by keeping out tags
613 $application = htmlentities(strip_tags($application), ENT_QUOTES);
615 // Secure it a little more with a reg.exp.
616 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
618 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
619 $applicationPath = sprintf(
621 FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
626 // Full path for application
627 // Is the path there? This secures a bit the parameter (from untrusted source).
628 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
629 // Not found or not readable
630 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
633 // Set the detected application's name and full path for later usage
634 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
635 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name' , $application);
638 * Setter for request instance
640 * @param $requestInstance An instance of a Requestable class
643 private static function setRequestInstance (Requestable $requestInstance) {
644 self::$requestInstance = $requestInstance;
648 * Setter for response instance
650 * @param $responseInstance An instance of a Responseable class
653 private static function setResponseInstance (Responseable $responseInstance) {
654 self::$responseInstance = $responseInstance;