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