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