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