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