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