xref: /webtrees/app/Module/TopSurnamesModule.php (revision 102b4ac44f212e64db4f1856a1da4ed1949a71ef)
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\Services\ModuleService;
27use Fisharebest\Webtrees\Tree;
28use Fisharebest\Webtrees\Validator;
29use Illuminate\Database\Query\Expression;
30use Illuminate\Support\Str;
31use Psr\Http\Message\ServerRequestInterface;
32
33use function array_slice;
34use function array_sum;
35use function count;
36use function extract;
37use function uasort;
38use function uksort;
39use function view;
40
41use const EXTR_OVERWRITE;
42
43/**
44 * Class TopSurnamesModule
45 */
46class TopSurnamesModule extends AbstractModule implements ModuleBlockInterface
47{
48    use ModuleBlockTrait;
49
50    // Default values for new blocks.
51    private const DEFAULT_NUMBER = '10';
52    private const DEFAULT_STYLE  = 'table';
53
54    private ModuleService $module_service;
55
56    /**
57     * @param ModuleService $module_service
58     */
59    public function __construct(ModuleService $module_service)
60    {
61        $this->module_service = $module_service;
62    }
63
64    /**
65     * How should this module be identified in the control panel, etc.?
66     *
67     * @return string
68     */
69    public function title(): string
70    {
71        /* I18N: Name of a module. Top=Most common */
72        return I18N::translate('Top surnames');
73    }
74
75    public function description(): string
76    {
77        /* I18N: Description of the “Top surnames” module */
78        return I18N::translate('A list of the most popular surnames.');
79    }
80
81    /**
82     * Generate the HTML content of this block.
83     *
84     * @param Tree                 $tree
85     * @param int                  $block_id
86     * @param string               $context
87     * @param array<string,string> $config
88     *
89     * @return string
90     */
91    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
92    {
93        $num        = (int) $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
94        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
95
96        extract($config, EXTR_OVERWRITE);
97
98        $query = DB::table('name')
99            ->where('n_file', '=', $tree->id())
100            ->where('n_type', '<>', '_MARNM')
101            ->where('n_surn', '<>', '')
102            ->where('n_surn', '<>', Individual::NOMEN_NESCIO)
103            ->select([
104                DB::binaryColumn('n_surn', 'n_surn'),
105                DB::binaryColumn('n_surname', 'n_surname'),
106                new Expression('COUNT(*) AS total'),
107            ])
108            ->groupBy([
109                DB::binaryColumn('n_surn'),
110                DB::binaryColumn('n_surname'),
111            ]);
112
113        /** @var array<array<int>> $top_surnames */
114        $top_surnames = [];
115
116        foreach ($query->get() as $row) {
117            $row->n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
118            $row->n_surn = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
119
120            $top_surnames[$row->n_surn][$row->n_surname] ??= 0;
121            $top_surnames[$row->n_surn][$row->n_surname] += (int) $row->total;
122        }
123
124        uasort($top_surnames, static fn (array $x, array $y): int => array_sum($y) <=> array_sum($x));
125
126        $top_surnames = array_slice($top_surnames, 0, $num, true);
127
128        // Find a module providing individual lists.
129        $module = $this->module_service
130            ->findByComponent(ModuleListInterface::class, $tree, Auth::user())
131            ->first(static fn (ModuleInterface $module): bool => $module instanceof IndividualListModule);
132
133        switch ($info_style) {
134            case 'tagcloud':
135                uksort($top_surnames, I18N::comparator());
136                $content = view('lists/surnames-tag-cloud', [
137                    'module'   => $module,
138                    'params'   => [],
139                    'surnames' => $top_surnames,
140                    'totals'   => true,
141                    'tree'     => $tree,
142                ]);
143                break;
144
145            case 'list':
146                $content = view('lists/surnames-bullet-list', [
147                    'module'   => $module,
148                    'params'   => [],
149                    'surnames' => $top_surnames,
150                    'totals'   => true,
151                    'tree'     => $tree,
152                ]);
153                break;
154
155            case 'array':
156                $content = view('lists/surnames-compact-list', [
157                    'module'   => $module,
158                    'params'   => [],
159                    'surnames' => $top_surnames,
160                    'totals'   => true,
161                    'tree'     => $tree,
162                ]);
163                break;
164
165            case 'table':
166            default:
167                uksort($top_surnames, I18N::comparator());
168                $content = view('lists/surnames-table', [
169                    'families' => false,
170                    'module'   => $module,
171                    'order'    => [[1, 'desc']],
172                    'params'   => [],
173                    'surnames' => $top_surnames,
174                    'tree'     => $tree,
175                ]);
176                break;
177        }
178
179        if ($context !== self::CONTEXT_EMBED) {
180            $num = count($top_surnames);
181            if ($num === 1) {
182                // I18N: i.e. most popular surname.
183                $title = I18N::translate('Top surname');
184            } else {
185                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
186                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
187            }
188
189            return view('modules/block-template', [
190                'block'      => Str::kebab($this->name()),
191                'id'         => $block_id,
192                'config_url' => $this->configUrl($tree, $context, $block_id),
193                'title'      => $title,
194                'content'    => $content,
195            ]);
196        }
197
198        return $content;
199    }
200
201    /**
202     * Should this block load asynchronously using AJAX?
203     *
204     * Simple blocks are faster in-line, more complex ones can be loaded later.
205     *
206     * @return bool
207     */
208    public function loadAjax(): bool
209    {
210        return false;
211    }
212
213    /**
214     * Can this block be shown on the user’s home page?
215     *
216     * @return bool
217     */
218    public function isUserBlock(): bool
219    {
220        return true;
221    }
222
223    /**
224     * Can this block be shown on the tree’s home page?
225     *
226     * @return bool
227     */
228    public function isTreeBlock(): bool
229    {
230        return true;
231    }
232
233    /**
234     * Update the configuration for a block.
235     *
236     * @param ServerRequestInterface $request
237     * @param int     $block_id
238     *
239     * @return void
240     */
241    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
242    {
243        $num        = Validator::parsedBody($request)->integer('num');
244        $info_style = Validator::parsedBody($request)->string('infoStyle');
245
246        $this->setBlockSetting($block_id, 'num', (string) $num);
247        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
248    }
249
250    /**
251     * An HTML form to edit block settings
252     *
253     * @param Tree $tree
254     * @param int  $block_id
255     *
256     * @return string
257     */
258    public function editBlockConfiguration(Tree $tree, int $block_id): string
259    {
260        $num        = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
261        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
262
263        $info_styles = [
264            /* I18N: An option in a list-box */
265            'list'     => I18N::translate('bullet list'),
266            /* I18N: An option in a list-box */
267            'array'    => I18N::translate('compact list'),
268            /* I18N: An option in a list-box */
269            'table'    => I18N::translate('table'),
270            /* I18N: An option in a list-box */
271            'tagcloud' => I18N::translate('tag cloud'),
272        ];
273
274        return view('modules/top10_surnames/config', [
275            'num'         => $num,
276            'info_style'  => $info_style,
277            'info_styles' => $info_styles,
278        ]);
279    }
280}
281