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;
27 * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
29 * @author Roland Haeder <webmaster@ship-simu.org>
31 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
32 * @license GNU GPL 3.0 or any newer version
33 * @link http://www.ship-simu.org
35 * This program is free software: you can redistribute it and/or modify
36 * it under the terms of the GNU General Public License as published by
37 * the Free Software Foundation, either version 3 of the License, or
38 * (at your option) any later version.
40 * This program is distributed in the hope that it will be useful,
41 * but WITHOUT ANY WARRANTY; without even the implied warranty of
42 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 * GNU General Public License for more details.
45 * You should have received a copy of the GNU General Public License
46 * along with this program. If not, see <http://www.gnu.org/licenses/>.
48 final class FrameworkBootstrap {
51 * Detected server address
53 private static $serverAddress = NULL;
56 * Instance of a Requestable class
58 private static $requestInstance = NULL;
61 * Instance of a Responseable class
63 private static $responseInstance = NULL;
66 * Includes applications may have. They will be tried in the given order,
67 * some will become soon deprecated.
69 private static $configAppIncludes = array(
70 // The ApplicationHelper class (required)
71 'class_ApplicationHelper' => 'required',
72 // Some debugging stuff (optional but can be committed)
73 'debug' => 'optional',
74 // Application's exception handler (optional but can be committed)
75 'exceptions' => 'optional',
76 // Application's configuration file (committed, non-local specific)
77 'config' => 'required',
78 // Local configuration file (optional, not committed, listed in .gitignore)
79 'config-local' => 'optional',
80 // Application data (deprecated)
81 'data' => 'deprecated',
82 // Application loader (deprecated)
83 'loader' => 'deprecated',
84 // Application initializer (deprecated)
85 'init' => 'deprecated',
86 // Application starter (deprecated)
87 'starter' => 'deprecated',
91 * Private constructor, no instance is needed from this class as only
92 * static methods exist.
94 private function __construct () {
95 // Prevent making instances from this "utilities" class
99 * Getter for request instance
101 * @return $requestInstance An instance of a Requestable class
103 public static function getRequestInstance () {
104 return self::$requestInstance;
108 * Getter for response instance
110 * @return $responseInstance An instance of a Responseable class
112 public static function getResponseInstance () {
113 return self::$responseInstance;
117 * "Getter" to get response/request type from analysis of the system.
119 * @return $requestType Analyzed request type
121 public static function getRequestTypeFromSystem () {
122 // Default is console
123 $requestType = 'console';
125 // Is 'HTTP_HOST' set?
126 if (isset($_SERVER['HTTP_HOST'])) {
127 // Then it is a HTML response/request.
128 $requestType = 'html';
136 * Checks whether the given file/path is in open_basedir(). This does not
137 * gurantee that the file is actually readable and/or writeable. If you need
138 * such gurantee then please use isReadableFile() instead.
140 * @param $filePathName Name of the file/path to be checked
141 * @return $isReachable Whether it is within open_basedir()
143 public static function isReachableFilePath ($filePathName) {
144 // Is not reachable by default
145 $isReachable = false;
147 // Get open_basedir parameter
148 $openBaseDir = ini_get('open_basedir');
151 if (!empty($openBaseDir)) {
153 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
154 // Check on existence
155 if (substr($filePathName, 0, strlen($dir)) == $dir) {
161 // If open_basedir is not set, all is allowed
170 * Checks whether the give file is within open_basedir() (done by
171 * isReachableFilePath()), is actually a file and is readable.
173 * @param $fileName Name of the file to be checked
174 * @return $isReadable Whether the file is readable (and therefor exists)
176 public static function isReadableFile ($fileName) {
177 // Default is not readable
180 // Is within parameters, so check if it is a file and readable
183 self::isReachableFilePath($fileName)
185 file_exists($fileName)
189 is_readable($fileName)
198 * Loads given include file
200 * @param $fqfn Include's FQFN
202 * @throws InvalidArgumentException If $fqfn was not found or not readable or deprecated
204 public static function loadInclude ($fqfn) {
206 //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
208 // Should be there ...
209 if (!self::isReadableFile($fqfn)) {
211 throw new InvalidArgumentException(sprintf('Cannot find fqfn=%s.', $fqfn));
218 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
222 * Does the actual bootstrap
226 public static function doBootstrap () {
227 // Load basic include files to continue bootstrapping
228 self::loadInclude(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
229 self::loadInclude(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
230 self::loadInclude(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR));
232 // Load global configuration
233 self::loadInclude(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php'));
237 * Initializes the framework by scanning for all framework-relevant
238 * classes, interfaces and exception. Then determine the request type and
239 * initialize a Requestable instance which will then contain all request
240 * parameter, also from CLI. Next step is to validate the application
245 public static function initFramework () {
247 * 1) Load class loader and scan framework classes, interfaces and
250 self::scanFrameworkClasses();
253 * 2) Determine the request type, console or web and store request and
254 * response here. This also initializes the request instance will
255 * all given parameters (see doc-tag for possible sources of
258 self::determineRequestType();
261 * 3) Now, that there are all request parameters being available, check
262 * if 'app' is supplied. If it is not found, abort execution, if
263 * found, continue below with next step.
265 self::validateApplicationParameter();
269 * Initializes the detected application. This may fail if required files
270 * are not found in the application's base path (not to be confused with
271 * 'application_base_path' which only points to /some/foo/application/.
275 public static function prepareApplication () {
276 // Configuration entry 'detected_app_name' must be set, get it here, including full path
277 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
278 $fullPath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
281 * Now check and load all files, found deprecated files will throw a
282 * warning at the user.
284 foreach (self::$configAppIncludes as $fileName => $status) {
286 $fqfn = sprintf('%s%s.php', $fullPath, $fileName);
288 // Determine if this file is wanted/readable/deprecated
289 if (($status == 'required') && (!self::isReadableFile($fqfn))) {
290 // Nope, required file cannot be found/read from
291 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileName));
292 } elseif ((file_exists($fqfn)) && (!is_readable($fqfn))) {
293 // Found, not readable file
294 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileName, $application));
295 } elseif (($status != 'required') && (!self::isReadableFile($fqfn))) {
296 // Not found but optional/deprecated file, skip it
300 // Is the file deprecated?
301 if ($status == 'deprecated') {
303 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);
305 // Skip loading deprecated file
310 self::loadInclude($fqfn);
313 // Scan for application's classes, exceptions and interfaces
314 ClassLoader::scanApplicationClasses();
318 * Starts a fully initialized application, the class ApplicationHelper must
319 * be loaded at this point.
323 public static function startApplication () {
324 // Configuration entry 'detected_app_name' must be set, get it here
325 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
327 // Is there an application helper instance?
328 $applicationInstance = call_user_func_array(
330 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
334 // Some sanity checks
335 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
336 // Something went wrong!
337 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.",
339 'CoreFramework\Helper\Application\ApplicationHelper'
341 } elseif (!is_object($applicationInstance)) {
343 ApplicationEntryPoint::exitApplication(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is not an object (%s).",
345 gettype($applicationInstance)
347 } elseif (!($applicationInstance instanceof ManageableApplication)) {
349 ApplicationEntryPoint::exitApplication(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.",
354 // Set it in registry
355 Registry::getRegistry()->addInstance('app', $applicationInstance);
357 // Now call all methods in one go
358 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
360 //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
363 call_user_func(array($applicationInstance, $methodName));
368 * Initializes database instance, no need to double-call this method
372 public static function initDatabaseInstance () {
373 // Get application instance
374 $applicationInstance = ApplicationHelper::getSelfInstance();
376 // Is the database instance already set?
377 if ($applicationInstance instanceof DatabaseConnector) {
378 // Yes, then abort here
379 throw new BadMethodCallException('Method called twice.');
382 // Initialize database layer
383 $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
385 // Prepare database instance
386 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
388 // Set it in application helper
389 $applicationInstance->setDatabaseInstance($connectionInstance);
393 * Detects the server address (SERVER_ADDR) and set it in configuration
395 * @return $serverAddress The detected server address
396 * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
397 * @todo Have to check some more entries from $_SERVER here
399 public static function detectServerAddress () {
401 if (!isset(self::$serverAddress)) {
402 // Is it set in $_SERVER?
403 if (!empty($_SERVER['SERVER_ADDR'])) {
404 // Set it from $_SERVER
405 self::$serverAddress = $_SERVER['SERVER_ADDR'];
406 } elseif (isset($_SERVER['SERVER_NAME'])) {
407 // Resolve IP address
408 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
411 if ($serverIp === false) {
413 * Why is gethostbyname() returning the host name and not
414 * false as many other PHP functions are doing? ;-(
416 throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
420 self::$serverAddress = $serverIp;
422 // Run auto-detecting through console tools lib
423 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
428 return self::$serverAddress;
432 * Setter for default time zone (must be correct!)
434 * @param $timezone The timezone string (e.g. Europe/Berlin)
435 * @return $success If timezone was accepted
436 * @throws NullPointerException If $timezone is NULL
437 * @throws InvalidArgumentException If $timezone is empty
439 public static function setDefaultTimezone ($timezone) {
441 if (is_null($timezone)) {
443 throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
444 } elseif (!is_string($timezone)) {
446 throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
447 } elseif ((is_string($timezone)) && (empty($timezone))) {
449 throw new InvalidArgumentException('timezone is empty');
456 * Set desired time zone to prevent date() and related functions to
457 * issue an E_WARNING.
459 $success = date_default_timezone_set($timezone);
466 * Detects the HTTPS flag
468 * @return $https The detected HTTPS flag or null if failed
470 public static function detectHttpSecured () {
475 if (self::isHttpSecured()) {
477 $https = $_SERVER['HTTPS'];
485 * Checks whether HTTPS is set in $_SERVER
487 * @return $isset Whether HTTPS is set
488 * @todo Test more fields
490 public static function isHttpSecured () {
491 return (isset($_SERVER['HTTPS']));
495 * Dectect and return the base URL for all URLs and forms
497 * @return $baseUrl Detected base URL
499 public static function detectBaseUrl () {
500 // Initialize the URL
504 if (self::isHttpSecured()) {
505 // Add the >s< for HTTPS
509 // Construct the full URL and secure it against CSRF attacks
510 $baseUrl = $protocol . '://' . self::detectDomain() . self::detectScriptPath();
517 * Detect safely and return the full domain where this script is installed
519 * @return $fullDomain The detected full domain
521 public static function detectDomain () {
522 // Full domain is localnet.invalid by default
523 $fullDomain = 'localnet.invalid';
525 // Is the server name there?
526 if (isset($_SERVER['SERVER_NAME'])) {
527 // Detect the full domain
528 $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
536 * Detect safely the script path without trailing slash which is the glue
537 * between "http://your-domain.invalid/" and "script-name.php"
539 * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
541 public static function detectScriptPath () {
545 // Is the scriptname set?
546 if (isset($_SERVER['SCRIPT_NAME'])) {
547 // Get dirname from it and replace back-slashes with slashes for lame OSes...
548 $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
556 * 1) Loads class scanner and scans all framework's classes and interfaces.
557 * This method also registers the class loader's method autoLoad() for the
558 * SPL auto-load feature. Remember that you can register additional methods
559 * (not functions, please) for other libraries.
561 * Yes, I know about Composer, but I like to keep my class loader around.
562 * You can always use mine as long as your classes have a namespace
563 * according naming-convention: Vendor\Project\Group[\SubGroup]
567 private static function scanFrameworkClasses () {
568 // Include the class loader function
569 require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
571 // Register auto-load function with the SPL
572 spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
574 // Scan for all framework classes, exceptions and interfaces
575 ClassLoader::scanFrameworkClasses();
579 * 2) Determines request/response type and stores the created
580 * request/response instances in this object for later usage.
584 private static function determineRequestType () {
585 // Determine request type
586 $request = self::getRequestTypeFromSystem();
587 $requestType = self::getRequestTypeFromSystem();
589 // Create a new request object
590 $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
592 // Remember request instance here
593 self::setRequestInstance($requestInstance);
595 // Do we have another response?
596 if ($requestInstance->isRequestElementSet('request')) {
598 $request = strtolower($requestInstance->getRequestElement('request'));
599 $requestType = $request;
602 // ... and a new response object
603 $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
604 $responseInstance = ObjectFactory::createObjectByName($responseClass);
606 // Remember response instance here
607 self::setResponseInstance($responseInstance);
611 * 3) Validate parameter 'app' if it is set and the application is there.
615 private static function validateApplicationParameter () {
616 // Is the parameter set?
617 if (!self::getRequestInstance()->isRequestElementSet('app')) {
619 * Don't continue here, the application 'selector' is no longer
620 * supported and only existed as an idea to select the proper
621 * application (by user).
623 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
626 // Get it for local usage
627 $application = self::getRequestInstance()->getRequestElement('app');
629 // Secure it, by keeping out tags
630 $application = htmlentities(strip_tags($application), ENT_QUOTES);
632 // Secure it a little more with a reg.exp.
633 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
635 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
636 $applicationPath = sprintf(
638 FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
643 // Full path for application
644 // Is the path there? This secures a bit the parameter (from untrusted source).
645 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
646 // Not found or not readable
647 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
650 // Set the detected application's name and full path for later usage
651 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
652 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name' , $application);
655 * Setter for request instance
657 * @param $requestInstance An instance of a Requestable class
660 private static function setRequestInstance (Requestable $requestInstance) {
661 self::$requestInstance = $requestInstance;
665 * Setter for response instance
667 * @param $responseInstance An instance of a Responseable class
670 private static function setResponseInstance (Responseable $responseInstance) {
671 self::$responseInstance = $responseInstance;