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