xref: /webtrees/app/Module/TopSurnamesModule.php (revision 09523927627d8824ee0799f8137d6de75b8b7921)
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    /**
76     * A sentence describing what this module does.
77     *
78     * @return string
79     */
80    public function description(): string
81    {
82        /* I18N: Description of the “Top surnames” module */
83        return I18N::translate('A list of the most popular surnames.');
84    }
85
86    /**
87     * Generate the HTML content of this block.
88     *
89     * @param Tree                 $tree
90     * @param int                  $block_id
91     * @param string               $context
92     * @param array<string,string> $config
93     *
94     * @return string
95     */
96    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
97    {
98        $num        = (int) $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
99        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
100
101        extract($config, EXTR_OVERWRITE);
102
103        $query = DB::table('name')
104            ->where('n_file', '=', $tree->id())
105            ->where('n_type', '<>', '_MARNM')
106            ->where('n_surn', '<>', '')
107            ->where('n_surn', '<>', Individual::NOMEN_NESCIO)
108            ->select([
109                $this->binaryColumn('n_surn', 'n_surn'),
110                $this->binaryColumn('n_surname', 'n_surname'),
111                new Expression('COUNT(*) AS total'),
112            ])
113            ->groupBy([
114                $this->binaryColumn('n_surn'),
115                $this->binaryColumn('n_surname'),
116            ]);
117
118        /** @var array<array<int>> $top_surnames */
119        $top_surnames = [];
120
121        foreach ($query->get() as $row) {
122            $row->n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
123            $row->n_surn = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
124
125            $top_surnames[$row->n_surn][$row->n_surname] ??= 0;
126            $top_surnames[$row->n_surn][$row->n_surname] += (int) $row->total;
127        }
128
129        uasort($top_surnames, static fn (array $x, array $y): int => array_sum($y) <=> array_sum($x));
130
131        $top_surnames = array_slice($top_surnames, 0, $num, true);
132
133        // Find a module providing individual lists.
134        $module = $this->module_service
135            ->findByComponent(ModuleListInterface::class, $tree, Auth::user())
136            ->first(static function (ModuleInterface $module): bool {
137                // The family list extends the individual list
138                return
139                    $module instanceof IndividualListModule &&
140                    !$module instanceof FamilyListModule;
141            });
142
143        switch ($info_style) {
144            case 'tagcloud':
145                uksort($top_surnames, I18N::comparator());
146                $content = view('lists/surnames-tag-cloud', [
147                    'module'   => $module,
148                    'params'   => [],
149                    'surnames' => $top_surnames,
150                    'totals'   => true,
151                    'tree'     => $tree,
152                ]);
153                break;
154
155            case 'list':
156                $content = view('lists/surnames-bullet-list', [
157                    'module'   => $module,
158                    'params'   => [],
159                    'surnames' => $top_surnames,
160                    'totals'   => true,
161                    'tree'     => $tree,
162                ]);
163                break;
164
165            case 'array':
166                $content = view('lists/surnames-compact-list', [
167                    'module'   => $module,
168                    'params'   => [],
169                    'surnames' => $top_surnames,
170                    'totals'   => true,
171                    'tree'     => $tree,
172                ]);
173                break;
174
175            case 'table':
176            default:
177                uksort($top_surnames, I18N::comparator());
178                $content = view('lists/surnames-table', [
179                    'families' => false,
180                    'module'   => $module,
181                    'order'    => [[1, 'desc']],
182                    'params'   => [],
183                    'surnames' => $top_surnames,
184                    'tree'     => $tree,
185                ]);
186                break;
187        }
188
189        if ($context !== self::CONTEXT_EMBED) {
190            $num = count($top_surnames);
191            if ($num === 1) {
192                // I18N: i.e. most popular surname.
193                $title = I18N::translate('Top surname');
194            } else {
195                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
196                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
197            }
198
199            return view('modules/block-template', [
200                'block'      => Str::kebab($this->name()),
201                'id'         => $block_id,
202                'config_url' => $this->configUrl($tree, $context, $block_id),
203                'title'      => $title,
204                'content'    => $content,
205            ]);
206        }
207
208        return $content;
209    }
210
211    /**
212     * Should this block load asynchronously using AJAX?
213     *
214     * Simple blocks are faster in-line, more complex ones can be loaded later.
215     *
216     * @return bool
217     */
218    public function loadAjax(): bool
219    {
220        return false;
221    }
222
223    /**
224     * Can this block be shown on the user’s home page?
225     *
226     * @return bool
227     */
228    public function isUserBlock(): bool
229    {
230        return true;
231    }
232
233    /**
234     * Can this block be shown on the tree’s home page?
235     *
236     * @return bool
237     */
238    public function isTreeBlock(): bool
239    {
240        return true;
241    }
242
243    /**
244     * Update the configuration for a block.
245     *
246     * @param ServerRequestInterface $request
247     * @param int     $block_id
248     *
249     * @return void
250     */
251    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
252    {
253        $num        = Validator::parsedBody($request)->integer('num');
254        $info_style = Validator::parsedBody($request)->string('infoStyle');
255
256        $this->setBlockSetting($block_id, 'num', (string) $num);
257        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
258    }
259
260    /**
261     * An HTML form to edit block settings
262     *
263     * @param Tree $tree
264     * @param int  $block_id
265     *
266     * @return string
267     */
268    public function editBlockConfiguration(Tree $tree, int $block_id): string
269    {
270        $num        = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
271        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
272
273        $info_styles = [
274            /* I18N: An option in a list-box */
275            'list'     => I18N::translate('bullet list'),
276            /* I18N: An option in a list-box */
277            'array'    => I18N::translate('compact list'),
278            /* I18N: An option in a list-box */
279            'table'    => I18N::translate('table'),
280            /* I18N: An option in a list-box */
281            'tagcloud' => I18N::translate('tag cloud'),
282        ];
283
284        return view('modules/top10_surnames/config', [
285            'num'         => $num,
286            'info_style'  => $info_style,
287            'info_styles' => $info_styles,
288        ]);
289    }
290
291    /**
292     * This module assumes the database will use binary collation on the name columns.
293     * Until we convert MySQL databases to use utf8_bin, we need to do this at run-time.
294     *
295     * @param string      $column
296     * @param string|null $alias
297     *
298     * @return Expression
299     */
300    private function binaryColumn(string $column, string $alias = null): Expression
301    {
302        if (DB::connection()->getDriverName() === 'mysql') {
303            $sql = 'CAST(' . $column . ' AS binary)';
304        } else {
305            $sql = $column;
306        }
307
308        if ($alias !== null) {
309            $sql .= ' AS ' . $alias;
310        }
311
312        return new Expression($sql);
313    }
314}
315