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