xref: /webtrees/app/Module/TopSurnamesModule.php (revision 9b802b22a7b94d1d30e0433dd46fe641f3757505)
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\Database;
22use Fisharebest\Webtrees\Functions\FunctionsPrintLists;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Tree;
25use Symfony\Component\HttpFoundation\Request;
26
27/**
28 * Class TopSurnamesModule
29 */
30class TopSurnamesModule extends AbstractModule implements ModuleBlockInterface
31{
32    // Default values for new blocks.
33    private const DEFAULT_NUMBER = '10';
34    private const DEFAULT_STYLE  = 'table';
35
36    /**
37     * How should this module be labelled on tabs, menus, etc.?
38     *
39     * @return string
40     */
41    public function getTitle(): string
42    {
43        /* I18N: Name of a module. Top=Most common */
44        return I18N::translate('Top surnames');
45    }
46
47    /**
48     * A sentence describing what this module does.
49     *
50     * @return string
51     */
52    public function getDescription(): string
53    {
54        /* I18N: Description of the “Top surnames” module */
55        return I18N::translate('A list of the most popular surnames.');
56    }
57
58    /**
59     * Generate the HTML content of this block.
60     *
61     * @param Tree     $tree
62     * @param int      $block_id
63     * @param string   $ctype
64     * @param string[] $cfg
65     *
66     * @return string
67     */
68    public function getBlock(Tree $tree, int $block_id, string $ctype = '', array $cfg = []): string
69    {
70        $num       = (int) $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
71        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
72
73        extract($cfg, EXTR_OVERWRITE);
74
75        // Use the count of base surnames.
76        $top_surnames = Database::prepare(
77            "SELECT n_surn FROM `##name`" .
78            " WHERE n_file = :tree_id AND n_type != '_MARNM' AND n_surn NOT IN ('@N.N.', '')" .
79            " GROUP BY n_surn" .
80            " ORDER BY COUNT(n_surn) DESC" .
81            " LIMIT :limit"
82        )->execute([
83            'tree_id' => $tree->id(),
84            'limit'   => $num,
85        ])->fetchOneColumn();
86
87        $all_surnames = [];
88        foreach ($top_surnames as $top_surname) {
89            $variants = Database::prepare(
90                "SELECT n_surname COLLATE utf8_bin, COUNT(*) FROM `##name` WHERE n_file = :tree_id AND n_surn COLLATE :collate = :surname GROUP BY 1"
91            )->execute([
92                'collate' => I18N::collation(),
93                'surname' => $top_surname,
94                'tree_id' => $tree->id(),
95            ])->fetchAssoc();
96
97            $variants = array_map(function (string $count): int {
98                return (int) $count;
99            }, $variants);
100
101            $all_surnames[$top_surname] = $variants;
102        }
103
104        switch ($infoStyle) {
105            case 'tagcloud':
106                uksort($all_surnames, [I18N::class, 'strcasecmp']);
107                $content = FunctionsPrintLists::surnameTagCloud($all_surnames, 'individual-list', true, $tree);
108                break;
109            case 'list':
110                uasort($all_surnames, [$this, 'surnameCountSort']);
111                $content = FunctionsPrintLists::surnameList($all_surnames, 1, true, 'individual-list', $tree);
112                break;
113            case 'array':
114                uasort($all_surnames, [$this, 'surnameCountSort']);
115                $content = FunctionsPrintLists::surnameList($all_surnames, 2, true, 'individual-list', $tree);
116                break;
117            case 'table':
118            default:
119                $content = view('lists/surnames-table', [
120                    'surnames' => $all_surnames,
121                    'route'    => 'individual-list',
122                    'tree'     => $tree,
123                ]);
124                break;
125        }
126
127        if ($ctype !== '') {
128            $num = count($top_surnames);
129            if ($num === 1) {
130                // I18N: i.e. most popular surname.
131                $title = I18N::translate('Top surname');
132            } else {
133                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
134                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
135            }
136
137            if ($ctype === 'gedcom' && Auth::isManager($tree)) {
138                $config_url = route('tree-page-block-edit', [
139                    'block_id' => $block_id,
140                    'ged'      => $tree->name(),
141                ]);
142            } elseif ($ctype === 'user' && Auth::check()) {
143                $config_url = route('user-page-block-edit', [
144                    'block_id' => $block_id,
145                    'ged'      => $tree->name(),
146                ]);
147            } else {
148                $config_url = '';
149            }
150
151            return view('modules/block-template', [
152                'block'      => str_replace('_', '-', $this->getName()),
153                'id'         => $block_id,
154                'config_url' => $config_url,
155                'title'      => $title,
156                'content'    => $content,
157            ]);
158        }
159
160        return $content;
161    }
162
163    /** {@inheritdoc} */
164    public function loadAjax(): bool
165    {
166        return false;
167    }
168
169    /** {@inheritdoc} */
170    public function isUserBlock(): bool
171    {
172        return true;
173    }
174
175    /** {@inheritdoc} */
176    public function isGedcomBlock(): bool
177    {
178        return true;
179    }
180
181    /**
182     * Update the configuration for a block.
183     *
184     * @param Request $request
185     * @param int     $block_id
186     *
187     * @return void
188     */
189    public function saveBlockConfiguration(Request $request, int $block_id)
190    {
191        $this->setBlockSetting($block_id, 'num', $request->get('num', self::DEFAULT_NUMBER));
192        $this->setBlockSetting($block_id, 'infoStyle', $request->get('infoStyle', self::DEFAULT_STYLE));
193    }
194
195    /**
196     * An HTML form to edit block settings
197     *
198     * @param Tree $tree
199     * @param int  $block_id
200     *
201     * @return void
202     */
203    public function editBlockConfiguration(Tree $tree, int $block_id)
204    {
205        $num       = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
206        $infoStyle = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
207
208        $info_styles = [
209            /* I18N: An option in a list-box */
210            'list'     => I18N::translate('bullet list'),
211            /* I18N: An option in a list-box */
212            'array'    => I18N::translate('compact list'),
213            /* I18N: An option in a list-box */
214            'table'    => I18N::translate('table'),
215            /* I18N: An option in a list-box */
216            'tagcloud' => I18N::translate('tag cloud'),
217        ];
218
219        echo view('modules/top10_surnames/config', [
220            'num'         => $num,
221            'infoStyle'   => $infoStyle,
222            'info_styles' => $info_styles,
223        ]);
224    }
225
226    /**
227     * Sort (lists of counts of similar) surname by total count.
228     *
229     * @param string[] $a
230     * @param string[] $b
231     *
232     * @return int
233     */
234    private function surnameCountSort(array $a, array $b): int
235    {
236        return array_sum($b) - array_sum($a);
237    }
238}
239