xref: /webtrees/app/Module/TopSurnamesModule.php (revision d3d68c00895c5db24007b987c2ee5f9f44403bef)
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 fn (string $n): int => (int) $n)
118                ->all();
119
120            $all_surnames[$top_surname] = $variants;
121        }
122
123        // Find a module providing individual lists.
124        $module = $this->module_service
125            ->findByComponent(ModuleListInterface::class, $tree, Auth::user())
126            ->first(static function (ModuleInterface $module): bool {
127                // The family list extends the individual list
128                return
129                    $module instanceof IndividualListModule &&
130                    !$module instanceof FamilyListModule;
131            });
132
133        switch ($infoStyle) {
134            case 'tagcloud':
135                uksort($all_surnames, I18N::comparator());
136                $content = FunctionsPrintLists::surnameTagCloud($all_surnames, $module, true, $tree);
137                break;
138            case 'list':
139                uasort($all_surnames, fn (array $a, array $b): int => array_sum($b) <=> array_sum($a));
140                $content = FunctionsPrintLists::surnameList($all_surnames, 1, true, $module, $tree);
141                break;
142            case 'array':
143                uasort($all_surnames, fn (array $a, array $b): int => array_sum($b) <=> array_sum($a));
144                $content = FunctionsPrintLists::surnameList($all_surnames, 2, true, $module, $tree);
145                break;
146            case 'table':
147            default:
148                $content = view('lists/surnames-table', [
149                    'surnames' => $all_surnames,
150                    'module'   => $module,
151                    'families' => false,
152                    'tree'     => $tree,
153                ]);
154                break;
155        }
156
157        if ($context !== self::CONTEXT_EMBED) {
158            $num = count($top_surnames);
159            if ($num === 1) {
160                // I18N: i.e. most popular surname.
161                $title = I18N::translate('Top surname');
162            } else {
163                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
164                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
165            }
166
167            return view('modules/block-template', [
168                'block'      => Str::kebab($this->name()),
169                'id'         => $block_id,
170                'config_url' => $this->configUrl($tree, $context, $block_id),
171                'title'      => $title,
172                'content'    => $content,
173            ]);
174        }
175
176        return $content;
177    }
178
179    /**
180     * Should this block load asynchronously using AJAX?
181     *
182     * Simple blocks are faster in-line, more complex ones can be loaded later.
183     *
184     * @return bool
185     */
186    public function loadAjax(): bool
187    {
188        return false;
189    }
190
191    /**
192     * Can this block be shown on the user’s home page?
193     *
194     * @return bool
195     */
196    public function isUserBlock(): bool
197    {
198        return true;
199    }
200
201    /**
202     * Can this block be shown on the tree’s home page?
203     *
204     * @return bool
205     */
206    public function isTreeBlock(): bool
207    {
208        return true;
209    }
210
211    /**
212     * Update the configuration for a block.
213     *
214     * @param ServerRequestInterface $request
215     * @param int     $block_id
216     *
217     * @return void
218     */
219    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
220    {
221        $params = (array) $request->getParsedBody();
222
223        $this->setBlockSetting($block_id, 'num', $params['num']);
224        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
225    }
226
227    /**
228     * An HTML form to edit block settings
229     *
230     * @param Tree $tree
231     * @param int  $block_id
232     *
233     * @return string
234     */
235    public function editBlockConfiguration(Tree $tree, int $block_id): string
236    {
237        $num        = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
238        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
239
240        $info_styles = [
241            /* I18N: An option in a list-box */
242            'list'     => I18N::translate('bullet list'),
243            /* I18N: An option in a list-box */
244            'array'    => I18N::translate('compact list'),
245            /* I18N: An option in a list-box */
246            'table'    => I18N::translate('table'),
247            /* I18N: An option in a list-box */
248            'tagcloud' => I18N::translate('tag cloud'),
249        ];
250
251        return view('modules/top10_surnames/config', [
252            'num'         => $num,
253            'info_style'  => $info_style,
254            'info_styles' => $info_styles,
255        ]);
256    }
257}
258