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