xref: /webtrees/app/Module/ModuleCustomTrait.php (revision 3340ecd27b8901a894bff51b7c40bfa2896a552b)
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\Module;
21
22use Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Webtrees\Http\Exceptions\HttpAccessDeniedException;
24use Fisharebest\Webtrees\Http\Exceptions\HttpNotFoundException;
25use Fisharebest\Webtrees\Mime;
26use Fisharebest\Webtrees\Registry;
27use GuzzleHttp\Client;
28use GuzzleHttp\Exception\GuzzleException;
29use Psr\Http\Message\ResponseInterface;
30use Psr\Http\Message\ServerRequestInterface;
31
32use function str_contains;
33use function strtolower;
34
35/**
36 * Trait ModuleCustomTrait - default implementation of ModuleCustomInterface
37 */
38trait ModuleCustomTrait
39{
40    /**
41     * A unique internal name for this module (based on the installation folder).
42     *
43     * @return string
44     */
45    abstract public function name(): string;
46
47    /**
48     * Where does this module store its resources
49     *
50     * @return string
51     */
52    abstract public function resourcesFolder(): string;
53
54    /**
55     * The person or organisation who created this module.
56     *
57     * @return string
58     */
59    public function customModuleAuthorName(): string
60    {
61        return '';
62    }
63
64    /**
65     * The version of this module.
66     *
67     * @return string  e.g. '1.2.3'
68     */
69    public function customModuleVersion(): string
70    {
71        return '';
72    }
73
74    /**
75     * A URL that will provide the latest version of this module.
76     *
77     * @return string
78     */
79    public function customModuleLatestVersionUrl(): string
80    {
81        return '';
82    }
83
84    /**
85     * Fetch the latest version of this module.
86     *
87     * @return string
88     */
89    public function customModuleLatestVersion(): string
90    {
91        // No update URL provided.
92        if ($this->customModuleLatestVersionUrl() === '') {
93            return $this->customModuleVersion();
94        }
95
96        return Registry::cache()->file()->remember($this->name() . '-latest-version', function (): string {
97            try {
98                $client = new Client([
99                    'timeout' => 3,
100                ]);
101
102                $response = $client->get($this->customModuleLatestVersionUrl());
103
104                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
105                    $version = $response->getBody()->getContents();
106
107                    // Does the response look like a version?
108                    if (preg_match('/^\d+\.\d+\.\d+/', $version)) {
109                        return $version;
110                    }
111                }
112            } catch (GuzzleException $ex) {
113                // Can't connect to the server?
114            }
115
116            return $this->customModuleVersion();
117        }, 86400);
118    }
119
120    /**
121     * Where to get support for this module.  Perhaps a github repository?
122     *
123     * @return string
124     */
125    public function customModuleSupportUrl(): string
126    {
127        return '';
128    }
129
130    /**
131     * Additional/updated translations.
132     *
133     * @param string $language
134     *
135     * @return array<string,string>
136     */
137    public function customTranslations(string $language): array
138    {
139        return [];
140    }
141
142    /**
143     * Create a URL for an asset.
144     *
145     * @param string $asset e.g. "css/theme.css" or "img/banner.png"
146     *
147     * @return string
148     */
149    public function assetUrl(string $asset): string
150    {
151        $file = $this->resourcesFolder() . $asset;
152
153        // Add the file's modification time to the URL, so we can set long expiry cache headers.
154        $hash = filemtime($file);
155
156        return route('module', [
157            'module' => $this->name(),
158            'action' => 'Asset',
159            'asset'  => $asset,
160            'hash'   => $hash,
161        ]);
162    }
163
164    /**
165     * Serve a CSS/JS file.
166     *
167     * @param ServerRequestInterface $request
168     *
169     * @return ResponseInterface
170     */
171    public function getAssetAction(ServerRequestInterface $request): ResponseInterface
172    {
173        // The file being requested.  e.g. "css/theme.css"
174        $asset = $request->getQueryParams()['asset'];
175
176        // Do not allow requests that try to access parent folders.
177        if (str_contains($asset, '..')) {
178            throw new HttpAccessDeniedException($asset);
179        }
180
181        // Find the file for this asset.
182        // Note that we could also generate CSS files using views/templates.
183        // e.g. $file = view(....)
184        $file = $this->resourcesFolder() . $asset;
185
186        if (!file_exists($file)) {
187            throw new HttpNotFoundException(e($file));
188        }
189
190        $content   = file_get_contents($file);
191        $extension = strtolower(pathinfo($asset, PATHINFO_EXTENSION));
192        $mime_type = Mime::TYPES[$extension] ?? Mime::DEFAULT_TYPE;
193
194        return response($content, StatusCodeInterface::STATUS_OK, [
195            'Cache-Control'  => 'public,max-age=31536000',
196            'Content-Type'   => $mime_type,
197        ]);
198    }
199}
200