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