X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=framework%2Fbootstrap%2Fclass_FrameworkBootstrap.php;h=c759f9416512e0e083272d894c8bbdcecd4eae8d;hb=b9bfbe86c031c9d83c3670602906df191a33ba2a;hp=000a2a9dde99952af94b2b053a5c7c4511d02883;hpb=dac90dee37db3dcdb64eba38b351df593f4e2bdb;p=core.git
diff --git a/framework/bootstrap/class_FrameworkBootstrap.php b/framework/bootstrap/class_FrameworkBootstrap.php
index 000a2a9d..c759f941 100644
--- a/framework/bootstrap/class_FrameworkBootstrap.php
+++ b/framework/bootstrap/class_FrameworkBootstrap.php
@@ -6,8 +6,10 @@ namespace CoreFramework\Bootstrap;
use CoreFramework\Configuration\FrameworkConfiguration;
use CoreFramework\Connection\Database\DatabaseConnection;
use CoreFramework\Connector\Database\DatabaseConnector;
+use CoreFramework\Console\Tools\ConsoleTools;
use CoreFramework\EntryPoint\ApplicationEntryPoint;
use CoreFramework\Factory\ObjectFactory;
+use CoreFramework\Generic\NullPointerException;
use CoreFramework\Helper\Application\ApplicationHelper;
use CoreFramework\Loader\ClassLoader;
use CoreFramework\Manager\ManageableApplication;
@@ -19,6 +21,8 @@ use CoreFramework\Response\Responseable;
// Import SPL stuff
use \BadMethodCallException;
+use \InvalidArgumentException;
+use \SplFileInfo;
/**
* A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
@@ -44,6 +48,11 @@ use \BadMethodCallException;
*/
final class FrameworkBootstrap {
+ /**
+ * Detected server address
+ */
+ private static $serverAddress = NULL;
+
/**
* Instance of a Requestable class
*/
@@ -129,24 +138,27 @@ final class FrameworkBootstrap {
* 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
+ * @param $fileInstance An instance of a SplFileInfo class
* @return $isReachable Whether it is within open_basedir()
*/
- public static function isReachableFilePath ($filePathName) {
+ public static function isReachableFilePath (SplFileInfo $fileInstance) {
// Is not reachable by default
$isReachable = false;
// Get open_basedir parameter
- $openBaseDir = ini_get('open_basedir');
+ $openBaseDir = trim(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) {
+ if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
// Is reachable
$isReachable = true;
+
+ // Abort lookup as it has been found in open_basedir
+ break;
} // END - if
} // END - foreach
} else {
@@ -162,25 +174,21 @@ final class FrameworkBootstrap {
* 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
+ * @param $fileInstance An instance of a SplFileInfo class
* @return $isReadable Whether the file is readable (and therefor exists)
*/
- public static function isReadableFile ($fileName) {
+ public static function isReadableFile (SplFileInfo $fileInstance) {
// Default is not readable
$isReadable = false;
- // Is within parameters, so check if it is a file and readable
+ // Check if it is a file and readable
$isReadable = (
(
- self::isReachableFilePath($fileName)
+ self::isReachableFilePath($fileInstance)
) && (
- file_exists($fileName)
+ $fileInstance->isFile()
) && (
- is_file($fileName)
- ) && (
- is_readable($fileName)
- ) && (
- filesize($fileName) > 100
+ $fileInstance->isReadable()
)
);
@@ -191,22 +199,22 @@ final class FrameworkBootstrap {
/**
* Loads given include file
*
- * @param $fqfn Include's FQFN
+ * @param $fileInstance An instance of a SplFileInfo class
* @return void
- * @throws InvalidArgumentException If $fqfn was not found or not readable or deprecated
+ * @throws InvalidArgumentException If file was not found or not readable or deprecated
*/
- public static function loadInclude ($fqfn) {
+ public static function loadInclude (SplFileInfo $fileInstance) {
// Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
// Should be there ...
- if (!self::isReadableFile($fqfn)) {
+ if (!self::isReadableFile($fileInstance)) {
// Abort here
- throw new InvalidArgumentException(sprintf('Cannot find fqfn=%s.', $fqfn));
+ throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
} // END - if
// Load it
- require $fqfn;
+ require $fileInstance->getPathname();
// Trace message
//* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
@@ -219,12 +227,12 @@ final class FrameworkBootstrap {
*/
public static function doBootstrap () {
// Load basic include files to continue bootstrapping
- 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));
+ self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
+ self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
+ self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
// Load global configuration
- self::loadInclude(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php'));
+ self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
}
/**
@@ -276,17 +284,17 @@ final class FrameworkBootstrap {
* warning at the user.
*/
foreach (self::$configAppIncludes as $fileName => $status) {
- // Construct FQFN
- $fqfn = sprintf('%s%s.php', $fullPath, $fileName);
+ // Construct file instance
+ $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
// Determine if this file is wanted/readable/deprecated
- if (($status == 'required') && (!self::isReadableFile($fqfn))) {
+ if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
// 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))) {
+ ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
+ } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
// 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))) {
+ ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
+ } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
// Not found but optional/deprecated file, skip it
continue;
}
@@ -301,7 +309,7 @@ final class FrameworkBootstrap {
} // END - if
// Load it
- self::loadInclude($fqfn);
+ self::loadInclude($fileInstance);
} // END - foreach
// Scan for application's classes, exceptions and interfaces
@@ -328,19 +336,19 @@ final class FrameworkBootstrap {
// Some sanity checks
if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
// Something went wrong!
- ApplicationEntryPoint::app_exit(sprintf("[Main:] The application %s could not be launched because the helper class %s is not loaded.",
+ ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application %s could not be launched because the helper class %s is not loaded.',
$application,
'CoreFramework\Helper\Application\ApplicationHelper'
));
} elseif (!is_object($applicationInstance)) {
// No object!
- ApplicationEntryPoint::app_exit(sprintf("[Main:] The application %s could not be launched because 'app' is not an object (%s).",
+ ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application %s 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 %s could not be launched because 'app' is lacking required interface ManageableApplication.",
+ ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application %s could not be launched because 'app' is lacking required interface ManageableApplication.',
$application
));
}
@@ -355,7 +363,7 @@ final class FrameworkBootstrap {
// Call method
call_user_func(array($applicationInstance, $methodName));
- } // END - if
+ } // END - foreach
}
/**
@@ -383,6 +391,150 @@ final class FrameworkBootstrap {
$applicationInstance->setDatabaseInstance($connectionInstance);
}
+ /**
+ * Detects the server address (SERVER_ADDR) and set it in configuration
+ *
+ * @return $serverAddress The detected server address
+ * @throws UnknownHostnameException If SERVER_NAME cannot be resolved to an IP address
+ * @todo Have to check some more entries from $_SERVER here
+ */
+ public static function detectServerAddress () {
+ // Is the entry set?
+ if (!isset(self::$serverAddress)) {
+ // Is it set in $_SERVER?
+ if (!empty($_SERVER['SERVER_ADDR'])) {
+ // Set it from $_SERVER
+ self::$serverAddress = $_SERVER['SERVER_ADDR'];
+ } elseif (isset($_SERVER['SERVER_NAME'])) {
+ // Resolve IP address
+ $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
+
+ // Is it valid?
+ if ($serverIp === false) {
+ /*
+ * Why is gethostbyname() returning the host name and not
+ * false as many other PHP functions are doing? ;-(
+ */
+ throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
+ } // END - if
+
+ // Al fine, set it
+ self::$serverAddress = $serverIp;
+ } else {
+ // Run auto-detecting through console tools lib
+ self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
+ }
+ } // END - if
+
+ // Return it
+ return self::$serverAddress;
+ }
+
+ /**
+ * Setter for default time zone (must be correct!)
+ *
+ * @param $timezone The timezone string (e.g. Europe/Berlin)
+ * @return $success If timezone was accepted
+ * @throws NullPointerException If $timezone is NULL
+ * @throws InvalidArgumentException If $timezone is empty
+ */
+ public static function setDefaultTimezone ($timezone) {
+ // Is it null?
+ if (is_null($timezone)) {
+ // Throw NPE
+ throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
+ } elseif (!is_string($timezone)) {
+ // Is not a string
+ throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
+ } elseif ((is_string($timezone)) && (empty($timezone))) {
+ // Entry is empty
+ throw new InvalidArgumentException('timezone is empty');
+ }
+
+ // Default success
+ $success = FALSE;
+
+ /*
+ * Set desired time zone to prevent date() and related functions to
+ * issue an E_WARNING.
+ */
+ $success = date_default_timezone_set($timezone);
+
+ // Return status
+ return $success;
+ }
+
+ /**
+ * Checks whether HTTPS is set in $_SERVER
+ *
+ * @return $isset Whether HTTPS is set
+ * @todo Test more fields
+ */
+ public static function isHttpSecured () {
+ return (isset($_SERVER['HTTPS']));
+ }
+
+ /**
+ * Dectect and return the base URL for all URLs and forms
+ *
+ * @return $baseUrl Detected base URL
+ */
+ public static function detectBaseUrl () {
+ // Initialize the URL
+ $protocol = 'http';
+
+ // Do we have HTTPS?
+ if (self::isHttpSecured()) {
+ // Add the >s< for HTTPS
+ $protocol = 's';
+ } // END - if
+
+ // Construct the full URL and secure it against CSRF attacks
+ $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
+
+ // Return the URL
+ return $baseUrl;
+ }
+
+ /**
+ * Detect safely and return the full domain where this script is installed
+ *
+ * @return $fullDomain The detected full domain
+ */
+ public static function detectDomain () {
+ // Full domain is localnet.invalid by default
+ $fullDomain = 'localnet.invalid';
+
+ // Is the server name there?
+ if (isset($_SERVER['SERVER_NAME'])) {
+ // Detect the full domain
+ $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
+ } // END - if
+
+ // Return it
+ return $fullDomain;
+ }
+
+ /**
+ * Detect safely the script path without trailing slash which is the glue
+ * between "http://your-domain.invalid/" and "script-name.php"
+ *
+ * @return $scriptPath The script path extracted from $_SERVER['SCRIPT_NAME']
+ */
+ public static function detectScriptPath () {
+ // Default is empty
+ $scriptPath = '';
+
+ // Is the scriptname set?
+ if (isset($_SERVER['SCRIPT_NAME'])) {
+ // Get dirname from it and replace back-slashes with slashes for lame OSes...
+ $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
+ } // END - if
+
+ // Return it
+ return $scriptPath;
+ }
+
/**
* 1) Loads class scanner and scans all framework's classes and interfaces.
* This method also registers the class loader's method autoLoad() for the
@@ -451,7 +603,7 @@ final class FrameworkBootstrap {
* 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.');
+ ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
} // END - if
// Get it for local usage
@@ -475,7 +627,7 @@ final class FrameworkBootstrap {
// 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));
+ ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
} // END - if
// Set the detected application's name and full path for later usage