xref: /webtrees/app/Webtrees.php (revision 9f37cd254b1a3e6bd44a0e3b12637fa6f632784c)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Closure;
23use ErrorException;
24use Fisharebest\Webtrees\Factories\CacheFactory;
25use Fisharebest\Webtrees\Factories\CalendarDateFactory;
26use Fisharebest\Webtrees\Factories\ElementFactory;
27use Fisharebest\Webtrees\Factories\EncodingFactory;
28use Fisharebest\Webtrees\Factories\FamilyFactory;
29use Fisharebest\Webtrees\Factories\FilesystemFactory;
30use Fisharebest\Webtrees\Factories\GedcomRecordFactory;
31use Fisharebest\Webtrees\Factories\HeaderFactory;
32use Fisharebest\Webtrees\Factories\ImageFactory;
33use Fisharebest\Webtrees\Factories\IndividualFactory;
34use Fisharebest\Webtrees\Factories\LocationFactory;
35use Fisharebest\Webtrees\Factories\MarkdownFactory;
36use Fisharebest\Webtrees\Factories\MediaFactory;
37use Fisharebest\Webtrees\Factories\NoteFactory;
38use Fisharebest\Webtrees\Factories\RepositoryFactory;
39use Fisharebest\Webtrees\Factories\ResponseFactory;
40use Fisharebest\Webtrees\Factories\RouteFactory;
41use Fisharebest\Webtrees\Factories\SlugFactory;
42use Fisharebest\Webtrees\Factories\SourceFactory;
43use Fisharebest\Webtrees\Factories\SubmissionFactory;
44use Fisharebest\Webtrees\Factories\SubmitterFactory;
45use Fisharebest\Webtrees\Factories\TimestampFactory;
46use Fisharebest\Webtrees\Factories\XrefFactory;
47use Fisharebest\Webtrees\GedcomFilters\GedcomEncodingFilter;
48use Fisharebest\Webtrees\Http\Middleware\BadBotBlocker;
49use Fisharebest\Webtrees\Http\Middleware\BaseUrl;
50use Fisharebest\Webtrees\Http\Middleware\BootModules;
51use Fisharebest\Webtrees\Http\Middleware\CheckForMaintenanceMode;
52use Fisharebest\Webtrees\Http\Middleware\ClientIp;
53use Fisharebest\Webtrees\Http\Middleware\CompressResponse;
54use Fisharebest\Webtrees\Http\Middleware\ContentLength;
55use Fisharebest\Webtrees\Http\Middleware\DoHousekeeping;
56use Fisharebest\Webtrees\Http\Middleware\EmitResponse;
57use Fisharebest\Webtrees\Http\Middleware\HandleExceptions;
58use Fisharebest\Webtrees\Http\Middleware\LoadRoutes;
59use Fisharebest\Webtrees\Http\Middleware\NoRouteFound;
60use Fisharebest\Webtrees\Http\Middleware\ReadConfigIni;
61use Fisharebest\Webtrees\Http\Middleware\Router;
62use Fisharebest\Webtrees\Http\Middleware\SecurityHeaders;
63use Fisharebest\Webtrees\Http\Middleware\UpdateDatabaseSchema;
64use Fisharebest\Webtrees\Http\Middleware\UseDatabase;
65use Fisharebest\Webtrees\Http\Middleware\UseLanguage;
66use Fisharebest\Webtrees\Http\Middleware\UseSession;
67use Fisharebest\Webtrees\Http\Middleware\UseTheme;
68use Fisharebest\Webtrees\Http\Middleware\UseTransaction;
69use Illuminate\Container\Container;
70use Middleland\Dispatcher;
71use Nyholm\Psr7\Factory\Psr17Factory;
72use Nyholm\Psr7Server\ServerRequestCreator;
73use Psr\Container\ContainerInterface;
74use Psr\Http\Message\ResponseFactoryInterface;
75use Psr\Http\Message\ResponseInterface;
76use Psr\Http\Message\ServerRequestFactoryInterface;
77use Psr\Http\Message\ServerRequestInterface;
78use Psr\Http\Message\StreamFactoryInterface;
79use Psr\Http\Message\UploadedFileFactoryInterface;
80use Psr\Http\Message\UriFactoryInterface;
81use Psr\Http\Server\MiddlewareInterface;
82
83use function date_default_timezone_set;
84use function error_reporting;
85use function is_string;
86use function mb_internal_encoding;
87use function set_error_handler;
88use function stream_filter_register;
89
90use const E_ALL;
91use const E_DEPRECATED;
92use const E_USER_DEPRECATED;
93
94/**
95 * Definitions for the webtrees application.
96 */
97class Webtrees
98{
99    // The root folder of this installation
100    public const ROOT_DIR = __DIR__ . '/../';
101
102    // This is the location of system data, such as temporary and cache files.
103    // The system files are always in this location.
104    // It is also the default location of user data, such as media and GEDCOM files.
105    // The user files could be anywhere supported by Flysystem.
106    public const DATA_DIR = self::ROOT_DIR . 'data/';
107
108    // Location of the file containing the database connection details.
109    public const CONFIG_FILE = self::DATA_DIR . 'config.ini.php';
110
111    // Location of the file that triggers maintenance mode.
112    public const OFFLINE_FILE = self::DATA_DIR . 'offline.txt';
113
114    // Location of our modules.
115    public const MODULES_PATH = 'modules_v4/';
116    public const MODULES_DIR  = self::ROOT_DIR . self::MODULES_PATH;
117
118    // Enable debugging on development builds.
119    public const DEBUG = self::STABILITY !== '';
120
121    // We want to know about all PHP errors during development, and fewer in production.
122    public const ERROR_REPORTING = self::DEBUG ? E_ALL : E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED;
123
124    // Page layouts for various page types.
125    public const LAYOUT_ADMINISTRATION = 'layouts/administration';
126    public const LAYOUT_AJAX           = 'layouts/ajax';
127    public const LAYOUT_DEFAULT        = 'layouts/default';
128    public const LAYOUT_ERROR          = 'layouts/error';
129
130    // The name of the application.
131    public const NAME = 'webtrees';
132
133    // Required version of database tables/columns/indexes/etc.
134    public const SCHEMA_VERSION = 45;
135
136    // e.g. "-dev", "-alpha", "-beta", etc.
137    public const STABILITY = '-alpha.2';
138
139    // Version number
140    public const VERSION = '2.1.0' . self::STABILITY;
141
142    // Project website.
143    public const URL = 'https://webtrees.net/';
144
145    // FAQ links
146    public const URL_FAQ_EMAIL = 'https://webtrees.net/faq/email';
147
148    // Project website.
149    public const GEDCOM_PDF = 'https://webtrees.net/downloads/gedcom-5-5-1.pdf';
150
151    private const MIDDLEWARE = [
152        EmitResponse::class,
153        SecurityHeaders::class,
154        ReadConfigIni::class,
155        BaseUrl::class,
156        HandleExceptions::class,
157        ClientIp::class,
158        ContentLength::class,
159        CompressResponse::class,
160        BadBotBlocker::class,
161        UseDatabase::class,
162        UpdateDatabaseSchema::class,
163        UseSession::class,
164        UseLanguage::class,
165        CheckForMaintenanceMode::class,
166        UseTheme::class,
167        DoHousekeeping::class,
168        UseTransaction::class,
169        LoadRoutes::class,
170        BootModules::class,
171        Router::class,
172        NoRouteFound::class,
173    ];
174
175    /**
176     * Initialise the application.
177     *
178     * @return void
179     */
180    public function bootstrap(): void
181    {
182        // Show all errors and warnings in development, fewer in production.
183        error_reporting(self::ERROR_REPORTING);
184        set_error_handler($this->phpErrorHandler());
185
186        // All modern software uses UTF-8 encoding.
187        mb_internal_encoding('UTF-8');
188
189        // Use UTC internally and convert to local time when displaying datetimes.
190        date_default_timezone_set('UTC');
191
192        // Factory objects
193        Registry::cache(new CacheFactory());
194        Registry::calendarDateFactory(new CalendarDateFactory());
195        Registry::elementFactory(new ElementFactory());
196        Registry::encodingFactory(new EncodingFactory());
197        Registry::familyFactory(new FamilyFactory());
198        Registry::filesystem(new FilesystemFactory());
199        Registry::gedcomRecordFactory(new GedcomRecordFactory());
200        Registry::headerFactory(new HeaderFactory());
201        Registry::imageFactory(new ImageFactory());
202        Registry::individualFactory(new IndividualFactory());
203        Registry::locationFactory(new LocationFactory());
204        Registry::markdownFactory(new MarkdownFactory());
205        Registry::mediaFactory(new MediaFactory());
206        Registry::noteFactory(new NoteFactory());
207        Registry::repositoryFactory(new RepositoryFactory());
208        Registry::responseFactory(new ResponseFactory(new Psr17Factory(), new Psr17Factory()));
209        Registry::routeFactory(new RouteFactory());
210        Registry::slugFactory(new SlugFactory());
211        Registry::sourceFactory(new SourceFactory());
212        Registry::submissionFactory(new SubmissionFactory());
213        Registry::submitterFactory(new SubmitterFactory());
214        Registry::timestampFactory(new TimestampFactory());
215        Registry::xrefFactory(new XrefFactory());
216
217        stream_filter_register(GedcomEncodingFilter::class, GedcomEncodingFilter::class);
218    }
219
220    /**
221     * Respond to a CLI request.
222     *
223     * @return void
224     */
225    public function cliRequest(): void
226    {
227        // CLI handler will go here.
228    }
229
230    /**
231     * Respond to an HTTP request.
232     *
233     * @return ResponseInterface
234     */
235    public function httpRequest(): ResponseInterface
236    {
237        $psr17factory = new Psr17Factory();
238
239        // PSR7 messages and PSR17 message-factories
240        self::set(ResponseFactoryInterface::class, $psr17factory);
241        self::set(ServerRequestFactoryInterface::class, $psr17factory);
242        self::set(StreamFactoryInterface::class, $psr17factory);
243        self::set(UploadedFileFactoryInterface::class, $psr17factory);
244        self::set(UriFactoryInterface::class, $psr17factory);
245
246        $server_request_creator = new ServerRequestCreator($psr17factory, $psr17factory, $psr17factory, $psr17factory);
247
248        $request = $server_request_creator->fromGlobals();
249
250        return self::dispatch($request, self::MIDDLEWARE);
251    }
252
253    /**
254     * @param ServerRequestInterface            $request
255     * @param array<string|MiddlewareInterface> $middleware
256     *
257     * @return ResponseInterface
258     */
259    public static function dispatch(ServerRequestInterface $request, array $middleware): ResponseInterface
260    {
261        $dispatcher = new Dispatcher($middleware, self::container());
262
263        return $dispatcher->dispatch($request);
264    }
265
266    /**
267     * An error handler that can be passed to set_error_handler().
268     *
269     * @return Closure
270     */
271    private function phpErrorHandler(): Closure
272    {
273        return static function (int $errno, string $errstr, string $errfile, int $errline): bool {
274            // Ignore errors that are silenced with '@'
275            if (error_reporting() & $errno) {
276                throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
277            }
278
279            return true;
280        };
281    }
282
283    /**
284     * @return ContainerInterface
285     */
286    public static function container(): ContainerInterface
287    {
288        return Container::getInstance();
289    }
290
291    /**
292     * Make an object, using dependency injection.
293     *
294     * @param string $class
295     *
296     * @return mixed
297     */
298    public static function make(string $class)
299    {
300        return Container::getInstance()->make($class);
301    }
302
303    /**
304     * Write a value into the container.
305     *
306     * @param string        $abstract
307     * @param string|object $concrete
308     */
309    public static function set(string $abstract, $concrete): void
310    {
311        if (is_string($concrete)) {
312            Container::getInstance()->bind($abstract, $concrete);
313        } else {
314            Container::getInstance()->instance($abstract, $concrete);
315        }
316    }
317}
318