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