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