xref: /webtrees/app/Module/TopSurnamesModule.php (revision 4566681e36384ac43cc05e51023d99b22bc71e73)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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> $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(['surname'])
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                $content = view('lists/surnames-table', [
172                    'surnames' => $all_surnames,
173                    'module'   => $module,
174                    'families' => false,
175                    'tree'     => $tree,
176                ]);
177                break;
178        }
179
180        if ($context !== self::CONTEXT_EMBED) {
181            $num = count($top_surnames);
182            if ($num === 1) {
183                // I18N: i.e. most popular surname.
184                $title = I18N::translate('Top surname');
185            } else {
186                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
187                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
188            }
189
190            return view('modules/block-template', [
191                'block'      => Str::kebab($this->name()),
192                'id'         => $block_id,
193                'config_url' => $this->configUrl($tree, $context, $block_id),
194                'title'      => $title,
195                'content'    => $content,
196            ]);
197        }
198
199        return $content;
200    }
201
202    /**
203     * Should this block load asynchronously using AJAX?
204     *
205     * Simple blocks are faster in-line, more complex ones can be loaded later.
206     *
207     * @return bool
208     */
209    public function loadAjax(): bool
210    {
211        return false;
212    }
213
214    /**
215     * Can this block be shown on the user’s home page?
216     *
217     * @return bool
218     */
219    public function isUserBlock(): bool
220    {
221        return true;
222    }
223
224    /**
225     * Can this block be shown on the tree’s home page?
226     *
227     * @return bool
228     */
229    public function isTreeBlock(): bool
230    {
231        return true;
232    }
233
234    /**
235     * Update the configuration for a block.
236     *
237     * @param ServerRequestInterface $request
238     * @param int     $block_id
239     *
240     * @return void
241     */
242    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
243    {
244        $params = (array) $request->getParsedBody();
245
246        $this->setBlockSetting($block_id, 'num', $params['num']);
247        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
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