xref: /webtrees/app/Module/TopSurnamesModule.php (revision a489bbce63e2bf20b248a715bda61beff646f1e7)
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                // 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::class, 'strcasecmp']);
136                $content = FunctionsPrintLists::surnameTagCloud($all_surnames, $module, true, $tree);
137                break;
138            case 'list':
139                uasort($all_surnames, [$this, 'surnameCountSort']);
140                $content = FunctionsPrintLists::surnameList($all_surnames, 1, true, $module, $tree);
141                break;
142            case 'array':
143                uasort($all_surnames, [$this, 'surnameCountSort']);
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        $infoStyle = $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            'infoStyle'   => $infoStyle,
254            'info_styles' => $info_styles,
255        ]);
256    }
257
258    /**
259     * Sort (lists of counts of similar) surname by total count.
260     *
261     * @param string[] $a
262     * @param string[] $b
263     *
264     * @return int
265     */
266    private function surnameCountSort(array $a, array $b): int
267    {
268        return array_sum($b) - array_sum($a);
269    }
270}
271