xref: /webtrees/app/Module/RecentChangesModule.php (revision a091ac74647eab281b25090b737835eeea14ae10)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\Carbon;
23use Fisharebest\Webtrees\Factory;
24use Fisharebest\Webtrees\GedcomRecord;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Services\UserService;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Database\Capsule\Manager as DB;
29use Illuminate\Database\Query\Expression;
30use Illuminate\Support\Collection;
31use Illuminate\Support\Str;
32use Psr\Http\Message\ServerRequestInterface;
33use stdClass;
34
35use function extract;
36use function view;
37
38use const EXTR_OVERWRITE;
39
40/**
41 * Class RecentChangesModule
42 */
43class RecentChangesModule extends AbstractModule implements ModuleBlockInterface
44{
45    use ModuleBlockTrait;
46
47    private const DEFAULT_DAYS       = '7';
48    private const DEFAULT_SHOW_USER  = '1';
49    private const DEFAULT_SORT_STYLE = 'date_desc';
50    private const DEFAULT_INFO_STYLE = 'table';
51    private const MAX_DAYS           = 90;
52
53    // Pagination
54    private const LIMIT_LOW  = 10;
55    private const LIMIT_HIGH = 20;
56
57    /** @var UserService */
58    private $user_service;
59
60    /**
61     * RecentChangesModule constructor.
62     *
63     * @param UserService $user_service
64     */
65    public function __construct(UserService $user_service)
66    {
67        $this->user_service = $user_service;
68    }
69
70    /**
71     * How should this module be identified in the control panel, etc.?
72     *
73     * @return string
74     */
75    public function title(): string
76    {
77        /* I18N: Name of a module */
78        return I18N::translate('Recent changes');
79    }
80
81    /**
82     * A sentence describing what this module does.
83     *
84     * @return string
85     */
86    public function description(): string
87    {
88        /* I18N: Description of the “Recent changes” module */
89        return I18N::translate('A list of records that have been updated recently.');
90    }
91
92    /**
93     * @param Tree   $tree
94     * @param int    $block_id
95     * @param string $context
96     * @param array  $config
97     *
98     * @return string
99     */
100    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
101    {
102        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
103        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
104        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
105        $show_user = (bool) $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
106
107        extract($config, EXTR_OVERWRITE);
108
109        $rows = $this->getRecentChanges($tree, $days);
110
111        switch ($sortStyle) {
112            case 'name':
113                $rows = $rows->sort(static function (stdClass $x, stdClass $y): int {
114                    return GedcomRecord::nameComparator()($x->record, $y->record);
115                });
116                $order = [[1, 'asc']];
117                break;
118
119            case 'date_asc':
120                $rows = $rows->sort(static function (stdClass $x, stdClass $y): int {
121                    return $x->time <=> $y->time;
122                });
123                $order = [[2, 'asc']];
124                break;
125
126            default:
127            case 'date_desc':
128                $rows = $rows->sort(static function (stdClass $x, stdClass $y): int {
129                    return $y->time <=> $x->time;
130                });
131                $order = [[2, 'desc']];
132                break;
133        }
134
135        if ($rows->isEmpty()) {
136            $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));
137        } elseif ($infoStyle === 'list') {
138            $content = view('modules/recent_changes/changes-list', [
139                'id'         => $block_id,
140                'limit_low'  => self::LIMIT_LOW,
141                'limit_high' => self::LIMIT_HIGH,
142                'rows'       => $rows->values(),
143                'show_user'  => $show_user,
144            ]);
145        } else {
146            $content = view('modules/recent_changes/changes-table', [
147                'limit_low'  => self::LIMIT_LOW,
148                'limit_high' => self::LIMIT_HIGH,
149                'rows'       => $rows,
150                'show_user'  => $show_user,
151                'order'      => $order,
152            ]);
153        }
154
155        if ($context !== self::CONTEXT_EMBED) {
156            return view('modules/block-template', [
157                'block'      => Str::kebab($this->name()),
158                'id'         => $block_id,
159                'config_url' => $this->configUrl($tree, $context, $block_id),
160                'title'      => I18N::plural('Changes in the last %s day', 'Changes in the last %s days', $days, I18N::number($days)),
161                'content'    => $content,
162            ]);
163        }
164
165        return $content;
166    }
167
168    /**
169     * Should this block load asynchronously using AJAX?
170     *
171     * Simple blocks are faster in-line, more complex ones can be loaded later.
172     *
173     * @return bool
174     */
175    public function loadAjax(): bool
176    {
177        return true;
178    }
179
180    /**
181     * Can this block be shown on the user’s home page?
182     *
183     * @return bool
184     */
185    public function isUserBlock(): bool
186    {
187        return true;
188    }
189
190    /**
191     * Can this block be shown on the tree’s home page?
192     *
193     * @return bool
194     */
195    public function isTreeBlock(): bool
196    {
197        return true;
198    }
199
200    /**
201     * Update the configuration for a block.
202     *
203     * @param ServerRequestInterface $request
204     * @param int     $block_id
205     *
206     * @return void
207     */
208    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
209    {
210        $params = (array) $request->getParsedBody();
211
212        $this->setBlockSetting($block_id, 'days', $params['days']);
213        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
214        $this->setBlockSetting($block_id, 'sortStyle', $params['sortStyle']);
215        $this->setBlockSetting($block_id, 'show_user', $params['show_user']);
216    }
217
218    /**
219     * An HTML form to edit block settings
220     *
221     * @param Tree $tree
222     * @param int  $block_id
223     *
224     * @return string
225     */
226    public function editBlockConfiguration(Tree $tree, int $block_id): string
227    {
228        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
229        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
230        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
231        $show_user = $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
232
233        $info_styles = [
234            /* I18N: An option in a list-box */
235            'list'  => I18N::translate('list'),
236            /* I18N: An option in a list-box */
237            'table' => I18N::translate('table'),
238        ];
239
240        $sort_styles = [
241            /* I18N: An option in a list-box */
242            'name'      => I18N::translate('sort by name'),
243            /* I18N: An option in a list-box */
244            'date_asc'  => I18N::translate('sort by date, oldest first'),
245            /* I18N: An option in a list-box */
246            'date_desc' => I18N::translate('sort by date, newest first'),
247        ];
248
249        return view('modules/recent_changes/config', [
250            'days'        => $days,
251            'infoStyle'   => $infoStyle,
252            'info_styles' => $info_styles,
253            'max_days'    => self::MAX_DAYS,
254            'sortStyle'   => $sortStyle,
255            'sort_styles' => $sort_styles,
256            'show_user'   => $show_user,
257        ]);
258    }
259
260    /**
261     * Find records that have changed since a given julian day
262     *
263     * @param Tree $tree Changes for which tree
264     * @param int  $days Number of days
265     *
266     * @return Collection<stdClass> List of records with changes
267     */
268    private function getRecentChanges(Tree $tree, int $days): Collection
269    {
270        $subquery = DB::table('change')
271            ->where('gedcom_id', '=', $tree->id())
272            ->where('status', '=', 'accepted')
273            ->where('new_gedcom', '<>', '')
274            ->where('change_time', '>', Carbon::now()->subDays($days))
275            ->groupBy(['xref'])
276            ->select(new Expression('MAX(change_id) AS recent_change_id'));
277
278        $query = DB::table('change')
279            ->joinSub($subquery, 'recent', 'recent_change_id', '=', 'change_id')
280            ->select(['change.*']);
281
282        return $query
283            ->get()
284            ->map(function (stdClass $row) use ($tree): stdClass {
285                return (object) [
286                    'record' => Factory::gedcomRecord()->make($row->xref, $tree, $row->new_gedcom),
287                    'time'   => Carbon::create($row->change_time)->local(),
288                    'user'   => $this->user_service->find($row->user_id),
289                ];
290            })
291            ->filter(static function (stdClass $row): bool {
292                return $row->record instanceof GedcomRecord && $row->record->canShow();
293            });
294    }
295}
296