xref: /webtrees/app/Module/ReviewChangesModule.php (revision 2729bcd2f87961fdbf9add0fc8b024473427529f)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 Illuminate\Database\Capsule\Manager as DB;
36use Illuminate\Database\Query\Builder;
37use Illuminate\Database\Query\Expression;
38use Illuminate\Support\Str;
39use Psr\Http\Message\ServerRequestInterface;
40
41use function time;
42
43/**
44 * Class ReviewChangesModule
45 */
46class ReviewChangesModule extends AbstractModule implements ModuleBlockInterface
47{
48    use ModuleBlockTrait;
49
50    private EmailService $email_service;
51
52    private UserService $user_service;
53
54    private TreeService $tree_service;
55
56    /**
57     * ReviewChangesModule constructor.
58     *
59     * @param EmailService $email_service
60     * @param TreeService  $tree_service
61     * @param UserService  $user_service
62     */
63    public function __construct(
64        EmailService $email_service,
65        TreeService $tree_service,
66        UserService $user_service
67    ) {
68        $this->email_service = $email_service;
69        $this->tree_service  = $tree_service;
70        $this->user_service  = $user_service;
71    }
72
73    /**
74     * How should this module be identified in the control panel, etc.?
75     *
76     * @return string
77     */
78    public function title(): string
79    {
80        /* I18N: Name of a module */
81        return I18N::translate('Pending changes');
82    }
83
84    /**
85     * A sentence describing what this module does.
86     *
87     * @return string
88     */
89    public function description(): string
90    {
91        /* I18N: Description of the “Pending changes” module */
92        return I18N::translate('A list of changes that need to be reviewed by a moderator, and email notifications.');
93    }
94
95    /**
96     * Generate the HTML content of this block.
97     *
98     * @param Tree                 $tree
99     * @param int                  $block_id
100     * @param string               $context
101     * @param array<string,string> $config
102     *
103     * @return string
104     */
105    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
106    {
107        $old_language = I18N::languageTag();
108
109        $sendmail = (bool) $this->getBlockSetting($block_id, 'sendmail', '1');
110        $days     = (int) $this->getBlockSetting($block_id, 'days', '1');
111
112        extract($config, EXTR_OVERWRITE);
113
114        $changes_exist = DB::table('change')
115            ->where('status', 'pending')
116            ->exists();
117
118        if ($changes_exist && $sendmail) {
119            $last_email_timestamp = (int) Site::getPreference('LAST_CHANGE_EMAIL');
120            $next_email_timestamp = $last_email_timestamp + 86400 * $days;
121
122            // There are pending changes - tell moderators/managers/administrators about them.
123            if ($next_email_timestamp < time()) {
124                // Which users have pending changes?
125                foreach ($this->user_service->all() as $user) {
126                    if ($user->getPreference(UserInterface::PREF_CONTACT_METHOD) !== MessageService::CONTACT_METHOD_NONE) {
127                        foreach ($this->tree_service->all() as $tmp_tree) {
128                            if ($tmp_tree->hasPendingEdit() && Auth::isManager($tmp_tree, $user)) {
129                                I18N::init($user->getPreference(UserInterface::PREF_LANGUAGE));
130
131                                $this->email_service->send(
132                                    new SiteUser(),
133                                    $user,
134                                    new TreeUser($tmp_tree),
135                                    I18N::translate('Pending changes'),
136                                    view('emails/pending-changes-text', [
137                                        'tree' => $tmp_tree,
138                                        'user' => $user,
139                                    ]),
140                                    view('emails/pending-changes-html', [
141                                        'tree' => $tmp_tree,
142                                        'user' => $user,
143                                    ])
144                                );
145                            }
146                        }
147                    }
148                }
149                I18N::init($old_language);
150                Site::setPreference('LAST_CHANGE_EMAIL', (string) time());
151            }
152        }
153        if (Auth::isEditor($tree) && $tree->hasPendingEdit()) {
154            $content = '';
155            if (Auth::isModerator($tree)) {
156                $content .= '<a href="' . e(route(PendingChanges::class, ['tree' => $tree->name()])) . '">' . I18N::translate('There are pending changes for you to moderate.') . '</a><br>';
157            }
158            if ($sendmail) {
159                $last_email_timestamp = Registry::timestampFactory()->make((int) Site::getPreference('LAST_CHANGE_EMAIL'));
160                $next_email_timestamp = $last_email_timestamp->addDays($days);
161
162                $content .= I18N::translate('Last email reminder was sent ') . view('components/datetime', ['timestamp' => $last_email_timestamp]) . '<br>';
163                $content .= I18N::translate('Next email reminder will be sent after ') . view('components/datetime', ['timestamp' => $next_email_timestamp]) . '<br><br>';
164            }
165            $content .= '<ul>';
166
167            $changes = DB::table('change')
168                ->where('gedcom_id', '=', $tree->id())
169                ->whereIn('change_id', static function (Builder $query) use ($tree): void {
170                    $query->select(new Expression('MAX(change_id)'))
171                        ->from('change')
172                        ->where('gedcom_id', '=', $tree->id())
173                        ->where('status', '=', 'pending')
174                        ->groupBy(['xref']);
175                })
176                //->select(['xref'])
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        $params = (array) $request->getParsedBody();
246
247        $this->setBlockSetting($block_id, 'days', $params['days']);
248        $this->setBlockSetting($block_id, 'sendmail', $params['sendmail']);
249    }
250
251    /**
252     * An HTML form to edit block settings
253     *
254     * @param Tree $tree
255     * @param int  $block_id
256     *
257     * @return string
258     */
259    public function editBlockConfiguration(Tree $tree, int $block_id): string
260    {
261        $sendmail = $this->getBlockSetting($block_id, 'sendmail', '1');
262        $days     = $this->getBlockSetting($block_id, 'days', '1');
263
264        return view('modules/review_changes/config', [
265            'days'     => $days,
266            'sendmail' => $sendmail,
267        ]);
268    }
269}
270