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