xref: /webtrees/app/Module/ReviewChangesModule.php (revision c540224494b4c0b9f7d890f59f1cd44e9f6d92ea)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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 <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Contracts\UserInterface;
24use Fisharebest\Webtrees\Http\RequestHandlers\PendingChanges;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Services\EmailService;
28use Fisharebest\Webtrees\Services\MessageService;
29use Fisharebest\Webtrees\Services\TreeService;
30use Fisharebest\Webtrees\Services\UserService;
31use Fisharebest\Webtrees\Site;
32use Fisharebest\Webtrees\SiteUser;
33use Fisharebest\Webtrees\Tree;
34use Fisharebest\Webtrees\TreeUser;
35use Fisharebest\Webtrees\Validator;
36use Illuminate\Database\Capsule\Manager as DB;
37use Illuminate\Database\Query\Builder;
38use Illuminate\Database\Query\Expression;
39use Illuminate\Support\Str;
40use Psr\Http\Message\ServerRequestInterface;
41
42use function time;
43
44/**
45 * Class ReviewChangesModule
46 */
47class ReviewChangesModule extends AbstractModule implements ModuleBlockInterface
48{
49    use ModuleBlockTrait;
50
51    private EmailService $email_service;
52
53    private UserService $user_service;
54
55    private TreeService $tree_service;
56
57    /**
58     * ReviewChangesModule constructor.
59     *
60     * @param EmailService $email_service
61     * @param TreeService  $tree_service
62     * @param UserService  $user_service
63     */
64    public function __construct(
65        EmailService $email_service,
66        TreeService $tree_service,
67        UserService $user_service
68    ) {
69        $this->email_service = $email_service;
70        $this->tree_service  = $tree_service;
71        $this->user_service  = $user_service;
72    }
73
74    /**
75     * How should this module be identified in the control panel, etc.?
76     *
77     * @return string
78     */
79    public function title(): string
80    {
81        /* I18N: Name of a module */
82        return I18N::translate('Pending changes');
83    }
84
85    /**
86     * A sentence describing what this module does.
87     *
88     * @return string
89     */
90    public function description(): string
91    {
92        /* I18N: Description of the “Pending changes” module */
93        return I18N::translate('A list of changes that need to be reviewed by a moderator, and email notifications.');
94    }
95
96    /**
97     * Generate the HTML content of this block.
98     *
99     * @param Tree                 $tree
100     * @param int                  $block_id
101     * @param string               $context
102     * @param array<string,string> $config
103     *
104     * @return string
105     */
106    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
107    {
108        $old_language = I18N::languageTag();
109
110        $sendmail = (bool) $this->getBlockSetting($block_id, 'sendmail', '1');
111        $days     = (int) $this->getBlockSetting($block_id, 'days', '1');
112
113        extract($config, EXTR_OVERWRITE);
114
115        $changes_exist = DB::table('change')
116            ->where('status', 'pending')
117            ->exists();
118
119        if ($changes_exist && $sendmail) {
120            $last_email_timestamp = (int) Site::getPreference('LAST_CHANGE_EMAIL');
121            $next_email_timestamp = $last_email_timestamp + 86400 * $days;
122
123            // There are pending changes - tell moderators/managers/administrators about them.
124            if ($next_email_timestamp < time()) {
125                // Which users have pending changes?
126                foreach ($this->user_service->all() as $user) {
127                    if ($user->getPreference(UserInterface::PREF_CONTACT_METHOD) !== MessageService::CONTACT_METHOD_NONE) {
128                        foreach ($this->tree_service->all() as $tmp_tree) {
129                            if ($tmp_tree->hasPendingEdit() && Auth::isManager($tmp_tree, $user)) {
130                                I18N::init($user->getPreference(UserInterface::PREF_LANGUAGE));
131
132                                $this->email_service->send(
133                                    new SiteUser(),
134                                    $user,
135                                    new TreeUser($tmp_tree),
136                                    I18N::translate('Pending changes'),
137                                    view('emails/pending-changes-text', [
138                                        'tree' => $tmp_tree,
139                                        'user' => $user,
140                                    ]),
141                                    view('emails/pending-changes-html', [
142                                        'tree' => $tmp_tree,
143                                        'user' => $user,
144                                    ])
145                                );
146                            }
147                        }
148                    }
149                }
150                I18N::init($old_language);
151                Site::setPreference('LAST_CHANGE_EMAIL', (string) time());
152            }
153        }
154        if (Auth::isEditor($tree) && $tree->hasPendingEdit()) {
155            $content = '';
156            if (Auth::isModerator($tree)) {
157                $content .= '<a href="' . e(route(PendingChanges::class, ['tree' => $tree->name()])) . '">' . I18N::translate('There are pending changes for you to moderate.') . '</a><br>';
158            }
159            if ($sendmail) {
160                $last_email_timestamp = Registry::timestampFactory()->make((int) Site::getPreference('LAST_CHANGE_EMAIL'));
161                $next_email_timestamp = $last_email_timestamp->addDays($days);
162
163                $content .= I18N::translate('Last email reminder was sent ') . view('components/datetime', ['timestamp' => $last_email_timestamp]) . '<br>';
164                $content .= I18N::translate('Next email reminder will be sent after ') . view('components/datetime', ['timestamp' => $next_email_timestamp]) . '<br><br>';
165            }
166            $content .= '<ul>';
167
168            $changes = DB::table('change')
169                ->where('gedcom_id', '=', $tree->id())
170                ->whereIn('change_id', static function (Builder $query) use ($tree): void {
171                    $query->select([new Expression('MAX(change_id)')])
172                        ->from('change')
173                        ->where('gedcom_id', '=', $tree->id())
174                        ->where('status', '=', 'pending')
175                        ->groupBy(['xref']);
176                })
177                ->get();
178
179            foreach ($changes as $change) {
180                $record = Registry::gedcomRecordFactory()->make($change->xref, $tree, $change->new_gedcom ?: $change->old_gedcom);
181                if ($record->canShow()) {
182                    $content .= '<li><a href="' . e($record->url()) . '">' . $record->fullName() . '</a></li>';
183                }
184            }
185            $content .= '</ul>';
186
187            if ($context !== self::CONTEXT_EMBED) {
188                return view('modules/block-template', [
189                    'block'      => Str::kebab($this->name()),
190                    'id'         => $block_id,
191                    'config_url' => $this->configUrl($tree, $context, $block_id),
192                    'title'      => $this->title(),
193                    'content'    => $content,
194                ]);
195            }
196
197            return $content;
198        }
199
200        return '';
201    }
202
203    /**
204     * Should this block load asynchronously using AJAX?
205     *
206     * Simple blocks are faster in-line, more complex ones can be loaded later.
207     *
208     * @return bool
209     */
210    public function loadAjax(): bool
211    {
212        return false;
213    }
214
215    /**
216     * Can this block be shown on the user’s home page?
217     *
218     * @return bool
219     */
220    public function isUserBlock(): bool
221    {
222        return true;
223    }
224
225    /**
226     * Can this block be shown on the tree’s home page?
227     *
228     * @return bool
229     */
230    public function isTreeBlock(): bool
231    {
232        return true;
233    }
234
235    /**
236     * Update the configuration for a block.
237     *
238     * @param ServerRequestInterface $request
239     * @param int     $block_id
240     *
241     * @return void
242     */
243    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
244    {
245        $days     = Validator::parsedBody($request)->integer('days');
246        $sendmail = Validator::parsedBody($request)->string('sendmail');
247
248        $this->setBlockSetting($block_id, 'days', (string) $days);
249        $this->setBlockSetting($block_id, 'sendmail', $sendmail);
250    }
251
252    /**
253     * An HTML form to edit block settings
254     *
255     * @param Tree $tree
256     * @param int  $block_id
257     *
258     * @return string
259     */
260    public function editBlockConfiguration(Tree $tree, int $block_id): string
261    {
262        $sendmail = $this->getBlockSetting($block_id, 'sendmail', '1');
263        $days     = $this->getBlockSetting($block_id, 'days', '1');
264
265        return view('modules/review_changes/config', [
266            'days'     => $days,
267            'sendmail' => $sendmail,
268        ]);
269    }
270}
271