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