xref: /webtrees/app/Module/RecentChangesModule.php (revision e7f56f2af615447ab1a7646851f88b465ace9e04)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 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\Auth;
21use Fisharebest\Webtrees\Database;
22use Fisharebest\Webtrees\GedcomRecord;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Tree;
25use Symfony\Component\HttpFoundation\Request;
26
27/**
28 * Class RecentChangesModule
29 */
30class RecentChangesModule extends AbstractModule implements ModuleBlockInterface
31{
32    const DEFAULT_BLOCK      = '1';
33    const DEFAULT_DAYS       = '7';
34    const DEFAULT_HIDE_EMPTY = '0';
35    const DEFAULT_SHOW_USER  = '1';
36    const DEFAULT_SORT_STYLE = 'date_desc';
37    const DEFAULT_INFO_STYLE = 'table';
38    const MAX_DAYS           = 90;
39
40    /** {@inheritdoc} */
41    public function getTitle(): string
42    {
43        /* I18N: Name of a module */
44        return I18N::translate('Recent changes');
45    }
46
47    /** {@inheritdoc} */
48    public function getDescription(): string
49    {
50        /* I18N: Description of the “Recent changes” module */
51        return I18N::translate('A list of records that have been updated recently.');
52    }
53
54    /** {@inheritdoc} */
55    public function getBlock(Tree $tree, int $block_id, bool $template = true, array $cfg = []): string
56    {
57        global $ctype;
58
59        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
60        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
61        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
62        $show_user = (bool) $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
63
64        extract($cfg, EXTR_OVERWRITE);
65
66        $records = $this->getRecentChanges($tree, $days);
67
68        switch ($sortStyle) {
69            case 'name':
70                uasort($records, ['self', 'sortByNameAndChangeDate']);
71                break;
72            case 'date_asc':
73                uasort($records, ['self', 'sortByChangeDateAndName']);
74                $records = array_reverse($records);
75                break;
76            case 'date_desc':
77                uasort($records, ['self', 'sortByChangeDateAndName']);
78        }
79
80        if (empty($records)) {
81            $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));
82        } elseif ($infoStyle === 'list') {
83            $content = view('modules/recent_changes/changes-list', [
84                'records'   => $records,
85                'show_user' => $show_user,
86            ]);
87        } else {
88            $content = view('modules/recent_changes/changes-table', [
89                'records'   => $records,
90                'show_user' => $show_user,
91            ]);
92        }
93
94        if ($template) {
95            if ($ctype === 'gedcom' && Auth::isManager($tree)) {
96                $config_url = route('tree-page-block-edit', [
97                    'block_id' => $block_id,
98                    'ged'      => $tree->getName(),
99                ]);
100            } elseif ($ctype === 'user' && Auth::check()) {
101                $config_url = route('user-page-block-edit', [
102                    'block_id' => $block_id,
103                    'ged'      => $tree->getName(),
104                ]);
105            } else {
106                $config_url = '';
107            }
108
109            return view('modules/block-template', [
110                'block'      => str_replace('_', '-', $this->getName()),
111                'id'         => $block_id,
112                'config_url' => $config_url,
113                'title'      => I18N::plural('Changes in the last %s day', 'Changes in the last %s days', $days, I18N::number($days)),
114                'content'    => $content,
115            ]);
116        }
117
118        return $content;
119    }
120
121    /** {@inheritdoc} */
122    public function loadAjax(): bool
123    {
124        return true;
125    }
126
127    /** {@inheritdoc} */
128    public function isUserBlock(): bool
129    {
130        return true;
131    }
132
133    /** {@inheritdoc} */
134    public function isGedcomBlock(): bool
135    {
136        return true;
137    }
138
139    /**
140     * Update the configuration for a block.
141     *
142     * @param Request $request
143     * @param int     $block_id
144     *
145     * @return void
146     */
147    public function saveBlockConfiguration(Request $request, int $block_id)
148    {
149        $days = $request->get('days', self::DEFAULT_DAYS);
150
151        if ((int) $days > self::MAX_DAYS || (int) $days < 1) {
152            $days = self::DEFAULT_DAYS;
153        }
154
155        $this->setBlockSetting($block_id, 'days', $days);
156        $this->setBlockSetting($block_id, 'infoStyle', $request->get('infoStyle', self::DEFAULT_INFO_STYLE));
157        $this->setBlockSetting($block_id, 'sortStyle', $request->get('sortStyle', self::DEFAULT_SORT_STYLE));
158        $this->setBlockSetting($block_id, 'show_user', $request->get('show_user', self::DEFAULT_SHOW_USER));
159    }
160
161    /**
162     * An HTML form to edit block settings
163     *
164     * @param Tree $tree
165     * @param int  $block_id
166     *
167     * @return void
168     */
169    public function editBlockConfiguration(Tree $tree, int $block_id)
170    {
171        $days      = (int) $this->getBlockSetting($block_id, 'days', self::DEFAULT_DAYS);
172        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_INFO_STYLE);
173        $sortStyle = $this->getBlockSetting($block_id, 'sortStyle', self::DEFAULT_SORT_STYLE);
174        $show_user = $this->getBlockSetting($block_id, 'show_user', self::DEFAULT_SHOW_USER);
175
176        $info_styles = [
177            /* I18N: An option in a list-box */
178            'list'  => I18N::translate('list'),
179            /* I18N: An option in a list-box */
180            'table' => I18N::translate('table'),
181        ];
182
183        $sort_styles = [
184            /* I18N: An option in a list-box */
185            'name'      => I18N::translate('sort by name'),
186            /* I18N: An option in a list-box */
187            'date_asc'  => I18N::translate('sort by date, oldest first'),
188            /* I18N: An option in a list-box */
189            'date_desc' => I18N::translate('sort by date, newest first'),
190        ];
191
192        echo view('modules/recent_changes/config', [
193            'days'        => $days,
194            'infoStyle'   => $infoStyle,
195            'info_styles' => $info_styles,
196            'max_days'    => self::MAX_DAYS,
197            'sortStyle'   => $sortStyle,
198            'sort_styles' => $sort_styles,
199            'show_user'   => $show_user,
200        ]);
201    }
202
203    /**
204     * Find records that have changed since a given julian day
205     *
206     * @param Tree $tree Changes for which tree
207     * @param int  $days Number of days
208     *
209     * @return GedcomRecord[] List of records with changes
210     */
211    private function getRecentChanges(Tree $tree, int $days): array
212    {
213        $sql =
214            "SELECT xref FROM `##change`" .
215            " WHERE new_gedcom != '' AND change_time > DATE_SUB(NOW(), INTERVAL :days DAY) AND gedcom_id = :tree_id" .
216            " GROUP BY xref" .
217            " ORDER BY MAX(change_id) DESC";
218
219        $vars = [
220            'days'    => $days,
221            'tree_id' => $tree->getTreeId(),
222        ];
223
224        $xrefs = Database::prepare($sql)->execute($vars)->fetchOneColumn();
225
226        $records = [];
227        foreach ($xrefs as $xref) {
228            $record = GedcomRecord::getInstance($xref, $tree);
229            if ($record && $record->canShow()) {
230                $records[] = $record;
231            }
232        }
233
234        return $records;
235    }
236
237    /**
238     * Sort the records by (1) last change date and (2) name
239     *
240     * @param GedcomRecord $a
241     * @param GedcomRecord $b
242     *
243     * @return int
244     */
245    private static function sortByChangeDateAndName(GedcomRecord $a, GedcomRecord $b): int
246    {
247        return $b->lastChangeTimestamp(true) - $a->lastChangeTimestamp(true) ?: GedcomRecord::compare($a, $b);
248    }
249
250    /**
251     * Sort the records by (1) name and (2) last change date
252     *
253     * @param GedcomRecord $a
254     * @param GedcomRecord $b
255     *
256     * @return int
257     */
258    private static function sortByNameAndChangeDate(GedcomRecord $a, GedcomRecord $b): int
259    {
260        return GedcomRecord::compare($a, $b) ?: $b->lastChangeTimestamp(true) - $a->lastChangeTimestamp(true);
261    }
262}
263