xref: /webtrees/app/Module/ReviewChangesModule.php (revision 65cf57062fc712114f930335533210fd95170cea)
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\EmailService;
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\User;
36use Illuminate\Database\Capsule\Manager as DB;
37use Illuminate\Support\Str;
38use Psr\Http\Message\ServerRequestInterface;
39
40use function assert;
41
42/**
43 * Class ReviewChangesModule
44 */
45class ReviewChangesModule extends AbstractModule implements ModuleBlockInterface
46{
47    use ModuleBlockTrait;
48
49    /** @var EmailService */
50    private $email_service;
51
52    /** @var UserService */
53    private $user_service;
54
55    /** @var TreeService */
56    private $tree_service;
57
58    /**
59     * ReviewChangesModule constructor.
60     *
61     * @param EmailService $email_service
62     * @param TreeService  $tree_service
63     * @param UserService  $user_service
64     */
65    public function __construct(
66        EmailService $email_service,
67        TreeService $tree_service,
68        UserService $user_service
69    ) {
70        $this->email_service = $email_service;
71        $this->tree_service  = $tree_service;
72        $this->user_service  = $user_service;
73    }
74
75    /**
76     * How should this module be identified in the control panel, etc.?
77     *
78     * @return string
79     */
80    public function title(): string
81    {
82        /* I18N: Name of a module */
83        return I18N::translate('Pending changes');
84    }
85
86    /**
87     * A sentence describing what this module does.
88     *
89     * @return string
90     */
91    public function description(): string
92    {
93        /* I18N: Description of the “Pending changes” module */
94        return I18N::translate('A list of changes that need to be reviewed by a moderator, and email notifications.');
95    }
96
97    /**
98     * Generate the HTML content of this block.
99     *
100     * @param Tree     $tree
101     * @param int      $block_id
102     * @param string   $context
103     * @param string[] $config
104     *
105     * @return string
106     */
107    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
108    {
109        $old_language = I18N::languageTag();
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(User::PREF_CONTACT_METHOD) !== '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(User::PREF_LANGUAGE));
132
133                                $this->email_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                            }
148                        }
149                    }
150                }
151                I18N::init($old_language);
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