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