xref: /webtrees/app/Module/ReviewChangesModule.php (revision cf7c85896a54223772c76826381a9151d4a21e10)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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\Webtrees\Auth;
23use Fisharebest\Webtrees\Carbon;
24use Fisharebest\Webtrees\Factory;
25use Fisharebest\Webtrees\Http\RequestHandlers\PendingChanges;
26use Fisharebest\Webtrees\I18N;
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 Fisharebest\Webtrees\User;
35use Illuminate\Database\Capsule\Manager as DB;
36use Illuminate\Support\Str;
37use Psr\Http\Message\ServerRequestInterface;
38
39/**
40 * Class ReviewChangesModule
41 */
42class ReviewChangesModule extends AbstractModule implements ModuleBlockInterface
43{
44    use ModuleBlockTrait;
45
46    /** @var EmailService */
47    private $email_service;
48
49    /** @var UserService */
50    private $user_service;
51
52    /** @var TreeService */
53    private $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 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 = Carbon::createFromTimestamp((int) Site::getPreference('LAST_CHANGE_EMAIL'));
119            $next_email_timestamp = $last_email_timestamp->addDays($days);
120
121            // There are pending changes - tell moderators/managers/administrators about them.
122            if ($next_email_timestamp < Carbon::now()) {
123                // Which users have pending changes?
124                foreach ($this->user_service->all() as $user) {
125                    if ($user->getPreference(User::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(User::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) Carbon::now()->unix());
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 = Carbon::createFromTimestamp((int) Site::getPreference('LAST_CHANGE_EMAIL'));
159                $next_email_timestamp = $last_email_timestamp->copy()->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                ->where('status', '=', 'pending')
169                ->select(['xref'])
170                ->get();
171
172            foreach ($changes as $change) {
173                $record = Factory::gedcomRecord()->make($change->xref, $tree);
174                if ($record->canShow()) {
175                    $content .= '<li><a href="' . e($record->url()) . '">' . $record->fullName() . '</a></li>';
176                }
177            }
178            $content .= '</ul>';
179
180            if ($context !== self::CONTEXT_EMBED) {
181                return view('modules/block-template', [
182                    'block'      => Str::kebab($this->name()),
183                    'id'         => $block_id,
184                    'config_url' => $this->configUrl($tree, $context, $block_id),
185                    'title'      => $this->title(),
186                    'content'    => $content,
187                ]);
188            }
189
190            return $content;
191        }
192
193        return '';
194    }
195
196    /**
197     * Should this block load asynchronously using AJAX?
198     *
199     * Simple blocks are faster in-line, more complex ones can be loaded later.
200     *
201     * @return bool
202     */
203    public function loadAjax(): bool
204    {
205        return false;
206    }
207
208    /**
209     * Can this block be shown on the user’s home page?
210     *
211     * @return bool
212     */
213    public function isUserBlock(): bool
214    {
215        return true;
216    }
217
218    /**
219     * Can this block be shown on the tree’s home page?
220     *
221     * @return bool
222     */
223    public function isTreeBlock(): bool
224    {
225        return true;
226    }
227
228    /**
229     * Update the configuration for a block.
230     *
231     * @param ServerRequestInterface $request
232     * @param int     $block_id
233     *
234     * @return void
235     */
236    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
237    {
238        $params = (array) $request->getParsedBody();
239
240        $this->setBlockSetting($block_id, 'days', $params['days']);
241        $this->setBlockSetting($block_id, 'sendmail', $params['sendmail']);
242    }
243
244    /**
245     * An HTML form to edit block settings
246     *
247     * @param Tree $tree
248     * @param int  $block_id
249     *
250     * @return string
251     */
252    public function editBlockConfiguration(Tree $tree, int $block_id): string
253    {
254        $sendmail = $this->getBlockSetting($block_id, 'sendmail', '1');
255        $days     = $this->getBlockSetting($block_id, 'days', '1');
256
257        return view('modules/review_changes/config', [
258            'days'     => $days,
259            'sendmail' => $sendmail,
260        ]);
261    }
262}
263