xref: /webtrees/app/Module/ReviewChangesModule.php (revision d9efec4aaa9aefd6a527c75c15e437b9a1a6604c)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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\TreeService;
29use Fisharebest\Webtrees\Services\UserService;
30use Fisharebest\Webtrees\Site;
31use Fisharebest\Webtrees\SiteUser;
32use Fisharebest\Webtrees\Tree;
33use Fisharebest\Webtrees\TreeUser;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Database\Query\Builder;
36use Illuminate\Database\Query\Expression;
37use Illuminate\Support\Str;
38use Psr\Http\Message\ServerRequestInterface;
39
40use function time;
41
42/**
43 * Class ReviewChangesModule
44 */
45class ReviewChangesModule extends AbstractModule implements ModuleBlockInterface
46{
47    use ModuleBlockTrait;
48
49    private EmailService $email_service;
50
51    private UserService $user_service;
52
53    private TreeService $tree_service;
54
55    /**
56     * ReviewChangesModule constructor.
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) !== '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                //->select(['xref'])
176                ->get();
177
178            foreach ($changes as $change) {
179                $record = Registry::gedcomRecordFactory()->make($change->xref, $tree, $change->new_gedcom ?: $change->old_gedcom);
180                if ($record->canShow()) {
181                    $content .= '<li><a href="' . e($record->url()) . '">' . $record->fullName() . '</a></li>';
182                }
183            }
184            $content .= '</ul>';
185
186            if ($context !== self::CONTEXT_EMBED) {
187                return view('modules/block-template', [
188                    'block'      => Str::kebab($this->name()),
189                    'id'         => $block_id,
190                    'config_url' => $this->configUrl($tree, $context, $block_id),
191                    'title'      => $this->title(),
192                    'content'    => $content,
193                ]);
194            }
195
196            return $content;
197        }
198
199        return '';
200    }
201
202    /**
203     * Should this block load asynchronously using AJAX?
204     *
205     * Simple blocks are faster in-line, more complex ones can be loaded later.
206     *
207     * @return bool
208     */
209    public function loadAjax(): bool
210    {
211        return false;
212    }
213
214    /**
215     * Can this block be shown on the user’s home page?
216     *
217     * @return bool
218     */
219    public function isUserBlock(): bool
220    {
221        return true;
222    }
223
224    /**
225     * Can this block be shown on the tree’s home page?
226     *
227     * @return bool
228     */
229    public function isTreeBlock(): bool
230    {
231        return true;
232    }
233
234    /**
235     * Update the configuration for a block.
236     *
237     * @param ServerRequestInterface $request
238     * @param int     $block_id
239     *
240     * @return void
241     */
242    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
243    {
244        $params = (array) $request->getParsedBody();
245
246        $this->setBlockSetting($block_id, 'days', $params['days']);
247        $this->setBlockSetting($block_id, 'sendmail', $params['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