xref: /webtrees/app/Module/TopSurnamesModule.php (revision 74512d6ac146245d47cbb558ff0cd343f0619ee7)
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,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                    'families' => false,
173                    'module'   => $module,
174                    'order'    => [[1, 'desc']],
175                    'surnames' => $all_surnames,
176                    'tree'     => $tree,
177                ]);
178                break;
179        }
180
181        if ($context !== self::CONTEXT_EMBED) {
182            $num = count($top_surnames);
183            if ($num === 1) {
184                // I18N: i.e. most popular surname.
185                $title = I18N::translate('Top surname');
186            } else {
187                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
188                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
189            }
190
191            return view('modules/block-template', [
192                'block'      => Str::kebab($this->name()),
193                'id'         => $block_id,
194                'config_url' => $this->configUrl($tree, $context, $block_id),
195                'title'      => $title,
196                'content'    => $content,
197            ]);
198        }
199
200        return $content;
201    }
202
203    /**
204     * Should this block load asynchronously using AJAX?
205     *
206     * Simple blocks are faster in-line, more complex ones can be loaded later.
207     *
208     * @return bool
209     */
210    public function loadAjax(): bool
211    {
212        return false;
213    }
214
215    /**
216     * Can this block be shown on the user’s home page?
217     *
218     * @return bool
219     */
220    public function isUserBlock(): bool
221    {
222        return true;
223    }
224
225    /**
226     * Can this block be shown on the tree’s home page?
227     *
228     * @return bool
229     */
230    public function isTreeBlock(): bool
231    {
232        return true;
233    }
234
235    /**
236     * Update the configuration for a block.
237     *
238     * @param ServerRequestInterface $request
239     * @param int     $block_id
240     *
241     * @return void
242     */
243    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
244    {
245        $params = (array) $request->getParsedBody();
246
247        $this->setBlockSetting($block_id, 'num', $params['num']);
248        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
249    }
250
251    /**
252     * An HTML form to edit block settings
253     *
254     * @param Tree $tree
255     * @param int  $block_id
256     *
257     * @return string
258     */
259    public function editBlockConfiguration(Tree $tree, int $block_id): string
260    {
261        $num        = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
262        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
263
264        $info_styles = [
265            /* I18N: An option in a list-box */
266            'list'     => I18N::translate('bullet list'),
267            /* I18N: An option in a list-box */
268            'array'    => I18N::translate('compact list'),
269            /* I18N: An option in a list-box */
270            'table'    => I18N::translate('table'),
271            /* I18N: An option in a list-box */
272            'tagcloud' => I18N::translate('tag cloud'),
273        ];
274
275        return view('modules/top10_surnames/config', [
276            'num'         => $num,
277            'info_style'  => $info_style,
278            'info_styles' => $info_styles,
279        ]);
280    }
281}
282