xref: /webtrees/app/Module/FamilyTreeStatisticsModule.php (revision 3cd40af69d340ac971a1172bf21e4696be693063)
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\I18N;
25use Fisharebest\Webtrees\Individual;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Services\ModuleService;
28use Fisharebest\Webtrees\Statistics;
29use Fisharebest\Webtrees\Tree;
30use Fisharebest\Webtrees\Validator;
31use Illuminate\Database\Query\Expression;
32use Illuminate\Support\Str;
33use Psr\Http\Message\ServerRequestInterface;
34
35use function array_slice;
36use function extract;
37use function view;
38
39use const EXTR_OVERWRITE;
40
41/**
42 * Class FamilyTreeStatisticsModule
43 */
44class FamilyTreeStatisticsModule extends AbstractModule implements ModuleBlockInterface
45{
46    use ModuleBlockTrait;
47
48    /** Show this number of surnames by default */
49    private const DEFAULT_NUMBER_OF_SURNAMES = '10';
50
51    private ModuleService $module_service;
52
53    /**
54     * @param ModuleService $module_service
55     */
56    public function __construct(ModuleService $module_service)
57    {
58        $this->module_service = $module_service;
59    }
60
61    /**
62     * How should this module be identified in the control panel, etc.?
63     *
64     * @return string
65     */
66    public function title(): string
67    {
68        /* I18N: Name of a module */
69        return I18N::translate('Statistics');
70    }
71
72    public function description(): string
73    {
74        /* I18N: Description of “Statistics” module */
75        return I18N::translate('The size of the family tree, earliest and latest events, common names, etc.');
76    }
77
78    /**
79     * Generate the HTML content of this block.
80     *
81     * @param Tree                 $tree
82     * @param int                  $block_id
83     * @param string               $context
84     * @param array<string,string> $config
85     *
86     * @return string
87     */
88    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
89    {
90        $statistics = Registry::container()->get(Statistics::class);
91
92        $show_last_update     = $this->getBlockSetting($block_id, 'show_last_update', '1');
93        $show_common_surnames = $this->getBlockSetting($block_id, 'show_common_surnames', '1');
94        $number_of_surnames   = (int) $this->getBlockSetting($block_id, 'number_of_surnames', self::DEFAULT_NUMBER_OF_SURNAMES);
95        $stat_indi            = $this->getBlockSetting($block_id, 'stat_indi', '1');
96        $stat_fam             = $this->getBlockSetting($block_id, 'stat_fam', '1');
97        $stat_sour            = $this->getBlockSetting($block_id, 'stat_sour', '1');
98        $stat_media           = $this->getBlockSetting($block_id, 'stat_media', '1');
99        $stat_repo            = $this->getBlockSetting($block_id, 'stat_repo', '1');
100        $stat_surname         = $this->getBlockSetting($block_id, 'stat_surname', '1');
101        $stat_events          = $this->getBlockSetting($block_id, 'stat_events', '1');
102        $stat_users           = $this->getBlockSetting($block_id, 'stat_users', '1');
103        $stat_first_birth     = $this->getBlockSetting($block_id, 'stat_first_birth', '1');
104        $stat_last_birth      = $this->getBlockSetting($block_id, 'stat_last_birth', '1');
105        $stat_first_death     = $this->getBlockSetting($block_id, 'stat_first_death', '1');
106        $stat_last_death      = $this->getBlockSetting($block_id, 'stat_last_death', '1');
107        $stat_long_life       = $this->getBlockSetting($block_id, 'stat_long_life', '1');
108        $stat_avg_life        = $this->getBlockSetting($block_id, 'stat_avg_life', '1');
109        $stat_most_chil       = $this->getBlockSetting($block_id, 'stat_most_chil', '1');
110        $stat_avg_chil        = $this->getBlockSetting($block_id, 'stat_avg_chil', '1');
111
112        extract($config, EXTR_OVERWRITE);
113
114        if ($show_common_surnames === '1') {
115            $query = DB::table('name')
116                ->where('n_file', '=', $tree->id())
117                ->where('n_type', '<>', '_MARNM')
118                ->where('n_surn', '<>', '')
119                ->where('n_surn', '<>', Individual::NOMEN_NESCIO)
120                ->select([
121                    DB::binaryColumn('n_surn', 'n_surn'),
122                    DB::binaryColumn('n_surname', 'n_surname'),
123                    new Expression('COUNT(*) AS total'),
124                ])
125                ->groupBy([
126                    DB::binaryColumn('n_surn'),
127                    DB::binaryColumn('n_surname'),
128                ]);
129
130            /** @var array<array<int>> $top_surnames */
131            $top_surnames = [];
132
133            foreach ($query->get() as $row) {
134                $row->n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
135                $row->n_surn = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
136
137                $top_surnames[$row->n_surn][$row->n_surname] ??= 0;
138                $top_surnames[$row->n_surn][$row->n_surname] += (int) $row->total;
139            }
140
141            uasort($top_surnames, static fn (array $x, array $y): int => array_sum($y) <=> array_sum($x));
142
143            $top_surnames = array_slice($top_surnames, 0, $number_of_surnames, true);
144
145            // Find a module providing individual lists
146            $module = $this->module_service
147                ->findByComponent(ModuleListInterface::class, $tree, Auth::user())
148                ->first(static fn (ModuleInterface $module): bool => $module instanceof IndividualListModule);
149
150            $surnames = view('lists/surnames-compact-list', [
151                'module'   => $module,
152                'totals'   => false,
153                'surnames' => $top_surnames,
154                'tree'     => $tree,
155            ]);
156        } else {
157            $surnames = '';
158        }
159
160        $content = view('modules/gedcom_stats/statistics', [
161            'show_last_update'     => $show_last_update,
162            'show_common_surnames' => $show_common_surnames,
163            'number_of_surnames'   => $number_of_surnames,
164            'stat_indi'            => $stat_indi,
165            'stat_fam'             => $stat_fam,
166            'stat_sour'            => $stat_sour,
167            'stat_media'           => $stat_media,
168            'stat_repo'            => $stat_repo,
169            'stat_surname'         => $stat_surname,
170            'stat_events'          => $stat_events,
171            'stat_users'           => $stat_users,
172            'stat_first_birth'     => $stat_first_birth,
173            'stat_last_birth'      => $stat_last_birth,
174            'stat_first_death'     => $stat_first_death,
175            'stat_last_death'      => $stat_last_death,
176            'stat_long_life'       => $stat_long_life,
177            'stat_avg_life'        => $stat_avg_life,
178            'stat_most_chil'       => $stat_most_chil,
179            'stat_avg_chil'        => $stat_avg_chil,
180            'surnames'             => $surnames,
181        ]);
182
183        $content = $statistics->embedTags($content);
184
185        if ($context !== self::CONTEXT_EMBED) {
186            return view('modules/block-template', [
187                'block'      => Str::kebab($this->name()),
188                'id'         => $block_id,
189                'config_url' => $this->configUrl($tree, $context, $block_id),
190                'title'      => $this->title(),
191                'content'    => $content,
192            ]);
193        }
194
195        return $content;
196    }
197
198    /**
199     * Should this block load asynchronously using AJAX?
200     *
201     * Simple blocks are faster in-line, more complex ones can be loaded later.
202     *
203     * @return bool
204     */
205    public function loadAjax(): bool
206    {
207        return true;
208    }
209
210    /**
211     * Can this block be shown on the user’s home page?
212     *
213     * @return bool
214     */
215    public function isUserBlock(): bool
216    {
217        return true;
218    }
219
220    /**
221     * Can this block be shown on the tree’s home page?
222     *
223     * @return bool
224     */
225    public function isTreeBlock(): bool
226    {
227        return true;
228    }
229
230    /**
231     * Update the configuration for a block.
232     *
233     * @param ServerRequestInterface $request
234     * @param int     $block_id
235     *
236     * @return void
237     */
238    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
239    {
240        $show_last_update     = Validator::parsedBody($request)->boolean('show_last_update', false);
241        $show_common_surnames = Validator::parsedBody($request)->boolean('show_common_surnames', false);
242        $number_of_surnames   = Validator::parsedBody($request)->integer('number_of_surnames');
243        $stat_indi            = Validator::parsedBody($request)->boolean('stat_indi', false);
244        $stat_fam             = Validator::parsedBody($request)->boolean('stat_fam', false);
245        $stat_sour            = Validator::parsedBody($request)->boolean('stat_sour', false);
246        $stat_other           = Validator::parsedBody($request)->boolean('stat_other', false);
247        $stat_media           = Validator::parsedBody($request)->boolean('stat_media', false);
248        $stat_repo            = Validator::parsedBody($request)->boolean('stat_repo', false);
249        $stat_surname         = Validator::parsedBody($request)->boolean('stat_surname', false);
250        $stat_events          = Validator::parsedBody($request)->boolean('stat_events', false);
251        $stat_users           = Validator::parsedBody($request)->boolean('stat_users', false);
252        $stat_first_birth     = Validator::parsedBody($request)->boolean('stat_first_birth', false);
253        $stat_last_birth      = Validator::parsedBody($request)->boolean('stat_last_birth', false);
254        $stat_first_death     = Validator::parsedBody($request)->boolean('stat_first_death', false);
255        $stat_last_death      = Validator::parsedBody($request)->boolean('stat_last_death', false);
256        $stat_long_life       = Validator::parsedBody($request)->boolean('stat_long_life', false);
257        $stat_avg_life        = Validator::parsedBody($request)->boolean('stat_avg_life', false);
258        $stat_most_chil       = Validator::parsedBody($request)->boolean('stat_most_chil', false);
259        $stat_avg_chil        = Validator::parsedBody($request)->boolean('stat_avg_chil', false);
260
261        $this->setBlockSetting($block_id, 'show_last_update', (string) $show_last_update);
262        $this->setBlockSetting($block_id, 'show_common_surnames', (string) $show_common_surnames);
263        $this->setBlockSetting($block_id, 'number_of_surnames', (string) $number_of_surnames);
264        $this->setBlockSetting($block_id, 'stat_indi', (string) $stat_indi);
265        $this->setBlockSetting($block_id, 'stat_fam', (string) $stat_fam);
266        $this->setBlockSetting($block_id, 'stat_sour', (string) $stat_sour);
267        $this->setBlockSetting($block_id, 'stat_other', (string) $stat_other);
268        $this->setBlockSetting($block_id, 'stat_media', (string) $stat_media);
269        $this->setBlockSetting($block_id, 'stat_repo', (string) $stat_repo);
270        $this->setBlockSetting($block_id, 'stat_surname', (string) $stat_surname);
271        $this->setBlockSetting($block_id, 'stat_events', (string) $stat_events);
272        $this->setBlockSetting($block_id, 'stat_users', (string) $stat_users);
273        $this->setBlockSetting($block_id, 'stat_first_birth', (string) $stat_first_birth);
274        $this->setBlockSetting($block_id, 'stat_last_birth', (string) $stat_last_birth);
275        $this->setBlockSetting($block_id, 'stat_first_death', (string) $stat_first_death);
276        $this->setBlockSetting($block_id, 'stat_last_death', (string) $stat_last_death);
277        $this->setBlockSetting($block_id, 'stat_long_life', (string) $stat_long_life);
278        $this->setBlockSetting($block_id, 'stat_avg_life', (string) $stat_avg_life);
279        $this->setBlockSetting($block_id, 'stat_most_chil', (string) $stat_most_chil);
280        $this->setBlockSetting($block_id, 'stat_avg_chil', (string) $stat_avg_chil);
281    }
282
283    /**
284     * An HTML form to edit block settings
285     *
286     * @param Tree $tree
287     * @param int  $block_id
288     *
289     * @return string
290     */
291    public function editBlockConfiguration(Tree $tree, int $block_id): string
292    {
293        $show_last_update     = $this->getBlockSetting($block_id, 'show_last_update', '1');
294        $show_common_surnames = $this->getBlockSetting($block_id, 'show_common_surnames', '1');
295        $number_of_surnames   = $this->getBlockSetting($block_id, 'number_of_surnames', self::DEFAULT_NUMBER_OF_SURNAMES);
296        $stat_indi            = $this->getBlockSetting($block_id, 'stat_indi', '1');
297        $stat_fam             = $this->getBlockSetting($block_id, 'stat_fam', '1');
298        $stat_sour            = $this->getBlockSetting($block_id, 'stat_sour', '1');
299        $stat_media           = $this->getBlockSetting($block_id, 'stat_media', '1');
300        $stat_repo            = $this->getBlockSetting($block_id, 'stat_repo', '1');
301        $stat_surname         = $this->getBlockSetting($block_id, 'stat_surname', '1');
302        $stat_events          = $this->getBlockSetting($block_id, 'stat_events', '1');
303        $stat_users           = $this->getBlockSetting($block_id, 'stat_users', '1');
304        $stat_first_birth     = $this->getBlockSetting($block_id, 'stat_first_birth', '1');
305        $stat_last_birth      = $this->getBlockSetting($block_id, 'stat_last_birth', '1');
306        $stat_first_death     = $this->getBlockSetting($block_id, 'stat_first_death', '1');
307        $stat_last_death      = $this->getBlockSetting($block_id, 'stat_last_death', '1');
308        $stat_long_life       = $this->getBlockSetting($block_id, 'stat_long_life', '1');
309        $stat_avg_life        = $this->getBlockSetting($block_id, 'stat_avg_life', '1');
310        $stat_most_chil       = $this->getBlockSetting($block_id, 'stat_most_chil', '1');
311        $stat_avg_chil        = $this->getBlockSetting($block_id, 'stat_avg_chil', '1');
312
313        return view('modules/gedcom_stats/config', [
314            'show_last_update'     => $show_last_update,
315            'show_common_surnames' => $show_common_surnames,
316            'number_of_surnames'   => $number_of_surnames,
317            'stat_indi'            => $stat_indi,
318            'stat_fam'             => $stat_fam,
319            'stat_sour'            => $stat_sour,
320            'stat_media'           => $stat_media,
321            'stat_repo'            => $stat_repo,
322            'stat_surname'         => $stat_surname,
323            'stat_events'          => $stat_events,
324            'stat_users'           => $stat_users,
325            'stat_first_birth'     => $stat_first_birth,
326            'stat_last_birth'      => $stat_last_birth,
327            'stat_first_death'     => $stat_first_death,
328            'stat_last_death'      => $stat_last_death,
329            'stat_long_life'       => $stat_long_life,
330            'stat_avg_life'        => $stat_avg_life,
331            'stat_most_chil'       => $stat_most_chil,
332            'stat_avg_chil'        => $stat_avg_chil,
333        ]);
334    }
335}
336