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