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