xref: /webtrees/app/Module/ReviewChangesModule.php (revision 6c98ae6b812cafb873e62ab73fbb6c86ae009481)
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                //->select(['xref'])
178                ->get();
179
180            foreach ($changes as $change) {
181                $record = Registry::gedcomRecordFactory()->make($change->xref, $tree, $change->new_gedcom ?: $change->old_gedcom);
182                if ($record->canShow()) {
183                    $content .= '<li><a href="' . e($record->url()) . '">' . $record->fullName() . '</a></li>';
184                }
185            }
186            $content .= '</ul>';
187
188            if ($context !== self::CONTEXT_EMBED) {
189                return view('modules/block-template', [
190                    'block'      => Str::kebab($this->name()),
191                    'id'         => $block_id,
192                    'config_url' => $this->configUrl($tree, $context, $block_id),
193                    'title'      => $this->title(),
194                    'content'    => $content,
195                ]);
196            }
197
198            return $content;
199        }
200
201        return '';
202    }
203
204    /**
205     * Should this block load asynchronously using AJAX?
206     *
207     * Simple blocks are faster in-line, more complex ones can be loaded later.
208     *
209     * @return bool
210     */
211    public function loadAjax(): bool
212    {
213        return false;
214    }
215
216    /**
217     * Can this block be shown on the user’s home page?
218     *
219     * @return bool
220     */
221    public function isUserBlock(): bool
222    {
223        return true;
224    }
225
226    /**
227     * Can this block be shown on the tree’s home page?
228     *
229     * @return bool
230     */
231    public function isTreeBlock(): bool
232    {
233        return true;
234    }
235
236    /**
237     * Update the configuration for a block.
238     *
239     * @param ServerRequestInterface $request
240     * @param int     $block_id
241     *
242     * @return void
243     */
244    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
245    {
246        $days     = Validator::parsedBody($request)->integer('days');
247        $sendmail = Validator::parsedBody($request)->string('sendmail');
248
249        $this->setBlockSetting($block_id, 'days', (string) $days);
250        $this->setBlockSetting($block_id, 'sendmail', $sendmail);
251    }
252
253    /**
254     * An HTML form to edit block settings
255     *
256     * @param Tree $tree
257     * @param int  $block_id
258     *
259     * @return string
260     */
261    public function editBlockConfiguration(Tree $tree, int $block_id): string
262    {
263        $sendmail = $this->getBlockSetting($block_id, 'sendmail', '1');
264        $days     = $this->getBlockSetting($block_id, 'days', '1');
265
266        return view('modules/review_changes/config', [
267            'days'     => $days,
268            'sendmail' => $sendmail,
269        ]);
270    }
271}
272