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