xref: /webtrees/app/Module/SiteMapModule.php (revision 4947e7089adb08f24bf1eef67994a106a8df60aa)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Carbon\Carbon;
21use Fisharebest\Webtrees\FlashMessages;
22use Fisharebest\Webtrees\GedcomRecord;
23use Fisharebest\Webtrees\Html;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Individual;
26use Fisharebest\Webtrees\Media;
27use Fisharebest\Webtrees\Note;
28use Fisharebest\Webtrees\Repository;
29use Fisharebest\Webtrees\Source;
30use Fisharebest\Webtrees\Tree;
31use Illuminate\Database\Capsule\Manager as DB;
32use Illuminate\Support\Collection;
33use Symfony\Component\HttpFoundation\RedirectResponse;
34use Symfony\Component\HttpFoundation\Request;
35use Symfony\Component\HttpFoundation\Response;
36use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
38/**
39 * Class SiteMapModule
40 */
41class SiteMapModule extends AbstractModule implements ModuleConfigInterface
42{
43    use ModuleConfigTrait;
44
45    private const RECORDS_PER_VOLUME = 500; // Keep sitemap files small, for memory, CPU and max_allowed_packet limits.
46    private const CACHE_LIFE         = 1209600; // Two weeks
47
48    /**
49     * How should this module be labelled on tabs, menus, etc.?
50     *
51     * @return string
52     */
53    public function title(): string
54    {
55        /* I18N: Name of a module - see http://en.wikipedia.org/wiki/Sitemaps */
56        return I18N::translate('Sitemaps');
57    }
58
59    /**
60     * A sentence describing what this module does.
61     *
62     * @return string
63     */
64    public function description(): string
65    {
66        /* I18N: Description of the “Sitemaps” module */
67        return I18N::translate('Generate sitemap files for search engines.');
68    }
69
70    /**
71     * @return Response
72     */
73    public function getAdminAction(): Response
74    {
75        $this->layout = 'layouts/administration';
76
77        $sitemap_url = route('module', [
78            'module' => $this->name(),
79            'action' => 'Index',
80        ]);
81
82        // This list comes from http://en.wikipedia.org/wiki/Sitemaps
83        $submit_urls = [
84            'Bing/Yahoo' => Html::url('https://www.bing.com/webmaster/ping.aspx', ['siteMap' => $sitemap_url]),
85            'Google'     => Html::url('https://www.google.com/webmasters/tools/ping', ['sitemap' => $sitemap_url]),
86        ];
87
88        return $this->viewResponse('modules/sitemap/config', [
89            'all_trees'   => Tree::all(),
90            'sitemap_url' => $sitemap_url,
91            'submit_urls' => $submit_urls,
92            'title'       => $this->title(),
93        ]);
94    }
95
96    /**
97     * @param Request $request
98     *
99     * @return RedirectResponse
100     */
101    public function postAdminAction(Request $request): RedirectResponse
102    {
103        foreach (Tree::all() as $tree) {
104            $include_in_sitemap = (bool) $request->get('sitemap' . $tree->id());
105            $tree->setPreference('include_in_sitemap', (string) $include_in_sitemap);
106        }
107
108        FlashMessages::addMessage(I18N::translate('The preferences for the module “%s” have been updated.', $this->title()), 'success');
109
110        return new RedirectResponse($this->getConfigLink());
111    }
112
113    /**
114     * @return Response
115     */
116    public function getIndexAction(): Response
117    {
118        $timestamp = (int) $this->getPreference('sitemap.timestamp');
119
120        if ($timestamp > Carbon::now()->timestamp - self::CACHE_LIFE) {
121            $content = $this->getPreference('sitemap.xml');
122        } else {
123            $count_individuals = DB::table('individuals')
124                ->groupBy('i_file')
125                ->select([DB::raw('COUNT(*) AS total'), 'i_file'])
126                ->pluck('total', 'i_file');
127
128            $count_media = DB::table('media')
129                ->groupBy('m_file')
130                ->select([DB::raw('COUNT(*) AS total'), 'm_file'])
131                ->pluck('total', 'm_file');
132
133            $count_notes = DB::table('other')
134                ->where('o_type', '=', 'NOTE')
135                ->groupBy('o_file')
136                ->select([DB::raw('COUNT(*) AS total'), 'o_file'])
137                ->pluck('total', 'o_file');
138
139            $count_repositories = DB::table('other')
140                ->where('o_type', '=', 'REPO')
141                ->groupBy('o_file')
142                ->select([DB::raw('COUNT(*) AS total'), 'o_file'])
143                ->pluck('total', 'o_file');
144
145            $count_sources = DB::table('sources')
146                ->groupBy('s_file')
147                ->select([DB::raw('COUNT(*) AS total'), 's_file'])
148                ->pluck('total', 's_file');
149
150            $content = view('modules/sitemap/sitemap-index.xml', [
151                'all_trees'          => Tree::all(),
152                'count_individuals'  => $count_individuals,
153                'count_media'        => $count_media,
154                'count_notes'        => $count_notes,
155                'count_repositories' => $count_repositories,
156                'count_sources'      => $count_sources,
157                'last_mod'           => date('Y-m-d'),
158                'records_per_volume' => self::RECORDS_PER_VOLUME,
159            ]);
160
161            $this->setPreference('sitemap.xml', $content);
162        }
163
164        return new Response($content, Response::HTTP_OK, [
165            'Content-Type' => 'application/xml',
166        ]);
167    }
168
169    /**
170     * @param Request $request
171     *
172     * @return Response
173     */
174    public function getFileAction(Request $request): Response
175    {
176        $file = $request->get('file', '');
177
178        if (!preg_match('/^(\d+)-([imnrs])-(\d+)$/', $file, $match)) {
179            throw new NotFoundHttpException('Bad sitemap file');
180        }
181
182        $timestamp = (int) $this->getPreference('sitemap-' . $file . '.timestamp');
183
184        if ($timestamp > WT_TIMESTAMP - self::CACHE_LIFE) {
185            $content = $this->getPreference('sitemap-' . $file . '.xml');
186        } else {
187            $tree = Tree::findById((int) $match[1]);
188
189            if ($tree === null) {
190                throw new NotFoundHttpException('No such tree');
191            }
192
193            $records = $this->sitemapRecords($tree, $match[2], self::RECORDS_PER_VOLUME, self::RECORDS_PER_VOLUME * $match[3]);
194
195            $content = view('modules/sitemap/sitemap-file.xml', ['records' => $records]);
196
197            $this->setPreference('sitemap.xml', $content);
198        }
199
200        return new Response($content, Response::HTTP_OK, [
201            'Content-Type' => 'application/xml',
202        ]);
203    }
204
205    /**
206     * @param Tree   $tree
207     * @param string $type
208     * @param int    $limit
209     * @param int    $offset
210     *
211     * @return Collection|GedcomRecord[]
212     */
213    private function sitemapRecords(Tree $tree, string $type, int $limit, int $offset): Collection
214    {
215        switch ($type) {
216            case 'i':
217                $records = $this->sitemapIndividuals($tree, $limit, $offset);
218                break;
219
220            case 'm':
221                $records = $this->sitemapMedia($tree, $limit, $offset);
222                break;
223
224            case 'n':
225                $records = $this->sitemapNotes($tree, $limit, $offset);
226                break;
227
228            case 'r':
229                $records = $this->sitemapRepositories($tree, $limit, $offset);
230                break;
231
232            case 's':
233                $records = $this->sitemapSources($tree, $limit, $offset);
234                break;
235
236            default:
237                throw new NotFoundHttpException('Invalid record type: ' . $type);
238        }
239
240        // Skip private records.
241        $records = $records->filter(GedcomRecord::accessFilter());
242
243        return $records;
244    }
245
246    /**
247     * @param Tree $tree
248     * @param int  $limit
249     * @param int  $offset
250     *
251     * @return Collection|Individual[]
252     */
253    private function sitemapIndividuals(Tree $tree, int $limit, int $offset): Collection
254    {
255        return DB::table('individuals')
256            ->where('i_file', '=', $tree->id())
257            ->orderBy('i_id')
258            ->skip($offset)
259            ->take($limit)
260            ->get()
261            ->map(Individual::rowMapper());
262    }
263
264    /**
265     * @param Tree $tree
266     * @param int  $limit
267     * @param int  $offset
268     *
269     * @return Collection|Media[]
270     */
271    private function sitemapMedia(Tree $tree, int $limit, int $offset): Collection
272    {
273        return DB::table('media')
274            ->where('m_file', '=', $tree->id())
275            ->orderBy('m_id')
276            ->skip($offset)
277            ->take($limit)
278            ->get()
279            ->map(Media::rowMapper());
280    }
281
282    /**
283     * @param Tree $tree
284     * @param int  $limit
285     * @param int  $offset
286     *
287     * @return Collection|Note[]
288     */
289    private function sitemapNotes(Tree $tree, int $limit, int $offset): Collection
290    {
291        return DB::table('other')
292            ->where('o_file', '=', $tree->id())
293            ->where('o_type', '=', 'NOTE')
294            ->orderBy('o_id')
295            ->skip($offset)
296            ->take($limit)
297            ->get()
298            ->map(Note::rowMapper());
299    }
300
301    /**
302     * @param Tree $tree
303     * @param int  $limit
304     * @param int  $offset
305     *
306     * @return Collection|Repository[]
307     */
308    private function sitemapRepositories(Tree $tree, int $limit, int $offset): Collection
309    {
310        return DB::table('other')
311            ->where('o_file', '=', $tree->id())
312            ->where('o_type', '=', 'REPO')
313            ->orderBy('o_id')
314            ->skip($offset)
315            ->take($limit)
316            ->get()
317            ->map(Repository::rowMapper());
318    }
319
320    /**
321     * @param Tree $tree
322     * @param int  $limit
323     * @param int  $offset
324     *
325     * @return Collection|Source[]
326     */
327    private function sitemapSources(Tree $tree, int $limit, int $offset): Collection
328    {
329        return DB::table('sources')
330            ->where('s_file', '=', $tree->id())
331            ->orderBy('s_id')
332            ->skip($offset)
333            ->take($limit)
334            ->get()
335            ->map(Source::rowMapper());
336    }
337}
338