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