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