xref: /webtrees/app/Module/TopSurnamesModule.php (revision 9ba014a766385c38470d363a384f5a2c9642a7b8)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Fisharebest\Webtrees\Auth;
21use Fisharebest\Webtrees\Functions\FunctionsPrintLists;
22use Fisharebest\Webtrees\I18N;
23use Fisharebest\Webtrees\Tree;
24use Fisharebest\Webtrees\Services\ModuleService;
25use Illuminate\Database\Capsule\Manager as DB;
26use Illuminate\Database\Query\Expression;
27use Illuminate\Support\Str;
28use Psr\Http\Message\ServerRequestInterface;
29
30/**
31 * Class TopSurnamesModule
32 */
33class TopSurnamesModule extends AbstractModule implements ModuleBlockInterface
34{
35    use ModuleBlockTrait;
36
37    // Default values for new blocks.
38    private const DEFAULT_NUMBER = '10';
39    private const DEFAULT_STYLE  = 'table';
40
41    /**
42     * How should this module be identified in the control panel, etc.?
43     *
44     * @return string
45     */
46    public function title(): string
47    {
48        /* I18N: Name of a module. Top=Most common */
49        return I18N::translate('Top surnames');
50    }
51
52    /**
53     * A sentence describing what this module does.
54     *
55     * @return string
56     */
57    public function description(): string
58    {
59        /* I18N: Description of the “Top surnames” module */
60        return I18N::translate('A list of the most popular surnames.');
61    }
62
63    /**
64     * Generate the HTML content of this block.
65     *
66     * @param Tree     $tree
67     * @param int      $block_id
68     * @param string   $context
69     * @param string[] $config
70     *
71     * @return string
72     */
73    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
74    {
75        $num       = (int) $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
76        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
77
78        extract($config, EXTR_OVERWRITE);
79
80        // Use the count of base surnames.
81        $top_surnames = DB::table('name')
82            ->where('n_file', '=', $tree->id())
83            ->where('n_type', '<>', '_MARNM')
84            ->whereNotIn('n_surn', ['@N.N.', ''])
85            ->groupBy('n_surn')
86            ->orderByDesc(new Expression('COUNT(n_surn)'))
87            ->take($num)
88            ->pluck('n_surn');
89
90        $all_surnames = [];
91
92        foreach ($top_surnames as $top_surname) {
93            $variants = DB::table('name')
94                ->where('n_file', '=', $tree->id())
95                ->where(new Expression('n_surn /*! COLLATE utf8_bin */'), '=', $top_surname)
96                ->groupBy('surname')
97                ->select([new Expression('n_surname /*! COLLATE utf8_bin */ AS surname'), new Expression('count(*) AS total')])
98                ->pluck('total', 'surname')
99                ->all();
100
101            $all_surnames[$top_surname] = $variants;
102        }
103
104        //find a module providing individual lists
105        $module = app(ModuleService::class)->findByComponent(ModuleListInterface::class, $tree, Auth::user())->first(static function (ModuleInterface $module): bool {
106            return $module instanceof IndividualListModule;
107        });
108
109        switch ($infoStyle) {
110            case 'tagcloud':
111                uksort($all_surnames, [I18N::class, 'strcasecmp']);
112                $content = FunctionsPrintLists::surnameTagCloud($all_surnames, $module, true, $tree);
113                break;
114            case 'list':
115                uasort($all_surnames, [$this, 'surnameCountSort']);
116                $content = FunctionsPrintLists::surnameList($all_surnames, 1, true, $module, $tree);
117                break;
118            case 'array':
119                uasort($all_surnames, [$this, 'surnameCountSort']);
120                $content = FunctionsPrintLists::surnameList($all_surnames, 2, true, $module, $tree);
121                break;
122            case 'table':
123            default:
124                $content = view('lists/surnames-table', [
125                    'surnames' => $all_surnames,
126                    'module'   => $module,
127                    'families' => false,
128                    'tree'     => $tree,
129                ]);
130                break;
131        }
132
133        if ($context !== self::CONTEXT_EMBED) {
134            $num = count($top_surnames);
135            if ($num === 1) {
136                // I18N: i.e. most popular surname.
137                $title = I18N::translate('Top surname');
138            } else {
139                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
140                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
141            }
142
143            return view('modules/block-template', [
144                'block'      => Str::kebab($this->name()),
145                'id'         => $block_id,
146                'config_url' => $this->configUrl($tree, $context, $block_id),
147                'title'      => $title,
148                'content'    => $content,
149            ]);
150        }
151
152        return $content;
153    }
154
155    /**
156     * Should this block load asynchronously using AJAX?
157     *
158     * Simple blocks are faster in-line, more complex ones can be loaded later.
159     *
160     * @return bool
161     */
162    public function loadAjax(): bool
163    {
164        return false;
165    }
166
167    /**
168     * Can this block be shown on the user’s home page?
169     *
170     * @return bool
171     */
172    public function isUserBlock(): bool
173    {
174        return true;
175    }
176
177    /**
178     * Can this block be shown on the tree’s home page?
179     *
180     * @return bool
181     */
182    public function isTreeBlock(): bool
183    {
184        return true;
185    }
186
187    /**
188     * Update the configuration for a block.
189     *
190     * @param ServerRequestInterface $request
191     * @param int     $block_id
192     *
193     * @return void
194     */
195    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
196    {
197        $params = $request->getParsedBody();
198
199        $this->setBlockSetting($block_id, 'num', $params['num']);
200        $this->setBlockSetting($block_id, 'infoStyle', $params['infoStyle']);
201    }
202
203    /**
204     * An HTML form to edit block settings
205     *
206     * @param Tree $tree
207     * @param int  $block_id
208     *
209     * @return string
210     */
211    public function editBlockConfiguration(Tree $tree, int $block_id): string
212    {
213        $num       = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
214        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
215
216        $info_styles = [
217            /* I18N: An option in a list-box */
218            'list'     => I18N::translate('bullet list'),
219            /* I18N: An option in a list-box */
220            'array'    => I18N::translate('compact list'),
221            /* I18N: An option in a list-box */
222            'table'    => I18N::translate('table'),
223            /* I18N: An option in a list-box */
224            'tagcloud' => I18N::translate('tag cloud'),
225        ];
226
227        return view('modules/top10_surnames/config', [
228            'num'         => $num,
229            'infoStyle'   => $infoStyle,
230            'info_styles' => $info_styles,
231        ]);
232    }
233
234    /**
235     * Sort (lists of counts of similar) surname by total count.
236     *
237     * @param string[] $a
238     * @param string[] $b
239     *
240     * @return int
241     */
242    private function surnameCountSort(array $a, array $b): int
243    {
244        return array_sum($b) - array_sum($a);
245    }
246}
247