Passed
Push — master ( 45f711...bd77bf )
by Greg
05:27
created

RecentChangesModule   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 92
dl 0
loc 228
rs 10
c 0
b 0
f 0
wmc 17

10 Methods

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