xref: /webtrees/app/Module/ResearchTaskModule.php (revision 4118eb0701089496b348217fd91c211bdff035bc)
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\Elements\DateValue;
24use Fisharebest\Webtrees\Elements\ResearchTask;
25use Fisharebest\Webtrees\Elements\WebtreesUser;
26use Fisharebest\Webtrees\Family;
27use Fisharebest\Webtrees\GedcomRecord;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Registry;
31use Fisharebest\Webtrees\Tree;
32use Illuminate\Database\Capsule\Manager as DB;
33use Illuminate\Database\Query\JoinClause;
34use Illuminate\Support\Collection;
35use Illuminate\Support\Str;
36use Psr\Http\Message\ServerRequestInterface;
37
38use const PHP_INT_MAX;
39
40/**
41 * Class ResearchTaskModule
42 */
43class ResearchTaskModule extends AbstractModule implements ModuleBlockInterface
44{
45    use ModuleBlockTrait;
46
47    private const DEFAULT_SHOW_OTHER      = '1';
48    private const DEFAULT_SHOW_UNASSIGNED = '1';
49    private const DEFAULT_SHOW_FUTURE     = '1';
50
51    // 31 DEC 9999
52    private const MAXIMUM_JULIAN_DAY = 5373484;
53
54    // Pagination
55    private const LIMIT_LOW  = 10;
56    private const LIMIT_HIGH = 20;
57
58    /**
59     * Early initialisation.  Called before most of the middleware.
60     */
61    public function boot(): void
62    {
63        Registry::elementFactory()->registerTags([
64            'FAM:_TODO'           => new ResearchTask(I18N::translate('Research task')),
65            'FAM:_TODO:DATE'      => new DateValue(I18N::translate('Date')),
66            'FAM:_TODO:_WT_USER'  => new WebtreesUser(I18N::translate('User')),
67            'INDI:_TODO'          => new ResearchTask(I18N::translate('Research task')),
68            'INDI:_TODO:DATE'     => new DateValue(I18N::translate('Date')),
69            'INDI:_TODO:_WT_USER' => new WebtreesUser(I18N::translate('User')),
70        ]);
71
72        Registry::elementFactory()->make('FAM')->subtag('_TODO', '0:M');
73        Registry::elementFactory()->make('INDI')->subtag('_TODO', '0:M');
74    }
75
76    /**
77     * A sentence describing what this module does.
78     *
79     * @return string
80     */
81    public function description(): string
82    {
83        /* I18N: Description of “Research tasks” module */
84        return I18N::translate('A list of tasks and activities that are linked to the family tree.');
85    }
86
87    /**
88     * Generate the HTML content of this block.
89     *
90     * @param Tree                 $tree
91     * @param int                  $block_id
92     * @param string               $context
93     * @param array<string,string> $config
94     *
95     * @return string
96     */
97    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
98    {
99        $show_other      = $this->getBlockSetting($block_id, 'show_other', self::DEFAULT_SHOW_OTHER);
100        $show_unassigned = $this->getBlockSetting($block_id, 'show_unassigned', self::DEFAULT_SHOW_UNASSIGNED);
101        $show_future     = $this->getBlockSetting($block_id, 'show_future', self::DEFAULT_SHOW_FUTURE);
102
103        extract($config, EXTR_OVERWRITE);
104
105        $end_jd      = $show_future ? self::MAXIMUM_JULIAN_DAY : Registry::timestampFactory()->now()->julianDay();
106        $individuals = $this->individualsWithTasks($tree, $end_jd);
107        $families    = $this->familiesWithTasks($tree, $end_jd);
108
109        $records = $individuals->merge($families);
110
111        $tasks = new Collection();
112
113        foreach ($records as $record) {
114            foreach ($record->facts(['_TODO']) as $task) {
115                $user_name = $task->attribute('_WT_USER');
116
117                if ($user_name === Auth::user()->userName()) {
118                    // Tasks belonging to us.
119                    $tasks->add($task);
120                } elseif ($user_name === '' && $show_unassigned) {
121                    // Tasks belonging to nobody.
122                    $tasks->add($task);
123                } elseif ($user_name !== '' && $show_other) {
124                    // Tasks belonging to others.
125                    $tasks->add($task);
126                }
127            }
128        }
129
130        if ($records->isEmpty()) {
131            $content = '<p>' . I18N::translate('There are no research tasks in this family tree.') . '</p>';
132        } else {
133            $content = view('modules/todo/research-tasks', [
134                'limit_low'  => self::LIMIT_LOW,
135                'limit_high' => self::LIMIT_HIGH,
136                'tasks'      => $tasks,
137            ]);
138        }
139
140        if ($context !== self::CONTEXT_EMBED) {
141            return view('modules/block-template', [
142                'block'      => Str::kebab($this->name()),
143                'id'         => $block_id,
144                'config_url' => $this->configUrl($tree, $context, $block_id),
145                'title'      => $this->title(),
146                'content'    => $content,
147            ]);
148        }
149
150        return $content;
151    }
152
153    /**
154     * @param Tree $tree
155     * @param int  $max_julian_day
156     *
157     * @return Collection<int,Individual>
158     */
159    private function individualsWithTasks(Tree $tree, int $max_julian_day): Collection
160    {
161        return DB::table('individuals')
162            ->join('dates', static function (JoinClause $join): void {
163                $join
164                    ->on('i_file', '=', 'd_file')
165                    ->on('i_id', '=', 'd_gid');
166            })
167            ->where('i_file', '=', $tree->id())
168            ->where('d_fact', '=', '_TODO')
169            ->where('d_julianday1', '<', $max_julian_day)
170            ->select(['individuals.*'])
171            ->distinct()
172            ->get()
173            ->map(Registry::individualFactory()->mapper($tree))
174            ->filter(GedcomRecord::accessFilter());
175    }
176
177    /**
178     * @param Tree $tree
179     * @param int  $max_julian_day
180     *
181     * @return Collection<int,Family>
182     */
183    private function familiesWithTasks(Tree $tree, int $max_julian_day): Collection
184    {
185        return DB::table('families')
186            ->join('dates', static function (JoinClause $join): void {
187                $join
188                    ->on('f_file', '=', 'd_file')
189                    ->on('f_id', '=', 'd_gid');
190            })
191            ->where('f_file', '=', $tree->id())
192            ->where('d_fact', '=', '_TODO')
193            ->where('d_julianday1', '<', $max_julian_day)
194            ->select(['families.*'])
195            ->distinct()
196            ->get()
197            ->map(Registry::familyFactory()->mapper($tree))
198            ->filter(GedcomRecord::accessFilter());
199    }
200
201    /**
202     * How should this module be identified in the control panel, etc.?
203     *
204     * @return string
205     */
206    public function title(): string
207    {
208        /* I18N: Name of a module. Tasks that need further research. */
209        return I18N::translate('Research tasks');
210    }
211
212    /**
213     * Should this block load asynchronously using AJAX?
214     *
215     * Simple blocks are faster in-line, more complex ones can be loaded later.
216     *
217     * @return bool
218     */
219    public function loadAjax(): bool
220    {
221        return false;
222    }
223
224    /**
225     * Can this block be shown on the user’s home page?
226     *
227     * @return bool
228     */
229    public function isUserBlock(): bool
230    {
231        return true;
232    }
233
234    /**
235     * Can this block be shown on the tree’s home page?
236     *
237     * @return bool
238     */
239    public function isTreeBlock(): bool
240    {
241        return true;
242    }
243
244    /**
245     * Update the configuration for a block.
246     *
247     * @param ServerRequestInterface $request
248     * @param int                    $block_id
249     *
250     * @return void
251     */
252    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
253    {
254        $params = (array) $request->getParsedBody();
255
256        $this->setBlockSetting($block_id, 'show_other', $params['show_other']);
257        $this->setBlockSetting($block_id, 'show_unassigned', $params['show_unassigned']);
258        $this->setBlockSetting($block_id, 'show_future', $params['show_future']);
259    }
260
261    /**
262     * An HTML form to edit block settings
263     *
264     * @param Tree $tree
265     * @param int  $block_id
266     *
267     * @return string
268     */
269    public function editBlockConfiguration(Tree $tree, int $block_id): string
270    {
271        $show_other      = $this->getBlockSetting($block_id, 'show_other', self::DEFAULT_SHOW_OTHER);
272        $show_unassigned = $this->getBlockSetting($block_id, 'show_unassigned', self::DEFAULT_SHOW_UNASSIGNED);
273        $show_future     = $this->getBlockSetting($block_id, 'show_future', self::DEFAULT_SHOW_FUTURE);
274
275        return view('modules/todo/config', [
276            'show_future'     => $show_future,
277            'show_other'      => $show_other,
278            'show_unassigned' => $show_unassigned,
279        ]);
280    }
281}
282