xref: /webtrees/app/Module/RecentChangesModule.php (revision d7c2f5cc56f17801156c069987440ca1da2c5057)
18c2e8227SGreg Roach<?php
23976b470SGreg Roach
38c2e8227SGreg Roach/**
48c2e8227SGreg Roach * webtrees: online genealogy
5d11be702SGreg Roach * Copyright (C) 2023 webtrees development team
68c2e8227SGreg Roach * This program is free software: you can redistribute it and/or modify
78c2e8227SGreg Roach * it under the terms of the GNU General Public License as published by
88c2e8227SGreg Roach * the Free Software Foundation, either version 3 of the License, or
98c2e8227SGreg Roach * (at your option) any later version.
108c2e8227SGreg Roach * This program is distributed in the hope that it will be useful,
118c2e8227SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
128c2e8227SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
138c2e8227SGreg Roach * GNU General Public License for more details.
148c2e8227SGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
168c2e8227SGreg Roach */
17fcfa147eSGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
2076692c8bSGreg Roachnamespace Fisharebest\Webtrees\Module;
2176692c8bSGreg Roach
226f4ec3caSGreg Roachuse Fisharebest\Webtrees\DB;
23501bc70dSGreg Roachuse Fisharebest\Webtrees\Family;
246e45321fSGreg Roachuse Fisharebest\Webtrees\GedcomRecord;
250e62c4b8SGreg Roachuse Fisharebest\Webtrees\I18N;
26501bc70dSGreg Roachuse Fisharebest\Webtrees\Individual;
2776d39c55SGreg Roachuse Fisharebest\Webtrees\Registry;
28bd77bf38SGreg Roachuse Fisharebest\Webtrees\Services\UserService;
296e45321fSGreg Roachuse Fisharebest\Webtrees\Tree;
30e10e1dc9SGreg Roachuse Fisharebest\Webtrees\User;
31748dbe15SGreg Roachuse Fisharebest\Webtrees\Validator;
32bd77bf38SGreg Roachuse Illuminate\Database\Query\Expression;
33501bc70dSGreg Roachuse Illuminate\Database\Query\JoinClause;
34bd77bf38SGreg Roachuse Illuminate\Support\Collection;
351e7a7a28SGreg Roachuse Illuminate\Support\Str;
366ccdf4f0SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
37bd77bf38SGreg Roach
38bd77bf38SGreg Roachuse function extract;
39bd77bf38SGreg Roachuse function view;
40bd77bf38SGreg Roach
41bd77bf38SGreg Roachuse const EXTR_OVERWRITE;
428c2e8227SGreg Roach
438c2e8227SGreg Roach/**
448c2e8227SGreg Roach * Class RecentChangesModule
458c2e8227SGreg Roach */
4637eb8894SGreg Roachclass RecentChangesModule extends AbstractModule implements ModuleBlockInterface
47c1010edaSGreg Roach{
4849a243cbSGreg Roach    use ModuleBlockTrait;
4949a243cbSGreg Roach
50501bc70dSGreg Roach    // Where do we look for change information
51501bc70dSGreg Roach    private const SOURCE_DATABASE = 'database';
52501bc70dSGreg Roach    private const SOURCE_GEDCOM   = 'gedcom';
53501bc70dSGreg Roach
5416d6367aSGreg Roach    private const DEFAULT_DAYS       = '7';
5516d6367aSGreg Roach    private const DEFAULT_SHOW_USER  = '1';
56501bc70dSGreg Roach    private const DEFAULT_SHOW_DATE  = '1';
5716d6367aSGreg Roach    private const DEFAULT_SORT_STYLE = 'date_desc';
5816d6367aSGreg Roach    private const DEFAULT_INFO_STYLE = 'table';
59501bc70dSGreg Roach    private const DEFAULT_SOURCE     = self::SOURCE_DATABASE;
6016d6367aSGreg Roach    private const MAX_DAYS           = 90;
618c2e8227SGreg Roach
6201221f27SGreg Roach    // Pagination
6301221f27SGreg Roach    private const LIMIT_LOW  = 10;
6401221f27SGreg Roach    private const LIMIT_HIGH = 20;
6501221f27SGreg Roach
6643f2f523SGreg Roach    private UserService $user_service;
67bd77bf38SGreg Roach
68bd77bf38SGreg Roach    /**
69bd77bf38SGreg Roach     * @param UserService $user_service
70bd77bf38SGreg Roach     */
71bd77bf38SGreg Roach    public function __construct(UserService $user_service)
72bd77bf38SGreg Roach    {
73bd77bf38SGreg Roach        $this->user_service = $user_service;
74bd77bf38SGreg Roach    }
75bd77bf38SGreg Roach
76961ec755SGreg Roach    /**
770cfd6963SGreg Roach     * How should this module be identified in the control panel, etc.?
78961ec755SGreg Roach     *
79961ec755SGreg Roach     * @return string
80961ec755SGreg Roach     */
8149a243cbSGreg Roach    public function title(): string
82c1010edaSGreg Roach    {
83bbb76c12SGreg Roach        /* I18N: Name of a module */
84bbb76c12SGreg Roach        return I18N::translate('Recent changes');
858c2e8227SGreg Roach    }
868c2e8227SGreg Roach
8749a243cbSGreg Roach    public function description(): string
88c1010edaSGreg Roach    {
89bbb76c12SGreg Roach        /* I18N: Description of the “Recent changes” module */
90bbb76c12SGreg Roach        return I18N::translate('A list of records that have been updated recently.');
918c2e8227SGreg Roach    }
928c2e8227SGreg Roach
930dcd9387SGreg Roach    /**
940dcd9387SGreg Roach     * @param Tree                 $tree
950dcd9387SGreg Roach     * @param int                  $block_id
960dcd9387SGreg Roach     * @param string               $context
9776d39c55SGreg Roach     * @param array<string,string> $config
980dcd9387SGreg Roach     *
990dcd9387SGreg Roach     * @return string
1000dcd9387SGreg Roach     */
1013caaa4d2SGreg Roach    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
102c1010edaSGreg Roach    {
10355664801SGreg Roach        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
1046e45321fSGreg Roach        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
1056e45321fSGreg Roach        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
106047cb287SGreg Roach        $show_user = (bool) $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
107501bc70dSGreg Roach        $show_date = (bool) $this->getBlockSetting($block_id, 'show_date', self::DEFAULT_SHOW_DATE);
108501bc70dSGreg Roach        $source    = $this->getBlockSetting($block_id, 'source', self::DEFAULT_SOURCE);
1098c2e8227SGreg Roach
1103caaa4d2SGreg Roach        extract($config, EXTR_OVERWRITE);
1118c2e8227SGreg Roach
112501bc70dSGreg Roach        if ($source === self::SOURCE_DATABASE) {
113501bc70dSGreg Roach            $rows = $this->getRecentChangesFromDatabase($tree, $days);
114501bc70dSGreg Roach        } else {
115501bc70dSGreg Roach            $rows = $this->getRecentChangesFromGenealogy($tree, $days);
116501bc70dSGreg Roach        }
1178c2e8227SGreg Roach
1180280f44aSGreg Roach        switch ($sortStyle) {
1190280f44aSGreg Roach            case 'name':
120*d7c2f5ccSGreg Roach                $rows  = $rows->sort(static fn (object $x, object $y): int => GedcomRecord::nameComparator()($x->record, $y->record));
121fbd9d3f8SGreg Roach                $order = [[1, 'asc']];
1228c2e8227SGreg Roach                break;
12380e23601SGreg Roach
1240280f44aSGreg Roach            case 'date_asc':
125*d7c2f5ccSGreg Roach                $rows  = $rows->sort(static fn (object $x, object $y): int => $x->time <=> $y->time);
126fbd9d3f8SGreg Roach                $order = [[2, 'asc']];
1278c2e8227SGreg Roach                break;
12880e23601SGreg Roach
129fbd9d3f8SGreg Roach            default:
1300280f44aSGreg Roach            case 'date_desc':
131*d7c2f5ccSGreg Roach                $rows  = $rows->sort(static fn (object $x, object $y): int => $y->time <=> $x->time);
1321be6d38bSGreg Roach                $order = [[2, 'desc']];
133fbd9d3f8SGreg Roach                break;
1348c2e8227SGreg Roach        }
1350280f44aSGreg Roach
136bd77bf38SGreg Roach        if ($rows->isEmpty()) {
1370280f44aSGreg Roach            $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));
1380280f44aSGreg Roach        } elseif ($infoStyle === 'list') {
1394d2d7d1aSGreg Roach            $content = view('modules/recent_changes/changes-list', [
140e24053e5SGreg Roach                'id'         => $block_id,
14101221f27SGreg Roach                'limit_low'  => self::LIMIT_LOW,
14201221f27SGreg Roach                'limit_high' => self::LIMIT_HIGH,
143e24053e5SGreg Roach                'rows'       => $rows->values(),
144501bc70dSGreg Roach                'show_date'  => $show_date,
1454d2d7d1aSGreg Roach                'show_user'  => $show_user,
1464d2d7d1aSGreg Roach            ]);
1470280f44aSGreg Roach        } else {
1484d2d7d1aSGreg Roach            $content = view('modules/recent_changes/changes-table', [
14901221f27SGreg Roach                'limit_low'  => self::LIMIT_LOW,
15001221f27SGreg Roach                'limit_high' => self::LIMIT_HIGH,
151bd77bf38SGreg Roach                'rows'       => $rows,
152501bc70dSGreg Roach                'show_date'  => $show_date,
1530280f44aSGreg Roach                'show_user'  => $show_user,
154fbd9d3f8SGreg Roach                'order'      => $order,
1550280f44aSGreg Roach            ]);
1568c2e8227SGreg Roach        }
1578c2e8227SGreg Roach
1583caaa4d2SGreg Roach        if ($context !== self::CONTEXT_EMBED) {
159147e99aaSGreg Roach            return view('modules/block-template', [
1601e7a7a28SGreg Roach                'block'      => Str::kebab($this->name()),
1619c6524dcSGreg Roach                'id'         => $block_id,
1623caaa4d2SGreg Roach                'config_url' => $this->configUrl($tree, $context, $block_id),
1638cbbfdceSGreg Roach                'title'      => I18N::plural('Changes in the last %s day', 'Changes in the last %s days', $days, I18N::number($days)),
1649c6524dcSGreg Roach                'content'    => $content,
1659c6524dcSGreg Roach            ]);
1668c2e8227SGreg Roach        }
167b2ce94c6SRico Sonntag
168b2ce94c6SRico Sonntag        return $content;
1698c2e8227SGreg Roach    }
1708c2e8227SGreg Roach
1713caaa4d2SGreg Roach    /**
1723caaa4d2SGreg Roach     * Should this block load asynchronously using AJAX?
1733caaa4d2SGreg Roach     *
1743caaa4d2SGreg Roach     * Simple blocks are faster in-line, more complex ones can be loaded later.
1753caaa4d2SGreg Roach     *
1763caaa4d2SGreg Roach     * @return bool
1773caaa4d2SGreg Roach     */
178c1010edaSGreg Roach    public function loadAjax(): bool
179c1010edaSGreg Roach    {
1808c2e8227SGreg Roach        return true;
1818c2e8227SGreg Roach    }
1828c2e8227SGreg Roach
1833caaa4d2SGreg Roach    /**
1843caaa4d2SGreg Roach     * Can this block be shown on the user’s home page?
1853caaa4d2SGreg Roach     *
1863caaa4d2SGreg Roach     * @return bool
1873caaa4d2SGreg Roach     */
188c1010edaSGreg Roach    public function isUserBlock(): bool
189c1010edaSGreg Roach    {
1908c2e8227SGreg Roach        return true;
1918c2e8227SGreg Roach    }
1928c2e8227SGreg Roach
1933caaa4d2SGreg Roach    /**
1943caaa4d2SGreg Roach     * Can this block be shown on the tree’s home page?
1953caaa4d2SGreg Roach     *
1963caaa4d2SGreg Roach     * @return bool
1973caaa4d2SGreg Roach     */
19863276d8fSGreg Roach    public function isTreeBlock(): bool
199c1010edaSGreg Roach    {
2008c2e8227SGreg Roach        return true;
2018c2e8227SGreg Roach    }
2028c2e8227SGreg Roach
20320ac4041SGreg Roach    /**
204a45f9889SGreg Roach     * Update the configuration for a block.
205a45f9889SGreg Roach     *
2066ccdf4f0SGreg Roach     * @param ServerRequestInterface $request
207a45f9889SGreg Roach     * @param int                    $block_id
208a45f9889SGreg Roach     *
209a45f9889SGreg Roach     * @return void
210a45f9889SGreg Roach     */
2116ccdf4f0SGreg Roach    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
212a45f9889SGreg Roach    {
213748dbe15SGreg Roach        $days       = Validator::parsedBody($request)->integer('days');
214748dbe15SGreg Roach        $info_style = Validator::parsedBody($request)->string('infoStyle');
215748dbe15SGreg Roach        $sort_style = Validator::parsedBody($request)->string('sortStyle');
216748dbe15SGreg Roach        $show_date  = Validator::parsedBody($request)->boolean('show_date');
217748dbe15SGreg Roach        $show_user  = Validator::parsedBody($request)->boolean('show_user');
218748dbe15SGreg Roach        $source     = Validator::parsedBody($request)->string('source');
219af2b6902SGreg Roach
220748dbe15SGreg Roach        $this->setBlockSetting($block_id, 'days', (string) $days);
221748dbe15SGreg Roach        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
222748dbe15SGreg Roach        $this->setBlockSetting($block_id, 'sortStyle', $sort_style);
223748dbe15SGreg Roach        $this->setBlockSetting($block_id, 'show_date', (string) $show_date);
224748dbe15SGreg Roach        $this->setBlockSetting($block_id, 'show_user', (string) $show_user);
225748dbe15SGreg Roach        $this->setBlockSetting($block_id, 'source', $source);
226a45f9889SGreg Roach    }
227a45f9889SGreg Roach
228a45f9889SGreg Roach    /**
22920ac4041SGreg Roach     * An HTML form to edit block settings
23020ac4041SGreg Roach     *
23120ac4041SGreg Roach     * @param Tree $tree
23220ac4041SGreg Roach     * @param int  $block_id
23320ac4041SGreg Roach     *
2343caaa4d2SGreg Roach     * @return string
23520ac4041SGreg Roach     */
2363caaa4d2SGreg Roach    public function editBlockConfiguration(Tree $tree, int $block_id): string
237c1010edaSGreg Roach    {
23855664801SGreg Roach        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
2396e45321fSGreg Roach        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
2406e45321fSGreg Roach        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
241501bc70dSGreg Roach        $show_date = $this->getBlockSetting($block_id, 'show_date', self::DEFAULT_SHOW_DATE);
2426e45321fSGreg Roach        $show_user = $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
243501bc70dSGreg Roach        $source    = $this->getBlockSetting($block_id, 'source', self::DEFAULT_SOURCE);
2448c2e8227SGreg Roach
245c385536dSGreg Roach        $info_styles = [
246bbb76c12SGreg Roach            /* I18N: An option in a list-box */
247bbb76c12SGreg Roach            'list'  => I18N::translate('list'),
248bbb76c12SGreg Roach            /* I18N: An option in a list-box */
249bbb76c12SGreg Roach            'table' => I18N::translate('table'),
250c385536dSGreg Roach        ];
2518c2e8227SGreg Roach
252c385536dSGreg Roach        $sort_styles = [
253bbb76c12SGreg Roach            /* I18N: An option in a list-box */
254bbb76c12SGreg Roach            'name'      => I18N::translate('sort by name'),
255bbb76c12SGreg Roach            /* I18N: An option in a list-box */
256bbb76c12SGreg Roach            'date_asc'  => I18N::translate('sort by date, oldest first'),
257bbb76c12SGreg Roach            /* I18N: An option in a list-box */
258bbb76c12SGreg Roach            'date_desc' => I18N::translate('sort by date, newest first'),
259c385536dSGreg Roach        ];
2608c2e8227SGreg Roach
261501bc70dSGreg Roach        $sources = [
262501bc70dSGreg Roach            /* I18N: An option in a list-box */
263501bc70dSGreg Roach            self::SOURCE_DATABASE => I18N::translate('show changes made in webtrees'),
264501bc70dSGreg Roach            /* I18N: An option in a list-box */
265501bc70dSGreg Roach            self::SOURCE_GEDCOM   => I18N::translate('show changes recorded in the genealogy data'),
266501bc70dSGreg Roach        ];
267501bc70dSGreg Roach
2683caaa4d2SGreg Roach        return view('modules/recent_changes/config', [
269c385536dSGreg Roach            'days'        => $days,
270c385536dSGreg Roach            'infoStyle'   => $infoStyle,
271c385536dSGreg Roach            'info_styles' => $info_styles,
272c385536dSGreg Roach            'max_days'    => self::MAX_DAYS,
273c385536dSGreg Roach            'sortStyle'   => $sortStyle,
274c385536dSGreg Roach            'sort_styles' => $sort_styles,
275501bc70dSGreg Roach            'source'      => $source,
276501bc70dSGreg Roach            'sources'     => $sources,
277501bc70dSGreg Roach            'show_date'   => $show_date,
278c385536dSGreg Roach            'show_user'   => $show_user,
279c385536dSGreg Roach        ]);
2808c2e8227SGreg Roach    }
2818c2e8227SGreg Roach
2826e45321fSGreg Roach    /**
2836e45321fSGreg Roach     * Find records that have changed since a given julian day
2846e45321fSGreg Roach     *
2856e45321fSGreg Roach     * @param Tree $tree Changes for which tree
28624319d9dSGreg Roach     * @param int  $days Number of days
2876e45321fSGreg Roach     *
288*d7c2f5ccSGreg Roach     * @return Collection<array-key,object> List of records with changes
2896e45321fSGreg Roach     */
290501bc70dSGreg Roach    private function getRecentChangesFromDatabase(Tree $tree, int $days): Collection
291c1010edaSGreg Roach    {
292bd77bf38SGreg Roach        $subquery = DB::table('change')
29377654037SGreg Roach            ->where('gedcom_id', '=', $tree->id())
29477654037SGreg Roach            ->where('status', '=', 'accepted')
29577654037SGreg Roach            ->where('new_gedcom', '<>', '')
296d97083feSGreg Roach            ->where('change_time', '>', Registry::timestampFactory()->now()->subtractDays($days)->toDateTimeString())
2977f5c2944SGreg Roach            ->groupBy(['xref'])
298059898c9SGreg Roach            ->select([new Expression('MAX(change_id) AS recent_change_id')]);
299bd77bf38SGreg Roach
300bd77bf38SGreg Roach        $query = DB::table('change')
301bd77bf38SGreg Roach            ->joinSub($subquery, 'recent', 'recent_change_id', '=', 'change_id')
302bd77bf38SGreg Roach            ->select(['change.*']);
303bd77bf38SGreg Roach
304bd77bf38SGreg Roach        return $query
305bd77bf38SGreg Roach            ->get()
306f25fc0f9SGreg Roach            ->map(fn (object $row): object => (object) [
3076b9cb339SGreg Roach                'record' => Registry::gedcomRecordFactory()->make($row->xref, $tree, $row->new_gedcom),
308d97083feSGreg Roach                'time'   => Registry::timestampFactory()->fromString($row->change_time),
309d608cecbSGreg Roach                'user'   => $this->user_service->find((int) $row->user_id),
310f25fc0f9SGreg Roach            ])
311f25fc0f9SGreg Roach            ->filter(static fn (object $row): bool => $row->record instanceof GedcomRecord && $row->record->canShow());
3126e45321fSGreg Roach    }
313501bc70dSGreg Roach
314501bc70dSGreg Roach    /**
315501bc70dSGreg Roach     * Find records that have changed since a given julian day
316501bc70dSGreg Roach     *
317501bc70dSGreg Roach     * @param Tree $tree Changes for which tree
318501bc70dSGreg Roach     * @param int  $days Number of days
319501bc70dSGreg Roach     *
320*d7c2f5ccSGreg Roach     * @return Collection<array-key,object> List of records with changes
321501bc70dSGreg Roach     */
322501bc70dSGreg Roach    private function getRecentChangesFromGenealogy(Tree $tree, int $days): Collection
323501bc70dSGreg Roach    {
324d97083feSGreg Roach        $julian_day = Registry::timestampFactory()->now()->subtractDays($days)->julianDay();
325501bc70dSGreg Roach
326501bc70dSGreg Roach        $individuals = DB::table('dates')
327501bc70dSGreg Roach            ->where('d_file', '=', $tree->id())
328501bc70dSGreg Roach            ->where('d_julianday1', '>=', $julian_day)
329501bc70dSGreg Roach            ->where('d_fact', '=', 'CHAN')
330501bc70dSGreg Roach            ->join('individuals', static function (JoinClause $join): void {
331501bc70dSGreg Roach                $join
332501bc70dSGreg Roach                    ->on('d_file', '=', 'i_file')
333501bc70dSGreg Roach                    ->on('d_gid', '=', 'i_id');
334501bc70dSGreg Roach            })
335501bc70dSGreg Roach            ->select(['individuals.*'])
336501bc70dSGreg Roach            ->get()
3376b9cb339SGreg Roach            ->map(Registry::individualFactory()->mapper($tree))
338501bc70dSGreg Roach            ->filter(Individual::accessFilter());
339501bc70dSGreg Roach
340501bc70dSGreg Roach        $families = DB::table('dates')
341501bc70dSGreg Roach            ->where('d_file', '=', $tree->id())
342501bc70dSGreg Roach            ->where('d_julianday1', '>=', $julian_day)
343501bc70dSGreg Roach            ->where('d_fact', '=', 'CHAN')
344501bc70dSGreg Roach            ->join('families', static function (JoinClause $join): void {
345501bc70dSGreg Roach                $join
346501bc70dSGreg Roach                    ->on('d_file', '=', 'f_file')
347501bc70dSGreg Roach                    ->on('d_gid', '=', 'f_id');
348501bc70dSGreg Roach            })
349501bc70dSGreg Roach            ->select(['families.*'])
350501bc70dSGreg Roach            ->get()
3516b9cb339SGreg Roach            ->map(Registry::familyFactory()->mapper($tree))
352501bc70dSGreg Roach            ->filter(Family::accessFilter());
353501bc70dSGreg Roach
354501bc70dSGreg Roach        return $individuals->merge($families)
355f70bcff5SGreg Roach            ->map(function (GedcomRecord $record): object {
356e10e1dc9SGreg Roach                $user = $this->user_service->findByUserName($record->lastChangeUser());
357e10e1dc9SGreg Roach
358501bc70dSGreg Roach                return (object) [
359501bc70dSGreg Roach                    'record' => $record,
360501bc70dSGreg Roach                    'time'   => $record->lastChangeTimestamp(),
361e10e1dc9SGreg Roach                    'user'   => $user ?? new User(0, '…', '…', ''),
362501bc70dSGreg Roach                ];
363501bc70dSGreg Roach            });
364501bc70dSGreg Roach    }
3658c2e8227SGreg Roach}
366