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