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\EntryPoint\ApplicationEntryPoint;
10 use CoreFramework\Factory\ObjectFactory;
11 use CoreFramework\Helper\Application\ApplicationHelper;
12 use CoreFramework\Loader\ClassLoader;
13 use CoreFramework\Manager\ManageableApplication;
14 use CoreFramework\Middleware\Debug\DebugMiddleware;
15 use CoreFramework\Object\BaseFrameworkSystem;
16 use CoreFramework\Registry\Registry;
17 use CoreFramework\Request\Requestable;
18 use CoreFramework\Response\Responseable;
21 use \BadMethodCallException;
24 * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
26 * @author Roland Haeder <webmaster@ship-simu.org>
28 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
29 * @license GNU GPL 3.0 or any newer version
30 * @link http://www.ship-simu.org
32 * This program is free software: you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation, either version 3 of the License, or
35 * (at your option) any later version.
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
42 * You should have received a copy of the GNU General Public License
43 * along with this program. If not, see <http://www.gnu.org/licenses/>.
45 final class FrameworkBootstrap {
48 * Instance of a Requestable class
50 private static $requestInstance = NULL;
53 * Instance of a Responseable class
55 private static $responseInstance = NULL;
58 * Includes applications may have. They will be tried in the given order,
59 * some will become soon deprecated.
61 private static $configAppIncludes = array(
62 // The ApplicationHelper class (required)
63 'class_ApplicationHelper' => 'required',
64 // Some debugging stuff (optional but can be committed)
65 'debug' => 'optional',
66 // Application's exception handler (optional but can be committed)
67 'exceptions' => 'optional',
68 // Application's configuration file (committed, non-local specific)
69 'config' => 'required',
70 // Local configuration file (optional, not committed, listed in .gitignore)
71 'config-local' => 'optional',
72 // Application data (deprecated)
73 'data' => 'deprecated',
74 // Application loader (deprecated)
75 'loader' => 'deprecated',
76 // Application initializer (deprecated)
77 'init' => 'deprecated',
78 // Application starter (deprecated)
79 'starter' => 'deprecated',
83 * Private constructor, no instance is needed from this class as only
84 * static methods exist.
86 private function __construct () {
87 // Prevent making instances from this "utilities" class
91 * Getter for request instance
93 * @return $requestInstance An instance of a Requestable class
95 public static function getRequestInstance () {
96 return self::$requestInstance;
100 * Getter for response instance
102 * @return $responseInstance An instance of a Responseable class
104 public static function getResponseInstance () {
105 return self::$responseInstance;
109 * "Getter" to get response/request type from analysis of the system.
111 * @return $requestType Analyzed request type
113 public static function getRequestTypeFromSystem () {
114 // Default is console
115 $requestType = 'console';
117 // Is 'HTTP_HOST' set?
118 if (isset($_SERVER['HTTP_HOST'])) {
119 // Then it is a HTML response/request.
120 $requestType = 'html';
128 * Checks whether the given file/path is in open_basedir(). This does not
129 * gurantee that the file is actually readable and/or writeable. If you need
130 * such gurantee then please use isReadableFile() instead.
132 * @param $filePathName Name of the file/path to be checked
133 * @return $isReachable Whether it is within open_basedir()
135 public static function isReachableFilePath ($filePathName) {
136 // Is not reachable by default
137 $isReachable = false;
139 // Get open_basedir parameter
140 $openBaseDir = ini_get('open_basedir');
143 if (!empty($openBaseDir)) {
145 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
146 // Check on existence
147 if (substr($filePathName, 0, strlen($dir)) == $dir) {
153 // If open_basedir is not set, all is allowed
162 * Checks whether the give file is within open_basedir() (done by
163 * isReachableFilePath()), is actually a file and is readable.
165 * @param $fileName Name of the file to be checked
166 * @return $isReadable Whether the file is readable (and therefor exists)
168 public static function isReadableFile ($fileName) {
169 // Default is not readable
172 // Is within parameters, so check if it is a file and readable
175 self::isReachableFilePath($fileName)
177 file_exists($fileName)
181 is_readable($fileName)
183 filesize($fileName) > 100
192 * Loads given include file
194 * @param $fqfn Include's FQFN
196 * @throws InvalidArgumentException If $fqfn was not found or not readable or deprecated
198 public static function loadInclude ($fqfn) {
200 //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
202 // Should be there ...
203 if (!self::isReadableFile($fqfn)) {
205 throw new InvalidArgumentException(sprintf('Cannot find fqfn=%s.', $fqfn));
212 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
216 * Does the actual bootstrap
220 public static function doBootstrap () {
221 // Load basic include files to continue bootstrapping
222 self::loadInclude(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
223 self::loadInclude(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
224 self::loadInclude(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR));
226 // Load global configuration
227 self::loadInclude(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php'));
231 * Initializes the framework by scanning for all framework-relevant
232 * classes, interfaces and exception. Then determine the request type and
233 * initialize a Requestable instance which will then contain all request
234 * parameter, also from CLI. Next step is to validate the application
239 public static function initFramework () {
241 * 1) Load class loader and scan framework classes, interfaces and
244 self::scanFrameworkClasses();
247 * 2) Determine the request type, console or web and store request and
248 * response here. This also initializes the request instance will
249 * all given parameters (see doc-tag for possible sources of
252 self::determineRequestType();
255 * 3) Now, that there are all request parameters being available, check
256 * if 'app' is supplied. If it is not found, abort execution, if
257 * found, continue below with next step.
259 self::validateApplicationParameter();
263 * Initializes the detected application. This may fail if required files
264 * are not found in the application's base path (not to be confused with
265 * 'application_base_path' which only points to /some/foo/application/.
269 public static function prepareApplication () {
270 // Configuration entry 'detected_app_name' must be set, get it here, including full path
271 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
272 $fullPath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
275 * Now check and load all files, found deprecated files will throw a
276 * warning at the user.
278 foreach (self::$configAppIncludes as $fileName => $status) {
280 $fqfn = sprintf('%s%s.php', $fullPath, $fileName);
282 // Determine if this file is wanted/readable/deprecated
283 if (($status == 'required') && (!self::isReadableFile($fqfn))) {
284 // Nope, required file cannot be found/read from
285 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileName));
286 } elseif ((file_exists($fqfn)) && (!is_readable($fqfn))) {
287 // Found, not readable file
288 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileName, $application));
289 } elseif (($status != 'required') && (!self::isReadableFile($fqfn))) {
290 // Not found but optional/deprecated file, skip it
294 // Is the file deprecated?
295 if ($status == 'deprecated') {
297 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);
299 // Skip loading deprecated file
304 self::loadInclude($fqfn);
307 // Scan for application's classes, exceptions and interfaces
308 ClassLoader::scanApplicationClasses();
312 * Starts a fully initialized application, the class ApplicationHelper must
313 * be loaded at this point.
317 public static function startApplication () {
318 // Configuration entry 'detected_app_name' must be set, get it here
319 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
321 // Is there an application helper instance?
322 $applicationInstance = call_user_func_array(
324 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
328 // Some sanity checks
329 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
330 // Something went wrong!
331 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.",
333 'CoreFramework\Helper\Application\ApplicationHelper'
335 } elseif (!is_object($applicationInstance)) {
337 ApplicationEntryPoint::exitApplication(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is not an object (%s).",
339 gettype($applicationInstance)
341 } elseif (!($applicationInstance instanceof ManageableApplication)) {
343 ApplicationEntryPoint::exitApplication(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.",
348 // Set it in registry
349 Registry::getRegistry()->addInstance('app', $applicationInstance);
351 // Now call all methods in one go
352 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
354 //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
357 call_user_func(array($applicationInstance, $methodName));
362 * Initializes database instance, no need to double-call this method
366 public static function initDatabaseInstance () {
367 // Get application instance
368 $applicationInstance = ApplicationHelper::getSelfInstance();
370 // Is the database instance already set?
371 if ($applicationInstance instanceof DatabaseConnector) {
372 // Yes, then abort here
373 throw new BadMethodCallException('Method called twice.');
376 // Initialize database layer
377 $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
379 // Prepare database instance
380 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
382 // Set it in application helper
383 $applicationInstance->setDatabaseInstance($connectionInstance);
387 * 1) Loads class scanner and scans all framework's classes and interfaces.
388 * This method also registers the class loader's method autoLoad() for the
389 * SPL auto-load feature. Remember that you can register additional methods
390 * (not functions, please) for other libraries.
392 * Yes, I know about Composer, but I like to keep my class loader around.
393 * You can always use mine as long as your classes have a namespace
394 * according naming-convention: Vendor\Project\Group[\SubGroup]
398 private static function scanFrameworkClasses () {
399 // Include the class loader function
400 require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
402 // Register auto-load function with the SPL
403 spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
405 // Scan for all framework classes, exceptions and interfaces
406 ClassLoader::scanFrameworkClasses();
410 * 2) Determines request/response type and stores the created
411 * request/response instances in this object for later usage.
415 private static function determineRequestType () {
416 // Determine request type
417 $request = self::getRequestTypeFromSystem();
418 $requestType = self::getRequestTypeFromSystem();
420 // Create a new request object
421 $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
423 // Remember request instance here
424 self::setRequestInstance($requestInstance);
426 // Do we have another response?
427 if ($requestInstance->isRequestElementSet('request')) {
429 $request = strtolower($requestInstance->getRequestElement('request'));
430 $requestType = $request;
433 // ... and a new response object
434 $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
435 $responseInstance = ObjectFactory::createObjectByName($responseClass);
437 // Remember response instance here
438 self::setResponseInstance($responseInstance);
442 * 3) Validate parameter 'app' if it is set and the application is there.
446 private static function validateApplicationParameter () {
447 // Is the parameter set?
448 if (!self::getRequestInstance()->isRequestElementSet('app')) {
450 * Don't continue here, the application 'selector' is no longer
451 * supported and only existed as an idea to select the proper
452 * application (by user).
454 ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
457 // Get it for local usage
458 $application = self::getRequestInstance()->getRequestElement('app');
460 // Secure it, by keeping out tags
461 $application = htmlentities(strip_tags($application), ENT_QUOTES);
463 // Secure it a little more with a reg.exp.
464 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
466 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
467 $applicationPath = sprintf(
469 FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
474 // Full path for application
475 // Is the path there? This secures a bit the parameter (from untrusted source).
476 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
477 // Not found or not readable
478 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
481 // Set the detected application's name and full path for later usage
482 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
483 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name' , $application);
486 * Setter for request instance
488 * @param $requestInstance An instance of a Requestable class
491 private static function setRequestInstance (Requestable $requestInstance) {
492 self::$requestInstance = $requestInstance;
496 * Setter for response instance
498 * @param $responseInstance An instance of a Responseable class
501 private static function setResponseInstance (Responseable $responseInstance) {
502 self::$responseInstance = $responseInstance;