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