xref: /webtrees/app/Module/RecentChangesModule.php (revision b11cdcd45131b1585d66693fab363cfeb18c51a4)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * 'Copyright (C) 2023 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 Fisharebest\Webtrees\Family;
23use Fisharebest\Webtrees\GedcomRecord;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Individual;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Services\UserService;
28use Fisharebest\Webtrees\Tree;
29use Fisharebest\Webtrees\User;
30use Fisharebest\Webtrees\Validator;
31use Illuminate\Database\Capsule\Manager as DB;
32use Illuminate\Database\Query\Expression;
33use Illuminate\Database\Query\JoinClause;
34use Illuminate\Support\Collection;
35use Illuminate\Support\Str;
36use Psr\Http\Message\ServerRequestInterface;
37use stdClass;
38
39use function extract;
40use function view;
41
42use const EXTR_OVERWRITE;
43
44/**
45 * Class RecentChangesModule
46 */
47class RecentChangesModule extends AbstractModule implements ModuleBlockInterface
48{
49    use ModuleBlockTrait;
50
51    // Where do we look for change information
52    private const SOURCE_DATABASE = 'database';
53    private const SOURCE_GEDCOM   = 'gedcom';
54
55    private const DEFAULT_DAYS       = '7';
56    private const DEFAULT_SHOW_USER  = '1';
57    private const DEFAULT_SHOW_DATE  = '1';
58    private const DEFAULT_SORT_STYLE = 'date_desc';
59    private const DEFAULT_INFO_STYLE = 'table';
60    private const DEFAULT_SOURCE     = self::SOURCE_DATABASE;
61    private const MAX_DAYS           = 90;
62
63    // Pagination
64    private const LIMIT_LOW  = 10;
65    private const LIMIT_HIGH = 20;
66
67    private UserService $user_service;
68
69    /**
70     * RecentChangesModule constructor.
71     *
72     * @param UserService $user_service
73     */
74    public function __construct(UserService $user_service)
75    {
76        $this->user_service = $user_service;
77    }
78
79    /**
80     * How should this module be identified in the control panel, etc.?
81     *
82     * @return string
83     */
84    public function title(): string
85    {
86        /* I18N: Name of a module */
87        return I18N::translate('Recent changes');
88    }
89
90    /**
91     * A sentence describing what this module does.
92     *
93     * @return string
94     */
95    public function description(): string
96    {
97        /* I18N: Description of the “Recent changes” module */
98        return I18N::translate('A list of records that have been updated recently.');
99    }
100
101    /**
102     * @param Tree                 $tree
103     * @param int                  $block_id
104     * @param string               $context
105     * @param array<string,string> $config
106     *
107     * @return string
108     */
109    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
110    {
111        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
112        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
113        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
114        $show_user = (bool) $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
115        $show_date = (bool) $this->getBlockSetting($block_id, 'show_date', self::DEFAULT_SHOW_DATE);
116        $source    = $this->getBlockSetting($block_id, 'source', self::DEFAULT_SOURCE);
117
118        extract($config, EXTR_OVERWRITE);
119
120        if ($source === self::SOURCE_DATABASE) {
121            $rows = $this->getRecentChangesFromDatabase($tree, $days);
122        } else {
123            $rows = $this->getRecentChangesFromGenealogy($tree, $days);
124        }
125
126        switch ($sortStyle) {
127            case 'name':
128                $rows  = $rows->sort(static function (stdClass $x, stdClass $y): int {
129                    return GedcomRecord::nameComparator()($x->record, $y->record);
130                });
131                $order = [[1, 'asc']];
132                break;
133
134            case 'date_asc':
135                $rows  = $rows->sort(static function (stdClass $x, stdClass $y): int {
136                    return $x->time <=> $y->time;
137                });
138                $order = [[2, 'asc']];
139                break;
140
141            default:
142            case 'date_desc':
143                $rows  = $rows->sort(static function (stdClass $x, stdClass $y): int {
144                    return $y->time <=> $x->time;
145                });
146                $order = [[2, 'desc']];
147                break;
148        }
149
150        if ($rows->isEmpty()) {
151            $content = I18N::plural('There have been no changes within the last %s day.', 'There have been no changes within the last %s days.', $days, I18N::number($days));
152        } elseif ($infoStyle === 'list') {
153            $content = view('modules/recent_changes/changes-list', [
154                'id'         => $block_id,
155                'limit_low'  => self::LIMIT_LOW,
156                'limit_high' => self::LIMIT_HIGH,
157                'rows'       => $rows->values(),
158                'show_date'  => $show_date,
159                'show_user'  => $show_user,
160            ]);
161        } else {
162            $content = view('modules/recent_changes/changes-table', [
163                'limit_low'  => self::LIMIT_LOW,
164                'limit_high' => self::LIMIT_HIGH,
165                'rows'       => $rows,
166                'show_date'  => $show_date,
167                'show_user'  => $show_user,
168                'order'      => $order,
169            ]);
170        }
171
172        if ($context !== self::CONTEXT_EMBED) {
173            return view('modules/block-template', [
174                'block'      => Str::kebab($this->name()),
175                'id'         => $block_id,
176                'config_url' => $this->configUrl($tree, $context, $block_id),
177                'title'      => I18N::plural('Changes in the last %s day', 'Changes in the last %s days', $days, I18N::number($days)),
178                'content'    => $content,
179            ]);
180        }
181
182        return $content;
183    }
184
185    /**
186     * Should this block load asynchronously using AJAX?
187     *
188     * Simple blocks are faster in-line, more complex ones can be loaded later.
189     *
190     * @return bool
191     */
192    public function loadAjax(): bool
193    {
194        return true;
195    }
196
197    /**
198     * Can this block be shown on the user’s home page?
199     *
200     * @return bool
201     */
202    public function isUserBlock(): bool
203    {
204        return true;
205    }
206
207    /**
208     * Can this block be shown on the tree’s home page?
209     *
210     * @return bool
211     */
212    public function isTreeBlock(): bool
213    {
214        return true;
215    }
216
217    /**
218     * Update the configuration for a block.
219     *
220     * @param ServerRequestInterface $request
221     * @param int                    $block_id
222     *
223     * @return void
224     */
225    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
226    {
227        $days       = Validator::parsedBody($request)->integer('days');
228        $info_style = Validator::parsedBody($request)->string('infoStyle');
229        $sort_style = Validator::parsedBody($request)->string('sortStyle');
230        $show_date  = Validator::parsedBody($request)->boolean('show_date');
231        $show_user  = Validator::parsedBody($request)->boolean('show_user');
232        $source     = Validator::parsedBody($request)->string('source');
233
234        $this->setBlockSetting($block_id, 'days', (string) $days);
235        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
236        $this->setBlockSetting($block_id, 'sortStyle', $sort_style);
237        $this->setBlockSetting($block_id, 'show_date', (string) $show_date);
238        $this->setBlockSetting($block_id, 'show_user', (string) $show_user);
239        $this->setBlockSetting($block_id, 'source', $source);
240    }
241
242    /**
243     * An HTML form to edit block settings
244     *
245     * @param Tree $tree
246     * @param int  $block_id
247     *
248     * @return string
249     */
250    public function editBlockConfiguration(Tree $tree, int $block_id): string
251    {
252        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
253        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
254        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
255        $show_date = $this->getBlockSetting($block_id, 'show_date', self::DEFAULT_SHOW_DATE);
256        $show_user = $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
257        $source    = $this->getBlockSetting($block_id, 'source', self::DEFAULT_SOURCE);
258
259        $info_styles = [
260            /* I18N: An option in a list-box */
261            'list'  => I18N::translate('list'),
262            /* I18N: An option in a list-box */
263            'table' => I18N::translate('table'),
264        ];
265
266        $sort_styles = [
267            /* I18N: An option in a list-box */
268            'name'      => I18N::translate('sort by name'),
269            /* I18N: An option in a list-box */
270            'date_asc'  => I18N::translate('sort by date, oldest first'),
271            /* I18N: An option in a list-box */
272            'date_desc' => I18N::translate('sort by date, newest first'),
273        ];
274
275        $sources = [
276            /* I18N: An option in a list-box */
277            self::SOURCE_DATABASE => I18N::translate('show changes made in webtrees'),
278            /* I18N: An option in a list-box */
279            self::SOURCE_GEDCOM   => I18N::translate('show changes recorded in the genealogy data'),
280        ];
281
282        return view('modules/recent_changes/config', [
283            'days'        => $days,
284            'infoStyle'   => $infoStyle,
285            'info_styles' => $info_styles,
286            'max_days'    => self::MAX_DAYS,
287            'sortStyle'   => $sortStyle,
288            'sort_styles' => $sort_styles,
289            'source'      => $source,
290            'sources'     => $sources,
291            'show_date'   => $show_date,
292            'show_user'   => $show_user,
293        ]);
294    }
295
296    /**
297     * Find records that have changed since a given julian day
298     *
299     * @param Tree $tree Changes for which tree
300     * @param int  $days Number of days
301     *
302     * @return Collection<array-key,stdClass> List of records with changes
303     */
304    private function getRecentChangesFromDatabase(Tree $tree, int $days): Collection
305    {
306        $subquery = DB::table('change')
307            ->where('gedcom_id', '=', $tree->id())
308            ->where('status', '=', 'accepted')
309            ->where('new_gedcom', '<>', '')
310            ->where('change_time', '>', Registry::timestampFactory()->now()->subtractDays($days)->toDateTimeString())
311            ->groupBy(['xref'])
312            ->select(new Expression('MAX(change_id) AS recent_change_id'));
313
314        $query = DB::table('change')
315            ->joinSub($subquery, 'recent', 'recent_change_id', '=', 'change_id')
316            ->select(['change.*']);
317
318        return $query
319            ->get()
320            ->map(function (object $row) use ($tree): object {
321                return (object) [
322                    'record' => Registry::gedcomRecordFactory()->make($row->xref, $tree, $row->new_gedcom),
323                    'time'   => Registry::timestampFactory()->fromString($row->change_time),
324                    'user'   => $this->user_service->find((int) $row->user_id),
325                ];
326            })
327            ->filter(static function (object $row): bool {
328                return $row->record instanceof GedcomRecord && $row->record->canShow();
329            });
330    }
331
332    /**
333     * Find records that have changed since a given julian day
334     *
335     * @param Tree $tree Changes for which tree
336     * @param int  $days Number of days
337     *
338     * @return Collection<array-key,stdClass> List of records with changes
339     */
340    private function getRecentChangesFromGenealogy(Tree $tree, int $days): Collection
341    {
342        $julian_day = Registry::timestampFactory()->now()->subtractDays($days)->julianDay();
343
344        $individuals = DB::table('dates')
345            ->where('d_file', '=', $tree->id())
346            ->where('d_julianday1', '>=', $julian_day)
347            ->where('d_fact', '=', 'CHAN')
348            ->join('individuals', static function (JoinClause $join): void {
349                $join
350                    ->on('d_file', '=', 'i_file')
351                    ->on('d_gid', '=', 'i_id');
352            })
353            ->select(['individuals.*'])
354            ->get()
355            ->map(Registry::individualFactory()->mapper($tree))
356            ->filter(Individual::accessFilter());
357
358        $families = DB::table('dates')
359            ->where('d_file', '=', $tree->id())
360            ->where('d_julianday1', '>=', $julian_day)
361            ->where('d_fact', '=', 'CHAN')
362            ->join('families', static function (JoinClause $join): void {
363                $join
364                    ->on('d_file', '=', 'f_file')
365                    ->on('d_gid', '=', 'f_id');
366            })
367            ->select(['families.*'])
368            ->get()
369            ->map(Registry::familyFactory()->mapper($tree))
370            ->filter(Family::accessFilter());
371
372        return $individuals->merge($families)
373            ->map(function (GedcomRecord $record): object {
374                $user = $this->user_service->findByUserName($record->lastChangeUser());
375
376                return (object) [
377                    'record' => $record,
378                    'time'   => $record->lastChangeTimestamp(),
379                    'user'   => $user ?? new User(0, '…', '…', ''),
380                ];
381            });
382    }
383}
384