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