xref: /webtrees/app/Module/ReviewChangesModule.php (revision ca50fb84724cb523ca8f4be8abd453a667296dcf)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Localization\Locale\LocaleInterface;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Carbon;
25use Fisharebest\Webtrees\GedcomRecord;
26use Fisharebest\Webtrees\Http\RequestHandlers\PendingChanges;
27use Fisharebest\Webtrees\I18N;
28use Fisharebest\Webtrees\Services\MailService;
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\Support\Str;
37use Psr\Http\Message\ServerRequestInterface;
38
39use function assert;
40
41/**
42 * Class ReviewChangesModule
43 */
44class ReviewChangesModule extends AbstractModule implements ModuleBlockInterface
45{
46    use ModuleBlockTrait;
47
48    /** @var MailService */
49    private $mail_service;
50
51    /** @var UserService */
52    private $user_service;
53
54    /** @var TreeService */
55    private $tree_service;
56
57    /**
58     * ReviewChangesModule constructor.
59     *
60     * @param MailService $mail_service
61     * @param TreeService $tree_service
62     * @param UserService $user_service
63     */
64    public function __construct(
65        MailService $mail_service,
66        TreeService $tree_service,
67        UserService $user_service
68    ) {
69        $this->mail_service = $mail_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 string[] $config
103     *
104     * @return string
105     */
106    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
107    {
108        $locale = app(ServerRequestInterface::class)->getAttribute('locale');
109        assert($locale instanceof LocaleInterface);
110
111        $sendmail = (bool) $this->getBlockSetting($block_id, 'sendmail', '1');
112        $days     = (int) $this->getBlockSetting($block_id, 'days', '1');
113
114        extract($config, EXTR_OVERWRITE);
115
116        $changes_exist = DB::table('change')
117            ->where('status', 'pending')
118            ->exists();
119
120        if ($changes_exist && $sendmail) {
121            $last_email_timestamp = Carbon::createFromTimestamp((int) Site::getPreference('LAST_CHANGE_EMAIL'));
122            $next_email_timestamp = $last_email_timestamp->addDays($days);
123
124            // There are pending changes - tell moderators/managers/administrators about them.
125            if ($next_email_timestamp < Carbon::now()) {
126                // Which users have pending changes?
127                foreach ($this->user_service->all() as $user) {
128                    if ($user->getPreference('contactmethod') !== 'none') {
129                        foreach ($this->tree_service->all() as $tmp_tree) {
130                            if ($tmp_tree->hasPendingEdit() && Auth::isManager($tmp_tree, $user)) {
131                                I18N::init($user->getPreference('language'));
132
133                                $this->mail_service->send(
134                                    new SiteUser(),
135                                    $user,
136                                    new TreeUser($tmp_tree),
137                                    I18N::translate('Pending changes'),
138                                    view('emails/pending-changes-text', [
139                                        'tree' => $tmp_tree,
140                                        'user' => $user,
141                                    ]),
142                                    view('emails/pending-changes-html', [
143                                        'tree' => $tmp_tree,
144                                        'user' => $user,
145                                    ])
146                                );
147                                I18N::init($locale->languageTag());
148                            }
149                        }
150                    }
151                }
152                Site::setPreference('LAST_CHANGE_EMAIL', (string) Carbon::now()->unix());
153            }
154        }
155        if (Auth::isEditor($tree) && $tree->hasPendingEdit()) {
156            $content = '';
157            if (Auth::isModerator($tree)) {
158                $content .= '<a href="' . e(route(PendingChanges::class, ['tree' => $tree->name()])) . '">' . I18N::translate('There are pending changes for you to moderate.') . '</a><br>';
159            }
160            if ($sendmail) {
161                $last_email_timestamp = Carbon::createFromTimestamp((int) Site::getPreference('LAST_CHANGE_EMAIL'));
162                $next_email_timestamp = $last_email_timestamp->copy()->addDays($days);
163
164                $content .= I18N::translate('Last email reminder was sent ') . view('components/datetime', ['timestamp' => $last_email_timestamp]) . '<br>';
165                $content .= I18N::translate('Next email reminder will be sent after ') . view('components/datetime', ['timestamp' => $next_email_timestamp]) . '<br><br>';
166            }
167            $content .= '<ul>';
168
169            $changes = DB::table('change')
170                ->where('gedcom_id', '=', $tree->id())
171                ->where('status', '=', 'pending')
172                ->select(['xref'])
173                ->get();
174
175            foreach ($changes as $change) {
176                $record = GedcomRecord::getInstance($change->xref, $tree);
177                if ($record->canShow()) {
178                    $content .= '<li><a href="' . e($record->url()) . '">' . $record->fullName() . '</a></li>';
179                }
180            }
181            $content .= '</ul>';
182
183            if ($context !== self::CONTEXT_EMBED) {
184                return view('modules/block-template', [
185                    'block'      => Str::kebab($this->name()),
186                    'id'         => $block_id,
187                    'config_url' => $this->configUrl($tree, $context, $block_id),
188                    'title'      => $this->title(),
189                    'content'    => $content,
190                ]);
191            }
192
193            return $content;
194        }
195
196        return '';
197    }
198
199    /**
200     * Should this block load asynchronously using AJAX?
201     *
202     * Simple blocks are faster in-line, more complex ones can be loaded later.
203     *
204     * @return bool
205     */
206    public function loadAjax(): bool
207    {
208        return false;
209    }
210
211    /**
212     * Can this block be shown on the user’s home page?
213     *
214     * @return bool
215     */
216    public function isUserBlock(): bool
217    {
218        return true;
219    }
220
221    /**
222     * Can this block be shown on the tree’s home page?
223     *
224     * @return bool
225     */
226    public function isTreeBlock(): bool
227    {
228        return true;
229    }
230
231    /**
232     * Update the configuration for a block.
233     *
234     * @param ServerRequestInterface $request
235     * @param int     $block_id
236     *
237     * @return void
238     */
239    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
240    {
241        $params = $request->getParsedBody();
242
243        $this->setBlockSetting($block_id, 'days', $params['days']);
244        $this->setBlockSetting($block_id, 'sendmail', $params['sendmail']);
245    }
246
247    /**
248     * An HTML form to edit block settings
249     *
250     * @param Tree $tree
251     * @param int  $block_id
252     *
253     * @return string
254     */
255    public function editBlockConfiguration(Tree $tree, int $block_id): string
256    {
257        $sendmail = $this->getBlockSetting($block_id, 'sendmail', '1');
258        $days     = $this->getBlockSetting($block_id, 'days', '1');
259
260        return view('modules/review_changes/config', [
261            'days'     => $days,
262            'sendmail' => $sendmail,
263        ]);
264    }
265}
266