namespace CoreFramework\Bootstrap;
// Import framework stuff
+use CoreFramework\Configuration\FrameworkConfiguration;
+use CoreFramework\Connection\Database\DatabaseConnection;
+use CoreFramework\Connector\Database\DatabaseConnector;
use CoreFramework\EntryPoint\ApplicationEntryPoint;
+use CoreFramework\Factory\ObjectFactory;
+use CoreFramework\Helper\Application\ApplicationHelper;
+use CoreFramework\Loader\ClassLoader;
+use CoreFramework\Manager\ManageableApplication;
+use CoreFramework\Middleware\Debug\DebugMiddleware;
+use CoreFramework\Object\BaseFrameworkSystem;
+use CoreFramework\Registry\Registry;
+use CoreFramework\Request\Requestable;
+use CoreFramework\Response\Responseable;
+
+// Import SPL stuff
+use \BadMethodCallException;
/**
* A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
final class FrameworkBootstrap {
+
+ /**
+ * Instance of a Requestable class
+ */
+ private static $requestInstance = NULL;
+
+ /**
+ * Instance of a Responseable class
+ */
+ private static $responseInstance = NULL;
+
+ /*
+ * Includes applications may have. They will be tried in the given order,
+ * some will become soon deprecated.
+ */
+ private static $configAppIncludes = array(
+ // The ApplicationHelper class (required)
+ 'class_ApplicationHelper' => 'required',
+ // Some debugging stuff (optional but can be committed)
+ 'debug' => 'optional',
+ // Application's exception handler (optional but can be committed)
+ 'exceptions' => 'optional',
+ // Application's configuration file (committed, non-local specific)
+ 'config' => 'required',
+ // Local configuration file (optional, not committed, listed in .gitignore)
+ 'config-local' => 'optional',
+ // Application data (deprecated)
+ 'data' => 'deprecated',
+ // Application loader (deprecated)
+ 'loader' => 'deprecated',
+ // Application initializer (deprecated)
+ 'init' => 'deprecated',
+ // Application starter (deprecated)
+ 'starter' => 'deprecated',
+ );
+
/**
* Private constructor, no instance is needed from this class as only
* static methods exist.
// Prevent making instances from this "utilities" class
}
+ /**
+ * Getter for request instance
+ *
+ * @return $requestInstance An instance of a Requestable class
+ */
+ public static function getRequestInstance () {
+ return self::$requestInstance;
+ }
+
+ /**
+ * Getter for response instance
+ *
+ * @return $responseInstance An instance of a Responseable class
+ */
+ public static function getResponseInstance () {
+ return self::$responseInstance;
+ }
+
+ /**
+ * "Getter" to get response/request type from analysis of the system.
+ *
+ * @return $requestType Analyzed request type
+ */
+ public static function getRequestTypeFromSystem () {
+ // Default is console
+ $requestType = 'console';
+
+ // Is 'HTTP_HOST' set?
+ if (isset($_SERVER['HTTP_HOST'])) {
+ // Then it is a HTML response/request.
+ $requestType = 'html';
+ } // END - if
+
+ // Return it
+ return $requestType;
+ }
+
+ /**
+ * Checks whether the given file/path is in open_basedir(). This does not
+ * gurantee that the file is actually readable and/or writeable. If you need
+ * such gurantee then please use isReadableFile() instead.
+ *
+ * @param $filePathName Name of the file/path to be checked
+ * @return $isReachable Whether it is within open_basedir()
+ */
+ public static function isReachableFilePath ($filePathName) {
+ // Is not reachable by default
+ $isReachable = false;
+
+ // Get open_basedir parameter
+ $openBaseDir = ini_get('open_basedir');
+
+ // Is it set?
+ if (!empty($openBaseDir)) {
+ // Check all entries
+ foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
+ // Check on existence
+ if (substr($filePathName, 0, strlen($dir)) == $dir) {
+ // Is reachable
+ $isReachable = true;
+ } // END - if
+ } // END - foreach
+ } else {
+ // If open_basedir is not set, all is allowed
+ $isReachable = true;
+ }
+
+ // Return status
+ return $isReachable;
+ }
+
+ /**
+ * Checks whether the give file is within open_basedir() (done by
+ * isReachableFilePath()), is actually a file and is readable.
+ *
+ * @param $fileName Name of the file to be checked
+ * @return $isReadable Whether the file is readable (and therefor exists)
+ */
+ public static function isReadableFile ($fileName) {
+ // Default is not readable
+ $isReadable = false;
+
+ // Is within parameters, so check if it is a file and readable
+ $isReadable = (
+ (
+ self::isReachableFilePath($fileName)
+ ) && (
+ file_exists($fileName)
+ ) && (
+ is_file($fileName)
+ ) && (
+ is_readable($fileName)
+ ) && (
+ filesize($fileName) > 100
+ )
+ );
+
+ // Return status
+ return $isReadable;
+ }
+
+ /**
+ * Loads given include file
+ *
+ * @param $fqfn Include's FQFN
+ * @return void
+ * @throws InvalidArgumentException If $fqfn was not found or not readable or deprecated
+ */
+ public static function loadInclude ($fqfn) {
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
+
+ // Should be there ...
+ if (!self::isReadableFile($fqfn)) {
+ // Abort here
+ throw new InvalidArgumentException(sprintf('Cannot find fqfn=%s.', $fqfn));
+ } // END - if
+
+ // Load it
+ require $fqfn;
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
/**
* Does the actual bootstrap
*
*/
public static function doBootstrap () {
// Load basic include files to continue bootstrapping
- require ApplicationEntryPoint::detectFrameworkPath() . 'main/interfaces/class_FrameworkInterface.php';
- require ApplicationEntryPoint::detectFrameworkPath() . 'main/interfaces/registry/class_Registerable.php';
- require ApplicationEntryPoint::detectFrameworkPath() . 'config/class_FrameworkConfiguration.php';
+ self::loadInclude(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
+ self::loadInclude(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
+ self::loadInclude(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR));
+
+ // Load global configuration
+ self::loadInclude(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php'));
+ }
+
+ /**
+ * Initializes the framework by scanning for all framework-relevant
+ * classes, interfaces and exception. Then determine the request type and
+ * initialize a Requestable instance which will then contain all request
+ * parameter, also from CLI. Next step is to validate the application
+ * (very basic).
+ *
+ * @return void
+ */
+ public static function initFramework () {
+ /**
+ * 1) Load class loader and scan framework classes, interfaces and
+ * exceptions.
+ */
+ self::scanFrameworkClasses();
+
+ /*
+ * 2) Determine the request type, console or web and store request and
+ * response here. This also initializes the request instance will
+ * all given parameters (see doc-tag for possible sources of
+ * parameters).
+ */
+ self::determineRequestType();
+
+ /*
+ * 3) Now, that there are all request parameters being available, check
+ * if 'app' is supplied. If it is not found, abort execution, if
+ * found, continue below with next step.
+ */
+ self::validateApplicationParameter();
+ }
+
+ /**
+ * Initializes the detected application. This may fail if required files
+ * are not found in the application's base path (not to be confused with
+ * 'application_base_path' which only points to /some/foo/application/.
+ *
+ * @return void
+ */
+ public static function prepareApplication () {
+ // Configuration entry 'detected_app_name' must be set, get it here, including full path
+ $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
+ $fullPath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
+
+ /*
+ * Now check and load all files, found deprecated files will throw a
+ * warning at the user.
+ */
+ foreach (self::$configAppIncludes as $fileName => $status) {
+ // Construct FQFN
+ $fqfn = sprintf('%s%s.php', $fullPath, $fileName);
+
+ // Determine if this file is wanted/readable/deprecated
+ if (($status == 'required') && (!self::isReadableFile($fqfn))) {
+ // Nope, required file cannot be found/read from
+ ApplicationEntryPoint::app_exit(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileName));
+ } elseif ((file_exists($fqfn)) && (!is_readable($fqfn))) {
+ // Found, not readable file
+ ApplicationEntryPoint::app_exit(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileName, $application));
+ } elseif (($status != 'required') && (!self::isReadableFile($fqfn))) {
+ // Not found but optional/deprecated file, skip it
+ continue;
+ }
+
+ // Is the file deprecated?
+ if ($status == 'deprecated') {
+ // Issue warning
+ 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);
+
+ // Skip loading deprecated file
+ continue;
+ } // END - if
+
+ // Load it
+ self::loadInclude($fqfn);
+ } // END - foreach
+
+ // Scan for application's classes, exceptions and interfaces
+ ClassLoader::scanApplicationClasses();
+ }
+
+ /**
+ * Starts a fully initialized application, the class ApplicationHelper must
+ * be loaded at this point.
+ *
+ * @return void
+ */
+ public static function startApplication () {
+ // Configuration entry 'detected_app_name' must be set, get it here
+ $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
+
+ // Is there an application helper instance?
+ $applicationInstance = call_user_func_array(
+ array(
+ 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
+ ), array()
+ );
+
+ // Some sanity checks
+ if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
+ // Something went wrong!
+ ApplicationEntryPoint::app_exit(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.",
+ $application,
+ 'CoreFramework\Helper\Application\ApplicationHelper'
+ ));
+ } elseif (!is_object($applicationInstance)) {
+ // No object!
+ ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is not an object (%s).",
+ $application,
+ gettype($applicationInstance)
+ ));
+ } elseif (!($applicationInstance instanceof ManageableApplication)) {
+ // Missing interface
+ ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.",
+ $application
+ ));
+ }
+
+ // Set it in registry
+ Registry::getRegistry()->addInstance('app', $applicationInstance);
+
+ // Now call all methods in one go
+ foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
+ // Debug message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
+
+ // Call method
+ call_user_func(array($applicationInstance, $methodName));
+ } // END - if
+ }
+
+ /**
+ * Initializes database instance, no need to double-call this method
+ *
+ * @return void
+ */
+ public static function initDatabaseInstance () {
+ // Get application instance
+ $applicationInstance = ApplicationHelper::getSelfInstance();
+
+ // Is the database instance already set?
+ if ($applicationInstance instanceof DatabaseConnector) {
+ // Yes, then abort here
+ throw new BadMethodCallException('Method called twice.');
+ } // END - if
+
+ // Initialize database layer
+ $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
+
+ // Prepare database instance
+ $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
+
+ // Set it in application helper
+ $applicationInstance->setDatabaseInstance($connectionInstance);
+ }
+
+ /**
+ * 1) Loads class scanner and scans all framework's classes and interfaces.
+ * This method also registers the class loader's method autoLoad() for the
+ * SPL auto-load feature. Remember that you can register additional methods
+ * (not functions, please) for other libraries.
+ *
+ * Yes, I know about Composer, but I like to keep my class loader around.
+ * You can always use mine as long as your classes have a namespace
+ * according naming-convention: Vendor\Project\Group[\SubGroup]
+ *
+ * @return void
+ */
+ private static function scanFrameworkClasses () {
+ // Include the class loader function
+ require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
+
+ // Register auto-load function with the SPL
+ spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
+
+ // Scan for all framework classes, exceptions and interfaces
+ ClassLoader::scanFrameworkClasses();
+ }
+
+ /**
+ * 2) Determines request/response type and stores the created
+ * request/response instances in this object for later usage.
+ *
+ * @return void
+ */
+ private static function determineRequestType () {
+ // Determine request type
+ $request = self::getRequestTypeFromSystem();
+ $requestType = self::getRequestTypeFromSystem();
+
+ // Create a new request object
+ $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
+
+ // Remember request instance here
+ self::setRequestInstance($requestInstance);
+
+ // Do we have another response?
+ if ($requestInstance->isRequestElementSet('request')) {
+ // Then use it
+ $request = strtolower($requestInstance->getRequestElement('request'));
+ $requestType = $request;
+ } // END - if
+
+ // ... and a new response object
+ $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
+ $responseInstance = ObjectFactory::createObjectByName($responseClass);
- // Load main configuration
- require ApplicationEntryPoint::detectFrameworkPath() . 'config.inc.php';
+ // Remember response instance here
+ self::setResponseInstance($responseInstance);
}
/**
- * Parses all parameters, like $_GET, $_POST, $_COOKIE and also "emulated"
- * from command-line. Accepted CLI parameters are in following forms:
+ * 3) Validate parameter 'app' if it is set and the application is there.
*
- * --foo=bar - parameter 'foo' gets value "bar" (string)
- * --enable-foo=true - parameter 'enableFoo' gets value true (boolean)
- * --baz=123 - parameter 'baz' get value 123 (integer)
+ * @return void
+ */
+ private static function validateApplicationParameter () {
+ // Is the parameter set?
+ if (!self::getRequestInstance()->isRequestElementSet('app')) {
+ /*
+ * Don't continue here, the application 'selector' is no longer
+ * supported and only existed as an idea to select the proper
+ * application (by user).
+ */
+ ApplicationEntryPoint::app_exit('No application specified. Please provide a parameter "app" and retry.');
+ } // END - if
+
+ // Get it for local usage
+ $application = self::getRequestInstance()->getRequestElement('app');
+
+ // Secure it, by keeping out tags
+ $application = htmlentities(strip_tags($application), ENT_QUOTES);
+
+ // Secure it a little more with a reg.exp.
+ $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
+
+ // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
+ $applicationPath = sprintf(
+ '%s%s%s',
+ FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
+ $application,
+ DIRECTORY_SEPARATOR
+ );
+
+ // Full path for application
+ // Is the path there? This secures a bit the parameter (from untrusted source).
+ if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
+ // Not found or not readable
+ ApplicationEntryPoint::app_exit(sprintf('Application "%s" not found.', $application));
+ } // END - if
+
+ // Set the detected application's name and full path for later usage
+ FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
+ FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name' , $application);
+ }
+ /**
+ * Setter for request instance
*
- * The same also works without 2 dashes as it was possible before:
+ * @param $requestInstance An instance of a Requestable class
+ * @return void
+ */
+ private static function setRequestInstance (Requestable $requestInstance) {
+ self::$requestInstance = $requestInstance;
+ }
+
+ /**
+ * Setter for response instance
*
- * app=tests - launches application 'tests' (parameter 'app' gets string value "tests")
+ * @param $responseInstance An instance of a Responseable class
+ * @return void
*/
- public static function parseParameters () {
+ private static function setResponseInstance (Responseable $responseInstance) {
+ self::$responseInstance = $responseInstance;
}
}