Allow DNS resolver to become quiet about its operations
[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                 );
184
185                 // Return status
186                 return $isReadable;
187         }
188
189         /**
190          * Loads given include file
191          *
192          * @param       $fqfn   Include's FQFN
193          * @return      void
194          * @throws      InvalidArgumentException        If $fqfn was not found or not readable or deprecated
195          */
196         public static function loadInclude ($fqfn) {
197                 // Trace message
198                 //* NOISY-DEBUG: */ printf('[%s:%d]: fqfn=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fqfn);
199
200                 // Should be there ...
201                 if (!self::isReadableFile($fqfn)) {
202                         // Abort here
203                         throw new InvalidArgumentException(sprintf('Cannot find fqfn=%s.', $fqfn));
204                 } // END - if
205
206                 // Load it
207                 require $fqfn;
208
209                 // Trace message
210                 //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
211         }
212
213         /**
214          * Does the actual bootstrap
215          *
216          * @return      void
217          */
218         public static function doBootstrap () {
219                 // Load basic include files to continue bootstrapping
220                 self::loadInclude(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
221                 self::loadInclude(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR));
222                 self::loadInclude(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR));
223
224                 // Load global configuration
225                 self::loadInclude(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php'));
226         }
227
228         /**
229          * Initializes the framework by scanning for all framework-relevant
230          * classes, interfaces and exception. Then determine the request type and
231          * initialize a Requestable instance which will then contain all request
232          * parameter, also from CLI. Next step is to validate the application
233          * (very basic).
234          *
235          * @return      void
236          */
237         public static function initFramework () {
238                 /**
239                  * 1) Load class loader and scan framework classes, interfaces and
240                  *    exceptions.
241                  */
242                 self::scanFrameworkClasses();
243
244                 /*
245                  * 2) Determine the request type, console or web and store request and
246                  *    response here. This also initializes the request instance will
247                  *    all given parameters (see doc-tag for possible sources of
248                  *    parameters).
249                  */
250                 self::determineRequestType();
251
252                 /*
253                  * 3) Now, that there are all request parameters being available, check
254                  *    if 'app' is supplied. If it is not found, abort execution, if
255                  *    found, continue below with next step.
256                  */
257                 self::validateApplicationParameter();
258         }
259
260         /**
261          * Initializes the detected application. This may fail if required files
262          * are not found in the application's base path (not to be confused with
263          * 'application_base_path' which only points to /some/foo/application/.
264          *
265          * @return      void
266          */
267         public static function prepareApplication () {
268                 // Configuration entry 'detected_app_name' must be set, get it here, including full path
269                 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
270                 $fullPath    = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_full_app_path');
271
272                 /*
273                  * Now check and load all files, found deprecated files will throw a
274                  * warning at the user.
275                  */
276                 foreach (self::$configAppIncludes as $fileName => $status) {
277                         // Construct FQFN
278                         $fqfn = sprintf('%s%s.php', $fullPath, $fileName);
279
280                         // Determine if this file is wanted/readable/deprecated
281                         if (($status == 'required') && (!self::isReadableFile($fqfn))) {
282                                 // Nope, required file cannot be found/read from
283                                 ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileName));
284                         } elseif ((file_exists($fqfn)) && (!is_readable($fqfn))) {
285                                 // Found, not readable file
286                                 ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileName, $application));
287                         } elseif (($status != 'required') && (!self::isReadableFile($fqfn))) {
288                                 // Not found but optional/deprecated file, skip it
289                                 continue;
290                         }
291
292                         // Is the file deprecated?
293                         if ($status == 'deprecated') {
294                                 // Issue warning
295                                 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);
296
297                                 // Skip loading deprecated file
298                                 continue;
299                         } // END - if
300
301                         // Load it
302                         self::loadInclude($fqfn);
303                 } // END - foreach
304
305                 // Scan for application's classes, exceptions and interfaces
306                 ClassLoader::scanApplicationClasses();
307         }
308
309         /**
310          * Starts a fully initialized application, the class ApplicationHelper must
311          * be loaded at this point.
312          *
313          * @return      void
314          */
315         public static function startApplication () {
316                 // Configuration entry 'detected_app_name' must be set, get it here
317                 $application = FrameworkConfiguration::getSelfInstance()->getConfigEntry('detected_app_name');
318
319                 // Is there an application helper instance?
320                 $applicationInstance = call_user_func_array(
321                         array(
322                                 'CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
323                         ), array()
324                 );
325
326                 // Some sanity checks
327                 if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
328                         // Something went wrong!
329                         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.",
330                                 $application,
331                                 'CoreFramework\Helper\Application\ApplicationHelper'
332                         ));
333                 } elseif (!is_object($applicationInstance)) {
334                         // No object!
335                         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).",
336                                 $application,
337                                 gettype($applicationInstance)
338                         ));
339                 } elseif (!($applicationInstance instanceof ManageableApplication)) {
340                         // Missing interface
341                         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.",
342                                 $application
343                         ));
344                 }
345
346                 // Set it in registry
347                 Registry::getRegistry()->addInstance('app', $applicationInstance);
348
349                 // Now call all methods in one go
350                 foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
351                         // Debug message
352                         //* NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
353
354                         // Call method
355                         call_user_func(array($applicationInstance, $methodName));
356                 } // END - if
357         }
358
359         /**
360          * Initializes database instance, no need to double-call this method
361          *
362          * @return      void
363          */
364         public static function initDatabaseInstance () {
365                 // Get application instance
366                 $applicationInstance = ApplicationHelper::getSelfInstance();
367
368                 // Is the database instance already set?
369                 if ($applicationInstance instanceof DatabaseConnector) {
370                         // Yes, then abort here
371                         throw new BadMethodCallException('Method called twice.');
372                 } // END - if
373
374                 // Initialize database layer
375                 $databaseInstance = ObjectFactory::createObjectByConfiguredName(FrameworkConfiguration::getSelfInstance()->getConfigEntry('database_type') . '_class');
376
377                 // Prepare database instance
378                 $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
379
380                 // Set it in application helper
381                 $applicationInstance->setDatabaseInstance($connectionInstance);
382         }
383
384         /**
385          * 1) Loads class scanner and scans all framework's classes and interfaces.
386          * This method also registers the class loader's method autoLoad() for the
387          * SPL auto-load feature. Remember that you can register additional methods
388          * (not functions, please) for other libraries.
389          *
390          * Yes, I know about Composer, but I like to keep my class loader around.
391          * You can always use mine as long as your classes have a namespace
392          * according naming-convention: Vendor\Project\Group[\SubGroup]
393          *
394          * @return      void
395          */
396         private static function scanFrameworkClasses () {
397                 // Include the class loader function
398                 require FrameworkConfiguration::getSelfInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
399
400                 // Register auto-load function with the SPL
401                 spl_autoload_register('CoreFramework\Loader\ClassLoader::autoLoad');
402
403                 // Scan for all framework classes, exceptions and interfaces
404                 ClassLoader::scanFrameworkClasses();
405         }
406
407         /**
408          * 2) Determines request/response type and stores the created
409          * request/response instances in this object for later usage.
410          *
411          * @return      void
412          */
413         private static function determineRequestType () {
414                 // Determine request type
415                 $request = self::getRequestTypeFromSystem();
416                 $requestType = self::getRequestTypeFromSystem();
417
418                 // Create a new request object
419                 $requestInstance = ObjectFactory::createObjectByName(sprintf('CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
420
421                 // Remember request instance here
422                 self::setRequestInstance($requestInstance);
423
424                 // Do we have another response?
425                 if ($requestInstance->isRequestElementSet('request')) {
426                         // Then use it
427                         $request = strtolower($requestInstance->getRequestElement('request'));
428                         $requestType = $request;
429                 } // END - if
430
431                 // ... and a new response object
432                 $responseClass = sprintf('CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
433                 $responseInstance = ObjectFactory::createObjectByName($responseClass);
434
435                 // Remember response instance here
436                 self::setResponseInstance($responseInstance);
437         }
438
439         /**
440          * 3) Validate parameter 'app' if it is set and the application is there.
441          *
442          * @return      void
443          */
444         private static function validateApplicationParameter () {
445                 // Is the parameter set?
446                 if (!self::getRequestInstance()->isRequestElementSet('app')) {
447                         /*
448                          * Don't continue here, the application 'selector' is no longer
449                          * supported and only existed as an idea to select the proper
450                          * application (by user).
451                          */
452                         ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
453                 } // END - if
454
455                 // Get it for local usage
456                 $application = self::getRequestInstance()->getRequestElement('app');
457
458                 // Secure it, by keeping out tags
459                 $application = htmlentities(strip_tags($application), ENT_QUOTES);
460
461                 // Secure it a little more with a reg.exp.
462                 $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
463
464                 // Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
465                 $applicationPath = sprintf(
466                         '%s%s%s',
467                         FrameworkConfiguration::getSelfInstance()->getConfigEntry('application_base_path'),
468                         $application,
469                         DIRECTORY_SEPARATOR
470                 );
471
472                 // Full path for application
473                 // Is the path there? This secures a bit the parameter (from untrusted source).
474                 if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
475                         // Not found or not readable
476                         ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
477                 } // END - if
478
479                 // Set the detected application's name and full path for later usage
480                 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
481                 FrameworkConfiguration::getSelfInstance()->setConfigEntry('detected_app_name'     , $application);
482         }
483         /**
484          * Setter for request instance
485          *
486          * @param       $requestInstance        An instance of a Requestable class
487          * @return      void
488          */
489         private static function setRequestInstance (Requestable $requestInstance) {
490                 self::$requestInstance = $requestInstance;
491         }
492
493         /**
494          * Setter for response instance
495          *
496          * @param       $responseInstance       An instance of a Responseable class
497          * @return      void
498          */
499         private static function setResponseInstance (Responseable $responseInstance) {
500                 self::$responseInstance = $responseInstance;
501         }
502
503 }