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