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