000a2a9dde99952af94b2b053a5c7c4511d02883
[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\EntryPoint\ApplicationEntryPoint;
10 use CoreFramework\Factory\ObjectFactory;
11 use CoreFramework\Helper\Application\ApplicationHelper;
12 use CoreFramework\Loader\ClassLoader;
13 use CoreFramework\Manager\ManageableApplication;
14 use CoreFramework\Middleware\Debug\DebugMiddleware;
15 use CoreFramework\Object\BaseFrameworkSystem;
16 use CoreFramework\Registry\Registry;
17 use CoreFramework\Request\Requestable;
18 use CoreFramework\Response\Responseable;
19
20 // Import SPL stuff
21 use \BadMethodCallException;
22
23 /**
24  * A framework-bootstrap class which helps the frameworks to bootstrap ... ;-)
25  *
26  * @author              Roland Haeder <webmaster@ship-simu.org>
27  * @version             0.0.0
28  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
29  * @license             GNU GPL 3.0 or any newer version
30  * @link                http://www.ship-simu.org
31  *
32  * This program is free software: you can redistribute it and/or modify
33  * it under the terms of the GNU General Public License as published by
34  * the Free Software Foundation, either version 3 of the License, or
35  * (at your option) any later version.
36  *
37  * This program is distributed in the hope that it will be useful,
38  * but WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40  * GNU General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License
43  * along with this program. If not, see <http://www.gnu.org/licenses/>.
44  */
45 final class FrameworkBootstrap {
46
47         /**
48          * Instance of a Requestable class
49          */
50         private static $requestInstance = NULL;
51
52         /**
53          * Instance of a Responseable class
54          */
55         private static $responseInstance = NULL;
56
57         /*
58          * Includes applications may have. They will be tried in the given order,
59          * some will become soon deprecated.
60          */
61         private static $configAppIncludes = array(
62                 // The ApplicationHelper class (required)
63                 'class_ApplicationHelper' => 'required',
64                 // Some debugging stuff (optional but can be committed)
65                 'debug'                   => 'optional',
66                 // Application's exception handler (optional but can be committed)
67                 'exceptions'              => 'optional',
68                 // Application's configuration file (committed, non-local specific)
69                 'config'                  => 'required',
70                 // Local configuration file (optional, not committed, listed in .gitignore)
71                 'config-local'            => 'optional',
72                 // Application data (deprecated)
73                 'data'                    => 'deprecated',
74                 // Application loader (deprecated)
75                 'loader'                  => 'deprecated',
76                 // Application initializer (deprecated)
77                 'init'                    => 'deprecated',
78                 // Application starter (deprecated)
79                 'starter'                 => 'deprecated',
80         );
81
82         /**
83          * Private constructor, no instance is needed from this class as only
84          * static methods exist.
85          */
86         private function __construct () {
87                 // Prevent making instances from this "utilities" class
88         }
89
90         /**
91          * Getter for request instance
92          *
93          * @return      $requestInstance        An instance of a Requestable class
94          */
95         public static function getRequestInstance () {
96                 return self::$requestInstance;
97         }
98
99         /**
100          * Getter for response instance
101          *
102          * @return      $responseInstance       An instance of a Responseable class
103          */
104         public static function getResponseInstance () {
105                 return self::$responseInstance;
106         }
107
108         /**
109          * "Getter" to get response/request type from analysis of the system.
110          *
111          * @return      $requestType    Analyzed request type
112          */
113         public static function getRequestTypeFromSystem () {
114                 // Default is console
115                 $requestType = 'console';
116
117                 // Is 'HTTP_HOST' set?
118                 if (isset($_SERVER['HTTP_HOST'])) {
119                         // Then it is a HTML response/request.
120                         $requestType = 'html';
121                 } // END - if
122
123                 // Return it
124                 return $requestType;
125         }
126
127         /**
128          * Checks whether the given file/path is in open_basedir(). This does not
129          * gurantee that the file is actually readable and/or writeable. If you need
130          * such gurantee then please use isReadableFile() instead.
131          *
132          * @param       $filePathName   Name of the file/path to be checked
133          * @return      $isReachable    Whether it is within open_basedir()
134          */
135         public static function isReachableFilePath ($filePathName) {
136                 // Is not reachable by default
137                 $isReachable = false;
138
139                 // Get open_basedir parameter
140                 $openBaseDir = ini_get('open_basedir');
141
142                 // Is it set?
143                 if (!empty($openBaseDir)) {
144                         // Check all entries
145                         foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
146                                 // Check on existence
147                                 if (substr($filePathName, 0, strlen($dir)) == $dir) {
148                                         // Is reachable
149                                         $isReachable = true;
150                                 } // END - if
151                         } // END - foreach
152                 } else {
153                         // If open_basedir is not set, all is allowed
154                         $isReachable = true;
155                 }
156
157                 // Return status
158                 return $isReachable;
159         }
160
161         /**
162          * Checks whether the give file is within open_basedir() (done by
163          * isReachableFilePath()), is actually a file and is readable.
164          *
165          * @param       $fileName               Name of the file to be checked
166          * @return      $isReadable             Whether the file is readable (and therefor exists)
167          */
168         public static function isReadableFile ($fileName) {
169                 // Default is not readable
170                 $isReadable = false;
171
172                 // Is within parameters, so check if it is a file and readable
173                 $isReadable = (
174                         (
175                                 self::isReachableFilePath($fileName)
176                         ) && (
177                                 file_exists($fileName)
178                         ) && (
179                                 is_file($fileName)
180                         ) && (
181                                 is_readable($fileName)
182                         ) && (
183                                 filesize($fileName) > 100
184                         )
185                 );
186
187                 // Return status
188                 return $isReadable;
189         }
190
191         /**
192          * Loads given include file
193          *
194          * @param       $fqfn   Include's FQFN
195          * @return      void
196          * @throws      InvalidArgumentException        If $fqfn was not found or not readable or deprecated
197          */
198         public static function loadInclude ($fqfn) {
199                 // Trace message
200                 //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
201
202                 // Should be there ...
203                 if (!self::isReadableFile($fqfn)) {
204                         // Abort here
205                         throw new InvalidArgumentException(sprintf('Cannot find fqfn=%s.', $fqfn));
206                 } // END - if
207
208                 // Load it
209                 require $fqfn;
210
211                 // Trace message
212                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
213         }
214
215         /**
216          * Does the actual bootstrap
217          *
218          * @return      void
219          */
220         public static function doBootstrap () {
221                 // Load basic include files to continue bootstrapping
222                 self::loadInclude(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
223                 self::loadInclude(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
224                 self::loadInclude(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR));
225
226                 // Load global configuration
227                 self::loadInclude(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php'));
228         }
229
230         /**
231          * Initializes the framework by scanning for all framework-relevant
232          * classes, interfaces and exception. Then determine the request type and
233          * initialize a Requestable instance which will then contain all request
234          * parameter, also from CLI. Next step is to validate the application
235          * (very basic).
236          *
237          * @return      void
238          */
239         public static function initFramework () {
240                 /**
241                  * 1) Load class loader and scan framework classes, interfaces and
242                  *    exceptions.
243                  */
244                 self::scanFrameworkClasses();
245
246                 /*
247                  * 2) Determine the request type, console or web and store request and
248                  *    response here. This also initializes the request instance will
249                  *    all given parameters (see doc-tag for possible sources of
250                  *    parameters).
251                  */
252                 self::determineRequestType();
253
254                 /*
255                  * 3) Now, that there are all request parameters being available, check
256                  *    if 'app' is supplied. If it is not found, abort execution, if
257                  *    found, continue below with next step.
258                  */
259                 self::validateApplicationParameter();
260         }
261
262         /**
263          * Initializes the detected application. This may fail if required files
264          * are not found in the application's base path (not to be confused with
265          * 'application_base_path' which only points to /some/foo/application/.
266          *
267          * @return      void
268          */
269         public static function prepareApplication () {
270                 // Configuration entry 'detected_app_name' must be set, get it here, including full path
271                 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
272                 $fullPath    = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
273
274                 /*
275                  * Now check and load all files, found deprecated files will throw a
276                  * warning at the user.
277                  */
278                 foreach (self::$configAppIncludes as $fileName => $status) {
279                         // Construct FQFN
280                         $fqfn = sprintf('%s%s.php', $fullPath, $fileName);
281
282                         // Determine if this file is wanted/readable/deprecated
283                         if (($status == 'required') && (!self::isReadableFile($fqfn))) {
284                                 // Nope, required file cannot be found/read from
285                                 ApplicationEntryPoint::app_exit(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileName));
286                         } elseif ((file_exists($fqfn)) && (!is_readable($fqfn))) {
287                                 // Found, not readable file
288                                 ApplicationEntryPoint::app_exit(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileName, $application));
289                         } elseif (($status != 'required') && (!self::isReadableFile($fqfn))) {
290                                 // Not found but optional/deprecated file, skip it
291                                 continue;
292                         }
293
294                         // Is the file deprecated?
295                         if ($status == 'deprecated') {
296                                 // Issue warning
297                                 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);
298
299                                 // Skip loading deprecated file
300                                 continue;
301                         } // END - if
302
303                         // Load it
304                         self::loadInclude($fqfn);
305                 } // END - foreach
306
307                 // Scan for application's classes, exceptions and interfaces
308                 ClassLoader::scanApplicationClasses();
309         }
310
311         /**
312          * Starts a fully initialized application, the class ApplicationHelper must
313          * be loaded at this point.
314          *
315          * @return      void
316          */
317         public static function startApplication () {
318                 // Configuration entry 'detected_app_name' must be set, get it here
319                 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
320
321                 // Is there an application helper instance?
322                 $applicationInstance = call_user_func_array(
323                         array(
324                                 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
325                         ), array()
326                 );
327
328                 // Some sanity checks
329                 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
330                         // Something went wrong!
331                         ApplicationEntryPoint::app_exit(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.",
332                                 $application,
333                                 'CoreFramework\Helper\Application\ApplicationHelper'
334                         ));
335                 } elseif (!is_object($applicationInstance)) {
336                         // No object!
337                         ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because &#39;app&#39; is not an object (%s).",
338                                 $application,
339                                 gettype($applicationInstance)
340                         ));
341                 } elseif (!($applicationInstance instanceof ManageableApplication)) {
342                         // Missing interface
343                         ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because &#39;app&#39; is lacking required interface ManageableApplication.",
344                                 $application
345                         ));
346                 }
347
348                 // Set it in registry
349                 Registry::getRegistry()->addInstance('app', $applicationInstance);
350
351                 // Now call all methods in one go
352                 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
353                         // Debug message
354                         //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
355
356                         // Call method
357                         call_user_func(array($applicationInstance, $methodName));
358                 } // END - if
359         }
360
361         /**
362          * Initializes database instance, no need to double-call this method
363          *
364          * @return      void
365          */
366         public static function initDatabaseInstance () {
367                 // Get application instance
368                 $applicationInstance = ApplicationHelper::getSelfInstance();
369
370                 // Is the database instance already set?
371                 if ($applicationInstance instanceof DatabaseConnector) {
372                         // Yes, then abort here
373                         throw new BadMethodCallException('Method called twice.');
374                 } // END - if
375
376                 // Initialize database layer
377                 $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
378
379                 // Prepare database instance
380                 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
381
382                 // Set it in application helper
383                 $applicationInstance->setDatabaseInstance($connectionInstance);
384         }
385
386         /**
387          * 1) Loads class scanner and scans all framework's classes and interfaces.
388          * This method also registers the class loader's method autoLoad() for the
389          * SPL auto-load feature. Remember that you can register additional methods
390          * (not functions, please) for other libraries.
391          *
392          * Yes, I know about Composer, but I like to keep my class loader around.
393          * You can always use mine as long as your classes have a namespace
394          * according naming-convention: Vendor\Project\Group[\SubGroup]
395          *
396          * @return      void
397          */
398         private static function scanFrameworkClasses () {
399                 // Include the class loader function
400                 require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
401
402                 // Register auto-load function with the SPL
403                 spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
404
405                 // Scan for all framework classes, exceptions and interfaces
406                 ClassLoader::scanFrameworkClasses();
407         }
408
409         /**
410          * 2) Determines request/response type and stores the created
411          * request/response instances in this object for later usage.
412          *
413          * @return      void
414          */
415         private static function determineRequestType () {
416                 // Determine request type
417                 $request = self::getRequestTypeFromSystem();
418                 $requestType = self::getRequestTypeFromSystem();
419
420                 // Create a new request object
421                 $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
422
423                 // Remember request instance here
424                 self::setRequestInstance($requestInstance);
425
426                 // Do we have another response?
427                 if ($requestInstance->isRequestElementSet('request')) {
428                         // Then use it
429                         $request = strtolower($requestInstance->getRequestElement('request'));
430                         $requestType = $request;
431                 } // END - if
432
433                 // ... and a new response object
434                 $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
435                 $responseInstance = ObjectFactory::createObjectByName($responseClass);
436
437                 // Remember response instance here
438                 self::setResponseInstance($responseInstance);
439         }
440
441         /**
442          * 3) Validate parameter 'app' if it is set and the application is there.
443          *
444          * @return      void
445          */
446         private static function validateApplicationParameter () {
447                 // Is the parameter set?
448                 if (!self::getRequestInstance()->isRequestElementSet('app')) {
449                         /*
450                          * Don't continue here, the application 'selector' is no longer
451                          * supported and only existed as an idea to select the proper
452                          * application (by user).
453                          */
454                         ApplicationEntryPoint::app_exit('No application specified. Please provide a parameter "app" and retry.');
455                 } // END - if
456
457                 // Get it for local usage
458                 $application = self::getRequestInstance()->getRequestElement('app');
459
460                 // Secure it, by keeping out tags
461                 $application = htmlentities(strip_tags($application), ENT_QUOTES);
462
463                 // Secure it a little more with a reg.exp.
464                 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
465
466                 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
467                 $applicationPath = sprintf(
468                         '%s%s%s',
469                         FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
470                         $application,
471                         DIRECTORY_SEPARATOR
472                 );
473
474                 // Full path for application
475                 // Is the path there? This secures a bit the parameter (from untrusted source).
476                 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
477                         // Not found or not readable
478                         ApplicationEntryPoint::app_exit(sprintf('Application "%s" not found.', $application));
479                 } // END - if
480
481                 // Set the detected application's name and full path for later usage
482                 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
483                 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name'     , $application);
484         }
485         /**
486          * Setter for request instance
487          *
488          * @param       $requestInstance        An instance of a Requestable class
489          * @return      void
490          */
491         private static function setRequestInstance (Requestable $requestInstance) {
492                 self::$requestInstance = $requestInstance;
493         }
494
495         /**
496          * Setter for response instance
497          *
498          * @param       $responseInstance       An instance of a Responseable class
499          * @return      void
500          */
501         private static function setResponseInstance (Responseable $responseInstance) {
502                 self::$responseInstance = $responseInstance;
503         }
504
505 }