xref: /webtrees/app/Module/HitCountFooterModule.php (revision c82761e34f1c58f6aa906b2ff55fa73a937de867)
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 Aura\Router\Route;
23use Fisharebest\Webtrees\Http\RequestHandlers\FamilyPage;
24use Fisharebest\Webtrees\Http\RequestHandlers\IndividualPage;
25use Fisharebest\Webtrees\Http\RequestHandlers\MediaPage;
26use Fisharebest\Webtrees\Http\RequestHandlers\NotePage;
27use Fisharebest\Webtrees\Http\RequestHandlers\RepositoryPage;
28use Fisharebest\Webtrees\Http\RequestHandlers\SourcePage;
29use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
30use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
31use Fisharebest\Webtrees\I18N;
32use Fisharebest\Webtrees\Session;
33use Fisharebest\Webtrees\Tree;
34use Illuminate\Database\Capsule\Manager as DB;
35use Psr\Http\Message\ResponseInterface;
36use Psr\Http\Message\ServerRequestInterface;
37use Psr\Http\Server\MiddlewareInterface;
38use Psr\Http\Server\RequestHandlerInterface;
39
40use function assert;
41
42/**
43 * Class HitCountFooterModule - show the number of page hits in the footer.
44 */
45class HitCountFooterModule extends AbstractModule implements ModuleFooterInterface, MiddlewareInterface
46{
47    use ModuleFooterTrait;
48
49    // Which routes do we count?
50    // For historical reasons, we record the names of the original webtrees script and parameter.
51    protected const PAGE_NAMES = [
52        FamilyPage::class     => 'family.php',
53        IndividualPage::class => 'individual.php',
54        MediaPage::class      => 'mediaviewer.php',
55        NotePage::class       => 'note.php',
56        RepositoryPage::class => 'repo.php',
57        SourcePage::class     => 'source.php',
58        TreePage::class       => 'index.php',
59        UserPage::class       => 'index.php',
60    ];
61
62    /** @var int Count of visits to the current page */
63    protected $page_hits = 0;
64
65    /**
66     * How should this module be labelled on tabs, footers, etc.?
67     *
68     * @return string
69     */
70    public function title(): string
71    {
72        /* I18N: Name of a module */
73        return I18N::translate('Hit counters');
74    }
75
76    /**
77     * A sentence describing what this module does.
78     *
79     * @return string
80     */
81    public function description(): string
82    {
83        /* I18N: Description of the “Hit counters” module */
84        return I18N::translate('Count the visits to each page');
85    }
86
87    /**
88     * The default position for this footer.  It can be changed in the control panel.
89     *
90     * @return int
91     */
92    public function defaultFooterOrder(): int
93    {
94        return 3;
95    }
96
97    /**
98     * A footer, to be added at the bottom of every page.
99     *
100     * @param ServerRequestInterface $request
101     *
102     * @return string
103     */
104    public function getFooter(ServerRequestInterface $request): string
105    {
106        if ($this->page_hits === 0) {
107            return '';
108        }
109
110        $digits = '<span class="odometer">' . I18N::digits($this->page_hits) . '</span>';
111
112        return view('modules/hit-counter/footer', [
113            'hit_counter' => I18N::plural('This page has been viewed %s time.', 'This page has been viewed %s times.', $this->page_hits, $digits),
114        ]);
115    }
116
117    /**
118     * @param ServerRequestInterface  $request
119     * @param RequestHandlerInterface $handler
120     *
121     * @return ResponseInterface
122     */
123    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
124    {
125        $route = $request->getAttribute('route');
126        assert($route instanceof Route);
127
128        $tree  = $request->getAttribute('tree');
129        $user  = $request->getAttribute('user');
130
131        if ($tree instanceof Tree && $tree->getPreference('SHOW_COUNTER')) {
132            $page_name = self::PAGE_NAMES[$route->name] ?? '';
133
134            switch ($route->name) {
135                case FamilyPage::class:
136                case IndividualPage::class:
137                case MediaPage::class:
138                case NotePage::class:
139                case RepositoryPage::class:
140                case SourcePage::class:
141                    $this->page_hits = $this->countHit($tree, $page_name, $request->getQueryParams()['xref'] ?? '');
142                    break;
143
144                case TreePage::class:
145                    $this->page_hits = $this->countHit($tree, $page_name, 'gedcom:' . $tree->id());
146                    break;
147
148                case UserPage::class:
149                    $this->page_hits = $this->countHit($tree, $page_name, 'user:' . $user->id());
150                    break;
151            }
152        }
153
154        return $handler->handle($request);
155    }
156
157    /**
158     * Increment the page count.
159     *
160     * @param Tree   $tree
161     * @param string $page
162     * @param string $parameter
163     *
164     * @return int
165     */
166    protected function countHit(Tree $tree, string $page, string $parameter): int
167    {
168        // Don't increment the counter while we stay on the same page.
169        if (
170            Session::get('last_page_name') === $page &&
171            Session::get('last_page_parameter') === $parameter &&
172            Session::get('last_gedcom_id') === $tree->id()
173        ) {
174            return (int) Session::get('last_count');
175        }
176
177        $count = (int) DB::table('hit_counter')
178            ->where('gedcom_id', '=', $tree->id())
179            ->where('page_name', '=', $page)
180            ->where('page_parameter', '=', $parameter)
181            ->value('page_count');
182
183        $count++;
184
185        DB::table('hit_counter')->updateOrInsert([
186            'gedcom_id'      => $tree->id(),
187            'page_name'      => $page,
188            'page_parameter' => $parameter,
189        ], [
190            'page_count' => $count,
191        ]);
192
193        Session::put('last_gedcom_id', $tree->id());
194        Session::put('last_page_name', $page);
195        Session::put('last_page_parameter', $parameter);
196        Session::put('last_count', $count);
197
198        return $count;
199    }
200}
201