xref: /webtrees/app/Module/RecentChangesModule.php (revision 2b47189bb11817638683564e5058e5019f413146)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Fisharebest\Webtrees\Carbon;
21use Fisharebest\Webtrees\GedcomRecord;
22use Fisharebest\Webtrees\I18N;
23use Fisharebest\Webtrees\Tree;
24use Illuminate\Database\Capsule\Manager as DB;
25use Illuminate\Support\Str;
26use Psr\Http\Message\ServerRequestInterface;
27
28/**
29 * Class RecentChangesModule
30 */
31class RecentChangesModule extends AbstractModule implements ModuleBlockInterface
32{
33    use ModuleBlockTrait;
34
35    private const DEFAULT_DAYS       = '7';
36    private const DEFAULT_SHOW_USER  = '1';
37    private const DEFAULT_SORT_STYLE = 'date_desc';
38    private const DEFAULT_INFO_STYLE = 'table';
39    private const MAX_DAYS           = 90;
40
41    /**
42     * How should this module be identified in the control panel, etc.?
43     *
44     * @return string
45     */
46    public function title(): string
47    {
48        /* I18N: Name of a module */
49        return I18N::translate('Recent changes');
50    }
51
52    /**
53     * A sentence describing what this module does.
54     *
55     * @return string
56     */
57    public function description(): string
58    {
59        /* I18N: Description of the “Recent changes” module */
60        return I18N::translate('A list of records that have been updated recently.');
61    }
62
63    /** {@inheritdoc} */
64    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
65    {
66        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
67        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
68        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
69        $show_user = (bool) $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
70
71        extract($config, EXTR_OVERWRITE);
72
73        $records = $this->getRecentChanges($tree, $days);
74
75        switch ($sortStyle) {
76            case 'name':
77                uasort($records, GedcomRecord::nameComparator());
78                break;
79
80            case 'date_asc':
81                uasort($records, GedcomRecord::lastChangeComparator());
82                break;
83
84            case 'date_desc':
85                uasort($records, GedcomRecord::lastChangeComparator(-1));
86        }
87
88        if (empty($records)) {
89            $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));
90        } elseif ($infoStyle === 'list') {
91            $content = view('modules/recent_changes/changes-list', [
92                'records'   => $records,
93                'show_user' => $show_user,
94            ]);
95        } else {
96            $content = view('modules/recent_changes/changes-table', [
97                'records'   => $records,
98                'show_user' => $show_user,
99            ]);
100        }
101
102        if ($context !== self::CONTEXT_EMBED) {
103            return view('modules/block-template', [
104                'block'      => Str::kebab($this->name()),
105                'id'         => $block_id,
106                'config_url' => $this->configUrl($tree, $context, $block_id),
107                'title'      => I18N::plural('Changes in the last %s day', 'Changes in the last %s days', $days, I18N::number($days)),
108                'content'    => $content,
109            ]);
110        }
111
112        return $content;
113    }
114
115    /**
116     * Should this block load asynchronously using AJAX?
117     *
118     * Simple blocks are faster in-line, more complex ones can be loaded later.
119     *
120     * @return bool
121     */
122    public function loadAjax(): bool
123    {
124        return true;
125    }
126
127    /**
128     * Can this block be shown on the user’s home page?
129     *
130     * @return bool
131     */
132    public function isUserBlock(): bool
133    {
134        return true;
135    }
136
137    /**
138     * Can this block be shown on the tree’s home page?
139     *
140     * @return bool
141     */
142    public function isTreeBlock(): bool
143    {
144        return true;
145    }
146
147    /**
148     * Update the configuration for a block.
149     *
150     * @param ServerRequestInterface $request
151     * @param int     $block_id
152     *
153     * @return void
154     */
155    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
156    {
157        $params = $request->getParsedBody();
158
159        $this->setBlockSetting($block_id, 'days', $params['days']);
160        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
161        $this->setBlockSetting($block_id, 'sortStyle', $params['sortStyle']);
162        $this->setBlockSetting($block_id, 'show_user', $params['show_user']);
163    }
164
165    /**
166     * An HTML form to edit block settings
167     *
168     * @param Tree $tree
169     * @param int  $block_id
170     *
171     * @return string
172     */
173    public function editBlockConfiguration(Tree $tree, int $block_id): string
174    {
175        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
176        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
177        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
178        $show_user = $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
179
180        $info_styles = [
181            /* I18N: An option in a list-box */
182            'list'  => I18N::translate('list'),
183            /* I18N: An option in a list-box */
184            'table' => I18N::translate('table'),
185        ];
186
187        $sort_styles = [
188            /* I18N: An option in a list-box */
189            'name'      => I18N::translate('sort by name'),
190            /* I18N: An option in a list-box */
191            'date_asc'  => I18N::translate('sort by date, oldest first'),
192            /* I18N: An option in a list-box */
193            'date_desc' => I18N::translate('sort by date, newest first'),
194        ];
195
196        return view('modules/recent_changes/config', [
197            'days'        => $days,
198            'infoStyle'   => $infoStyle,
199            'info_styles' => $info_styles,
200            'max_days'    => self::MAX_DAYS,
201            'sortStyle'   => $sortStyle,
202            'sort_styles' => $sort_styles,
203            'show_user'   => $show_user,
204        ]);
205    }
206
207    /**
208     * Find records that have changed since a given julian day
209     *
210     * @param Tree $tree Changes for which tree
211     * @param int  $days Number of days
212     *
213     * @return GedcomRecord[] List of records with changes
214     */
215    private function getRecentChanges(Tree $tree, int $days): array
216    {
217        return DB::table('change')
218            ->where('gedcom_id', '=', $tree->id())
219            ->where('status', '=', 'accepted')
220            ->where('new_gedcom', '<>', '')
221            ->where('change_time', '>', Carbon::now()->subDays($days))
222            ->groupBy(['xref'])
223            ->pluck('xref')
224            ->map(static function (string $xref) use ($tree): ?GedcomRecord {
225                return GedcomRecord::getInstance($xref, $tree);
226            })
227            ->filter(static function (?GedcomRecord $record): bool {
228                return $record instanceof GedcomRecord && $record->canShow();
229            })
230            ->all();
231    }
232}
233