047bcf894dd20be7d21d0841d90863cab3a19e80
[core.git] / framework / bootstrap / class_FrameworkBootstrap.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Bootstrap;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
7 use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
8 use Org\Mxchange\CoreFramework\Connector\Database\DatabaseConnector;
9 use Org\Mxchange\CoreFramework\Console\Tools\ConsoleTools;
10 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
11 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
12 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
13 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
14 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
15 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
16 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
17 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
18 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
19 use Org\Mxchange\CoreFramework\Request\Requestable;
20 use Org\Mxchange\CoreFramework\Response\Responseable;
21
22 // Import SPL stuff
23 use \BadMethodCallException;
24 use \InvalidArgumentException;
25 use \SplFileInfo;
26
27 /**
28  * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
29  *
30  * @author              Roland Haeder <webmaster@ship-simu.org>
31  * @version             0.0.0
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
35  *
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.
40  *
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.
45  *
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/>.
48  */
49 final class FrameworkBootstrap {
50
51         /**
52          * Detected server address
53          */
54         private static $serverAddress = NULL;
55
56         /**
57          * Instance of a Requestable class
58          */
59         private static $requestInstance = NULL;
60
61         /**
62          * Instance of a Responseable class
63          */
64         private static $responseInstance = NULL;
65
66         /**
67          * Instance of a FrameworkConfiguration class
68          */
69         private static $configurationInstance = NULL;
70
71         /**
72          * Database instance
73          */
74         private static $databaseInstance = NULL;
75
76         /*
77          * Includes applications may have. They will be tried in the given order,
78          * some will become soon deprecated.
79          */
80         private static $configAppIncludes = array(
81                 // The ApplicationHelper class (required)
82                 'class_ApplicationHelper' => 'required',
83                 // Some debugging stuff (optional but can be committed)
84                 'debug'                   => 'optional',
85                 // Application's exception handler (optional but can be committed)
86                 'exceptions'              => 'optional',
87                 // Application's configuration file (committed, non-local specific)
88                 'config'                  => 'required',
89                 // Local configuration file (optional, not committed, listed in .gitignore)
90                 'config-local'            => 'optional',
91                 // Application data (deprecated)
92                 'data'                    => 'deprecated',
93                 // Application loader (deprecated)
94                 'loader'                  => 'deprecated',
95                 // Application initializer (deprecated)
96                 'init'                    => 'deprecated',
97                 // Application starter (deprecated)
98                 'starter'                 => 'deprecated',
99         );
100
101         /**
102          * Private constructor, no instance is needed from this class as only
103          * static methods exist.
104          */
105         private function __construct () {
106                 // Prevent making instances from this "utilities" class
107         }
108
109         /**
110          * Some "getter" for a configuration instance, making sure, it is unique
111          *
112          * @return      $configurationInstance  An instance of a FrameworkConfiguration class
113          */
114         public static function getConfigurationInstance () {
115                 // Is the instance there?
116                 if (is_null(self::$configurationInstance)) {
117                         // Init new instance
118                         self::$configurationInstance = new FrameworkConfiguration();
119                 } // END - if
120
121                 // Return it
122                 return self::$configurationInstance;
123         }
124
125         /**
126          * "Getter" to get response/request type from analysis of the system.
127          *
128          * @return      $requestType    Analyzed request type
129          */
130         public static function getRequestTypeFromSystem () {
131                 // Default is console
132                 $requestType = 'console';
133
134                 // Is 'HTTP_HOST' set?
135                 if (isset($_SERVER['HTTP_HOST'])) {
136                         // Then it is a HTML response/request.
137                         $requestType = 'html';
138                 } // END - if
139
140                 // Return it
141                 return $requestType;
142         }
143
144         /**
145          * Checks whether the given file/path is in open_basedir(). This does not
146          * gurantee that the file is actually readable and/or writeable. If you need
147          * such gurantee then please use isReadableFile() instead.
148          *
149          * @param       $fileInstance   An instance of a SplFileInfo class
150          * @return      $isReachable    Whether it is within open_basedir()
151          */
152         public static function isReachableFilePath (SplFileInfo $fileInstance) {
153                 // Is not reachable by default
154                 $isReachable = false;
155
156                 // Get open_basedir parameter
157                 $openBaseDir = trim(ini_get('open_basedir'));
158
159                 // Is it set?
160                 if (!empty($openBaseDir)) {
161                         // Check all entries
162                         foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
163                                 // Check on existence
164                                 if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
165                                         // Is reachable
166                                         $isReachable = true;
167
168                                         // Abort lookup as it has been found in open_basedir
169                                         break;
170                                 } // END - if
171                         } // END - foreach
172                 } else {
173                         // If open_basedir is not set, all is allowed
174                         $isReachable = true;
175                 }
176
177                 // Return status
178                 return $isReachable;
179         }
180
181         /**
182          * Checks whether the give file is within open_basedir() (done by
183          * isReachableFilePath()), is actually a file and is readable.
184          *
185          * @param       $fileInstance   An instance of a SplFileInfo class
186          * @return      $isReadable             Whether the file is readable (and therefor exists)
187          */
188         public static function isReadableFile (SplFileInfo $fileInstance) {
189                 // Default is not readable
190                 $isReadable = false;
191
192                 // Check if it is a file and readable
193                 $isReadable = (
194                         (
195                                 self::isReachableFilePath($fileInstance)
196                         ) && (
197                                 $fileInstance->isFile()
198                         ) && (
199                                 $fileInstance->isReadable()
200                         )
201                 );
202
203                 // Return status
204                 return $isReadable;
205         }
206
207         /**
208          * Loads given include file
209          *
210          * @param       $fileInstance   An instance of a SplFileInfo class
211          * @return      void
212          * @throws      InvalidArgumentException        If file was not found or not readable or deprecated
213          */
214         public static function loadInclude (SplFileInfo $fileInstance) {
215                 // Trace message
216                 //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
217
218                 // Should be there ...
219                 if (!self::isReadableFile($fileInstance)) {
220                         // Abort here
221                         throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
222                 } // END - if
223
224                 // Load it
225                 require_once $fileInstance->getPathname();
226
227                 // Trace message
228                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
229         }
230
231         /**
232          * Does the actual bootstrap
233          *
234          * @return      void
235          */
236         public static function doBootstrap () {
237                 // Load basic include files to continue bootstrapping
238                 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
239                 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sclass_BaseFrameworkSystem.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
240                 self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sutils%sclass_StringUtils.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
241                 self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
242                 self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
243
244                 // Load global configuration
245                 self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
246         }
247
248         /**
249          * Initializes the framework by scanning for all framework-relevant
250          * classes, interfaces and exception. Then determine the request type and
251          * initialize a Requestable instance which will then contain all request
252          * parameter, also from CLI. Next step is to validate the application
253          * (very basic).
254          *
255          * @return      void
256          */
257         public static function initFramework () {
258                 /**
259                  * 1) Load class loader and scan framework classes, interfaces and
260                  *    exceptions.
261                  */
262                 self::scanFrameworkClasses();
263
264                 /*
265                  * 2) Determine the request type, console or web and store request and
266                  *    response here. This also initializes the request instance will
267                  *    all given parameters (see doc-tag for possible sources of
268                  *    parameters).
269                  */
270                 self::determineRequestType();
271
272                 /*
273                  * 3) Now, that there are all request parameters being available, check
274                  *    if 'application' is supplied. If it is not found, abort execution, if
275                  *    found, continue below with next step.
276                  */
277                 self::validateApplicationParameter();
278         }
279
280         /**
281          * Initializes the detected application. This may fail if required files
282          * are not found in the application's base path (not to be confused with
283          * 'application_base_path' which only points to /some/foo/application/.
284          *
285          * @return      void
286          */
287         public static function prepareApplication () {
288                 // Configuration entry 'detected_app_name' must be set, get it here, including full path
289                 $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
290                 $fullPath    = self::getConfigurationInstance()->getConfigEntry('detected_full_app_path');
291
292                 /*
293                  * Now check and load all files, found deprecated files will throw a
294                  * warning at the user.
295                  */
296                 foreach (self::$configAppIncludes as $fileName => $status) {
297                         // Construct file instance
298                         $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
299
300                         // Determine if this file is wanted/readable/deprecated
301                         if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
302                                 // Nope, required file cannot be found/read from
303                                 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
304                         } elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
305                                 // Found, not readable file
306                                 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
307                         } elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
308                                 // Not found but optional/deprecated file, skip it
309                                 continue;
310                         }
311
312                         // Is the file deprecated?
313                         if ($status == 'deprecated') {
314                                 // Issue warning
315                                 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);
316
317                                 // Skip loading deprecated file
318                                 continue;
319                         } // END - if
320
321                         // Load it
322                         self::loadInclude($fileInstance);
323                 } // END - foreach
324
325                 // Scan for application's classes, exceptions and interfaces
326                 ClassLoader::scanApplicationClasses();
327         }
328
329         /**
330          * Starts a fully initialized application, the class ApplicationHelper must
331          * be loaded at this point.
332          *
333          * @return      void
334          */
335         public static function startApplication () {
336                 // Configuration entry 'detected_app_name' must be set, get it here
337                 $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
338
339                 // Is there an application helper instance?
340                 $applicationInstance = call_user_func_array(
341                         array(
342                                 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
343                         ), array()
344                 );
345
346                 // Some sanity checks
347                 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
348                         // Something went wrong!
349                         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.',
350                                 $application,
351                                 'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper'
352                         ));
353                 } elseif (!is_object($applicationInstance)) {
354                         // No object!
355                         ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because &#39;app&#39; is not an object (%s).',
356                                 $application,
357                                 gettype($applicationInstance)
358                         ));
359                 } elseif (!($applicationInstance instanceof ManageableApplication)) {
360                         // Missing interface
361                         ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because &#39;app&#39; is lacking required interface ManageableApplication.',
362                                 $application
363                         ));
364                 }
365
366                 // Now call all methods in one go
367                 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
368                         // Debug message
369                         //*NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
370
371                         // Call method
372                         call_user_func(array($applicationInstance, $methodName));
373                 } // END - foreach
374         }
375
376         /**
377          * Initializes database instance, no need to double-call this method
378          *
379          * @return      void
380          */
381         public static function initDatabaseInstance () {
382                 // Get application instance
383                 $applicationInstance = ApplicationHelper::getSelfInstance();
384
385                 // Is the database instance already set?
386                 if (self::getDatabaseInstance() instanceof DatabaseConnector) {
387                         // Yes, then abort here
388                         throw new BadMethodCallException('Method called twice.');
389                 } // END - if
390
391                 // Initialize database layer
392                 $databaseInstance = ObjectFactory::createObjectByConfiguredName(self::getConfigurationInstance()->getConfigEntry('database_type') . '_class');
393
394                 // Prepare database instance
395                 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
396
397                 // Set it in application helper
398                 self::setDatabaseInstance($connectionInstance);
399         }
400
401         /**
402          * Detects the server address (SERVER_ADDR) and set it in configuration
403          *
404          * @return      $serverAddress  The detected server address
405          * @throws      UnknownHostnameException        If SERVER_NAME cannot be resolved to an IP address
406          * @todo        Have to check some more entries from $_SERVER here
407          */
408         public static function detectServerAddress () {
409                 // Is the entry set?
410                 if (!isset(self::$serverAddress)) {
411                         // Is it set in $_SERVER?
412                         if (!empty($_SERVER['SERVER_ADDR'])) {
413                                 // Set it from $_SERVER
414                                 self::$serverAddress = $_SERVER['SERVER_ADDR'];
415                         } elseif (isset($_SERVER['SERVER_NAME'])) {
416                                 // Resolve IP address
417                                 $serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
418
419                                 // Is it valid?
420                                 if ($serverIp === false) {
421                                         /*
422                                          * Why is gethostbyname() returning the host name and not
423                                          * false as many other PHP functions are doing? ;-(
424                                          */
425                                         throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
426                                 } // END - if
427
428                                 // Al fine, set it
429                                 self::$serverAddress = $serverIp;
430                         } else {
431                                 // Run auto-detecting through console tools lib
432                                 self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
433                         }
434                 } // END - if
435
436                 // Return it
437                 return self::$serverAddress;
438         }
439
440         /**
441          * Setter for default time zone (must be correct!)
442          *
443          * @param       $timezone       The timezone string (e.g. Europe/Berlin)
444          * @return      $success        If timezone was accepted
445          * @throws      NullPointerException    If $timezone is NULL
446          * @throws      InvalidArgumentException        If $timezone is empty
447          */
448         public static function setDefaultTimezone ($timezone) {
449                 // Is it null?
450                 if (is_null($timezone)) {
451                         // Throw NPE
452                         throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
453                 } elseif (!is_string($timezone)) {
454                         // Is not a string
455                         throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
456                 } elseif ((is_string($timezone)) && (empty($timezone))) {
457                         // Entry is empty
458                         throw new InvalidArgumentException('timezone is empty');
459                 }
460
461                 // Default success
462                 $success = FALSE;
463
464                 /*
465                  * Set desired time zone to prevent date() and related functions to
466                  * issue an E_WARNING.
467                  */
468                 $success = date_default_timezone_set($timezone);
469
470                 // Return status
471                 return $success;
472         }
473
474         /**
475          * Checks whether HTTPS is set in $_SERVER
476          *
477          * @return      $isset  Whether HTTPS is set
478          * @todo        Test more fields
479          */
480         public static function isHttpSecured () {
481                 return (
482                         (
483                                 (
484                                         isset($_SERVER['HTTPS'])
485                                 ) && (
486                                         strtolower($_SERVER['HTTPS']) == 'on'
487                                 )
488                         ) || (
489                                 (
490                                         isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
491                                 ) && (
492                                         strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
493                                 )
494                         )
495                 );
496         }
497
498         /**
499          * Dectect and return the base URL for all URLs and forms
500          *
501          * @return      $baseUrl        Detected base URL
502          */
503         public static function detectBaseUrl () {
504                 // Initialize the URL
505                 $protocol = 'http';
506
507                 // Do we have HTTPS?
508                 if (self::isHttpSecured()) {
509                         // Add the >s< for HTTPS
510                         $protocol = 'https';
511                 } // END - if
512
513                 // Construct the full URL and secure it against CSRF attacks
514                 $baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
515
516                 // Return the URL
517                 return $baseUrl;
518         }
519
520         /**
521          * Detect safely and return the full domain where this script is installed
522          *
523          * @return      $fullDomain             The detected full domain
524          */
525         public static function detectDomain () {
526                 // Full domain is localnet.invalid by default
527                 $fullDomain = 'localnet.invalid';
528
529                 // Is the server name there?
530                 if (isset($_SERVER['SERVER_NAME'])) {
531                         // Detect the full domain
532                         $fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
533                 } // END - if
534
535                 // Return it
536                 return $fullDomain;
537         }
538
539         /**
540          * Detect safely the script path without trailing slash which is the glue
541          * between "http://your-domain.invalid/" and "script-name.php"
542          *
543          * @return      $scriptPath             The script path extracted from $_SERVER['SCRIPT_NAME']
544          */
545         public static function detectScriptPath () {
546                 // Default is empty
547                 $scriptPath = '';
548
549                 // Is the scriptname set?
550                 if (isset($_SERVER['SCRIPT_NAME'])) {
551                         // Get dirname from it and replace back-slashes with slashes for lame OSes...
552                         $scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
553                 } // END - if
554
555                 // Return it
556                 return $scriptPath;
557         }
558
559         /**
560          * 1) Loads class scanner and scans all framework's classes and interfaces.
561          * This method also registers the class loader's method autoLoad() for the
562          * SPL auto-load feature. Remember that you can register additional methods
563          * (not functions, please) for other libraries.
564          *
565          * Yes, I know about Composer, but I like to keep my class loader around.
566          * You can always use mine as long as your classes have a namespace
567          * according naming-convention: Vendor\Project\Group[\SubGroup]
568          *
569          * @return      void
570          */
571         private static function scanFrameworkClasses () {
572                 // Include the class loader function
573                 require self::getConfigurationInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
574
575                 // Register auto-load function with the SPL
576                 spl_autoload_register('Org\Mxchange\CoreFramework\Loader\ClassLoader::autoLoad');
577
578                 // Scan for all framework classes, exceptions and interfaces
579                 ClassLoader::scanFrameworkClasses();
580         }
581
582         /**
583          * 2) Determines request/response type and stores the created
584          * request/response instances in this object for later usage.
585          *
586          * @return      void
587          */
588         private static function determineRequestType () {
589                 // Determine request type
590                 $request = self::getRequestTypeFromSystem();
591                 $requestType = self::getRequestTypeFromSystem();
592
593                 // Create a new request object
594                 $requestInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
595
596                 // Remember request instance here
597                 self::setRequestInstance($requestInstance);
598
599                 // Do we have another response?
600                 if ($requestInstance->isRequestElementSet('request')) {
601                         // Then use it
602                         $request = strtolower($requestInstance->getRequestElement('request'));
603                         $requestType = $request;
604                 } // END - if
605
606                 // ... and a new response object
607                 $responseClass = sprintf('Org\Mxchange\CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
608                 $responseInstance = ObjectFactory::createObjectByName($responseClass);
609
610                 // Remember response instance here
611                 self::setResponseInstance($responseInstance);
612         }
613
614         /**
615          * 3) Validate parameter 'application' if it is set and the application is there.
616          *
617          * @return      void
618          */
619         private static function validateApplicationParameter () {
620                 // Is the parameter set?
621                 if (!self::getRequestInstance()->isRequestElementSet('app')) {
622                         /*
623                          * Don't continue here, the application 'selector' is no longer
624                          * supported and only existed as an idea to select the proper
625                          * application (by user).
626                          */
627                         ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
628                 } // END - if
629
630                 // Get it for local usage
631                 $application = self::getRequestInstance()->getRequestElement('app');
632
633                 // Secure it, by keeping out tags
634                 $application = htmlentities(strip_tags($application), ENT_QUOTES);
635
636                 // Secure it a little more with a reg.exp.
637                 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
638
639                 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
640                 $applicationPath = sprintf(
641                         '%s%s%s',
642                         self::getConfigurationInstance()->getConfigEntry('application_base_path'),
643                         $application,
644                         DIRECTORY_SEPARATOR
645                 );
646
647                 // Full path for application
648                 // Is the path there? This secures a bit the parameter (from untrusted source).
649                 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
650                         // Not found or not readable
651                         ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
652                 } // END - if
653
654                 // Set the detected application's name and full path for later usage
655                 self::getConfigurationInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
656                 self::getConfigurationInstance()->setConfigEntry('detected_app_name'     , $application);
657         }
658
659         /**
660          * Getter for request instance
661          *
662          * @return      $requestInstance        An instance of a Requestable class
663          */
664         public static function getRequestInstance () {
665                 return self::$requestInstance;
666         }
667
668         /**
669          * Getter for response instance
670          *
671          * @return      $responseInstance       An instance of a Responseable class
672          */
673         public static function getResponseInstance () {
674                 return self::$responseInstance;
675         }
676
677         /**
678          * Setter for request instance
679          *
680          * @param       $requestInstance        An instance of a Requestable class
681          * @return      void
682          */
683         private static function setRequestInstance (Requestable $requestInstance) {
684                 self::$requestInstance = $requestInstance;
685         }
686
687         /**
688          * Setter for response instance
689          *
690          * @param       $responseInstance       An instance of a Responseable class
691          * @return      void
692          */
693         private static function setResponseInstance (Responseable $responseInstance) {
694                 self::$responseInstance = $responseInstance;
695         }
696
697         /**
698          * Setter for database instance
699          *
700          * @param       $databaseInstance       An instance of a DatabaseConnection class
701          * @return      void
702          */
703         public static function setDatabaseInstance (DatabaseConnection $databaseInstance) {
704                 self::$databaseInstance = $databaseInstance;
705         }
706
707         /**
708          * Getter for database instance
709          *
710          * @return      $databaseInstance       An instance of a DatabaseConnection class
711          */
712         public static function getDatabaseInstance () {
713                 // Return instance
714                 return self::$databaseInstance;
715         }
716
717 }