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