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