xref: /webtrees/app/Module/RecentChangesModule.php (revision bb03c9f048b83092098d5e46c2ab323ae7e2b314)
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\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    /**
92     * @param Tree   $tree
93     * @param int    $block_id
94     * @param string $context
95     * @param array  $config
96     *
97     * @return string
98     */
99    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
100    {
101        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
102        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
103        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
104        $show_user = (bool) $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
105
106        extract($config, EXTR_OVERWRITE);
107
108        $rows = $this->getRecentChanges($tree, $days);
109
110        switch ($sortStyle) {
111            case 'name':
112                $rows = $rows->sort(static function (stdClass $x, stdClass $y): int {
113                    return GedcomRecord::nameComparator()($x->record, $y->record);
114                });
115                $order = [[1, 'asc']];
116                break;
117
118            case 'date_asc':
119                $rows = $rows->sort(static function (stdClass $x, stdClass $y): int {
120                    return $x->time <=> $y->time;
121                });
122                $order = [[2, 'asc']];
123                break;
124
125            default:
126            case 'date_desc':
127                $rows = $rows->sort(static function (stdClass $x, stdClass $y): int {
128                    return $y->time <=> $x->time;
129                });
130                $order = [[2, 'desc']];
131                break;
132        }
133
134        if ($rows->isEmpty()) {
135            $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));
136        } elseif ($infoStyle === 'list') {
137            $content = view('modules/recent_changes/changes-list', [
138                'id'         => $block_id,
139                'limit_low'  => self::LIMIT_LOW,
140                'limit_high' => self::LIMIT_HIGH,
141                'rows'       => $rows->values(),
142                'show_user'  => $show_user,
143            ]);
144        } else {
145            $content = view('modules/recent_changes/changes-table', [
146                'limit_low'  => self::LIMIT_LOW,
147                'limit_high' => self::LIMIT_HIGH,
148                'rows'       => $rows,
149                'show_user'  => $show_user,
150                'order'      => $order,
151            ]);
152        }
153
154        if ($context !== self::CONTEXT_EMBED) {
155            return view('modules/block-template', [
156                'block'      => Str::kebab($this->name()),
157                'id'         => $block_id,
158                'config_url' => $this->configUrl($tree, $context, $block_id),
159                'title'      => I18N::plural('Changes in the last %s day', 'Changes in the last %s days', $days, I18N::number($days)),
160                'content'    => $content,
161            ]);
162        }
163
164        return $content;
165    }
166
167    /**
168     * Should this block load asynchronously using AJAX?
169     *
170     * Simple blocks are faster in-line, more complex ones can be loaded later.
171     *
172     * @return bool
173     */
174    public function loadAjax(): bool
175    {
176        return true;
177    }
178
179    /**
180     * Can this block be shown on the user’s home page?
181     *
182     * @return bool
183     */
184    public function isUserBlock(): bool
185    {
186        return true;
187    }
188
189    /**
190     * Can this block be shown on the tree’s home page?
191     *
192     * @return bool
193     */
194    public function isTreeBlock(): bool
195    {
196        return true;
197    }
198
199    /**
200     * Update the configuration for a block.
201     *
202     * @param ServerRequestInterface $request
203     * @param int     $block_id
204     *
205     * @return void
206     */
207    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
208    {
209        $params = (array) $request->getParsedBody();
210
211        $this->setBlockSetting($block_id, 'days', $params['days']);
212        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
213        $this->setBlockSetting($block_id, 'sortStyle', $params['sortStyle']);
214        $this->setBlockSetting($block_id, 'show_user', $params['show_user']);
215    }
216
217    /**
218     * An HTML form to edit block settings
219     *
220     * @param Tree $tree
221     * @param int  $block_id
222     *
223     * @return string
224     */
225    public function editBlockConfiguration(Tree $tree, int $block_id): string
226    {
227        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
228        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
229        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
230        $show_user = $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
231
232        $info_styles = [
233            /* I18N: An option in a list-box */
234            'list'  => I18N::translate('list'),
235            /* I18N: An option in a list-box */
236            'table' => I18N::translate('table'),
237        ];
238
239        $sort_styles = [
240            /* I18N: An option in a list-box */
241            'name'      => I18N::translate('sort by name'),
242            /* I18N: An option in a list-box */
243            'date_asc'  => I18N::translate('sort by date, oldest first'),
244            /* I18N: An option in a list-box */
245            'date_desc' => I18N::translate('sort by date, newest first'),
246        ];
247
248        return view('modules/recent_changes/config', [
249            'days'        => $days,
250            'infoStyle'   => $infoStyle,
251            'info_styles' => $info_styles,
252            'max_days'    => self::MAX_DAYS,
253            'sortStyle'   => $sortStyle,
254            'sort_styles' => $sort_styles,
255            'show_user'   => $show_user,
256        ]);
257    }
258
259    /**
260     * Find records that have changed since a given julian day
261     *
262     * @param Tree $tree Changes for which tree
263     * @param int  $days Number of days
264     *
265     * @return Collection<stdClass> List of records with changes
266     */
267    private function getRecentChanges(Tree $tree, int $days): Collection
268    {
269        $subquery = DB::table('change')
270            ->where('gedcom_id', '=', $tree->id())
271            ->where('status', '=', 'accepted')
272            ->where('new_gedcom', '<>', '')
273            ->where('change_time', '>', Carbon::now()->subDays($days))
274            ->groupBy(['xref'])
275            ->select(new Expression('MAX(change_id) AS recent_change_id'));
276
277        $query = DB::table('change')
278            ->joinSub($subquery, 'recent', 'recent_change_id', '=', 'change_id')
279            ->select(['change.*']);
280
281        return $query
282            ->get()
283            ->map(function (stdClass $row) use ($tree): stdClass {
284                return (object) [
285                    'record' => GedcomRecord::getInstance($row->xref, $tree, $row->new_gedcom),
286                    'time'   => Carbon::create($row->change_time)->local(),
287                    'user'   => $this->user_service->find($row->user_id),
288                ];
289            })
290            ->filter(static function (stdClass $row): bool {
291                return $row->record instanceof GedcomRecord && $row->record->canShow();
292            });
293    }
294}
295