Passed
Push — master ( d13d8d...dbf2b1 )
by Karel
11:09 queued 11s
created

MatomoController::reportingApi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 16
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 23
rs 9.7333
1
<?php
2
3
namespace Chuckbe\Chuckcms\Controllers;
4
5
use Carbon\Carbon;
6
use Chuckbe\Chuckcms\Chuck\Matomo\QueryFactory;
7
use Chuckbe\Chuckcms\Chuck\SiteRepository;
8
use Chuckbe\Chuckcms\Models\Site;
9
use Chuckbe\Chuckcms\Models\User;
10
use ChuckSite;
0 ignored issues
show
Bug introduced by
The type ChuckSite was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
12
use Illuminate\Foundation\Bus\DispatchesJobs;
13
use Illuminate\Foundation\Validation\ValidatesRequests;
14
use Illuminate\Http\Request;
15
use Illuminate\Routing\Controller as BaseController;
16
17
class MatomoController extends BaseController
18
{
19
    use AuthorizesRequests;
20
    use DispatchesJobs;
21
    use ValidatesRequests;
22
23
    private $site;
24
    private $siteRepository;
25
    private $user;
26
    private $siteId;
27
    private $authToken;
28
    private $matomoUrl;
29
30
    /**
31
     * Create a new controller instance.
32
     *
33
     * @return void
34
     */
35
    public function __construct(Site $site, SiteRepository $siteRepository, User $user)
36
    {
37
        $this->site = $site;
38
        $this->siteId = ChuckSite::getSetting('integrations.matomo-site-id');
39
        $this->authToken = ChuckSite::getSetting('integrations.matomo-auth-key');
40
        $this->siteRepository = $siteRepository;
41
        $this->user = $user;
42
        $this->matomoUrl = ChuckSite::getSetting('integrations.matomo-site-url');
43
    }
44
45
    public function reportingApi(Request $request)
46
    {
47
        $query_factory = QueryFactory::create($this->matomoUrl);
48
        $query_factory
49
            ->set('idSite', $this->siteId)
50
            ->set('token_auth', $this->authToken);
51
52
        $date = $this->getDateOrPeriodFromRequest($request);
53
        $period = $this->getDateOrPeriodFromRequest($request, true);
54
55
        $lastVisitsDetails = $query_factory->getQuery('Live.getLastVisitsDetails')
56
            ->setParameter('date', $date)
57
            ->setParameter('period', $period)
58
            ->setParameter('filter_limit', -1)
59
            ->execute()
60
            ->getResponse();
61
62
        $view = view('chuckcms::backend.dashboard.blocks.logs')->render();
63
64
        return response()->json(
65
            [
66
                'lastVisitsDetails' => $lastVisitsDetails,
67
                'htmlData'          => $view,
68
            ]
69
        );
70
    }
71
72
    public function visitorSummary(Request $request)
73
    {
74
        $query_factory = QueryFactory::create($this->matomoUrl);
75
        $query_factory
76
            ->set('idSite', $this->siteId)
77
            ->set('token_auth', $this->authToken);
78
79
        $visitorProfile = $query_factory->getQuery('Live.getVisitorProfile')
80
            ->setParameter('visitorId', $request->all()['visitorid'])
81
            ->execute()
82
            ->getResponse();
83
84
        $view = view('chuckcms::backend.dashboard.blocks.visitor_modal')->render();
85
86
        return response()->json(
87
            [
88
                'visitorProfile' => $visitorProfile,
89
                'visitorModal'   => $view,
90
            ]
91
        );
92
    }
93
94
    public function getLiveCounter()
95
    {
96
        $query_factory = QueryFactory::create($this->matomoUrl);
97
        $query_factory
98
            ->set('idSite', $this->siteId)
99
            ->set('token_auth', $this->authToken);
100
101
        $liveCounter = $query_factory->getQuery('Live.getCounters')
102
            ->setParameter('lastMinutes', 3)
103
            ->execute()
104
            ->getResponse();
105
106
        return response()->json(
107
            [
108
                'liveCounter' => $liveCounter,
109
            ]
110
        );
111
    }
112
113
    public function getVisitsData(Request $request)
114
    {
115
        $date = $this->getDateOrPeriodFromRequest($request);
116
        $period = $this->getDateOrPeriodFromRequest($request, true);
117
118
        $imgDate = '';
119
120
        switch ($period) {
121
            case 'range':
122
                $imgDate = $date;
123
                break;
124
125
            case 'week':
126
            case 'month':
127
                $value = $request->all()['value'];
128
                $range = [
129
                    'start' => $value['y2'].'-'.$value['m2'].'-'.$value['d2'],
130
                    'end'   => $value['y1'].'-'.$value['m1'].'-'.$value['d1'],
131
                ];
132
                $imgDate = $range['start'].','.$range['end'];
133
                break;
134
135
            case 'day':
136
                if ($date == 'today') {
137
                    $imgDate = date('Y-m-d').','.date('Y-m-d', strtotime(date('Y-m-d').' 2 day'));
138
                }
139
                if ($date == 'yesterday') {
140
                    $imgDate = date('Y-m-d').','.date('Y-m-d', strtotime(date('Y-m-d').' 2 day'));
141
                }
142
                break;
143
        }
144
145
        $matomoUrl = $this->matomoUrl;
146
        $query_factory = QueryFactory::create($matomoUrl);
147
148
        $query_factory
149
            ->set('idSite', $this->siteId)
150
            ->set('token_auth', $this->authToken);
151
152
        $data = $query_factory->getQuery('API.get ')
153
            ->setParameter('date', $date)
154
            ->setParameter('period', $period)
155
            ->execute()
156
            ->getResponse();
157
158
        return response()->json(
159
            [
160
                'visitimg'               => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&segment=&showtitle=1&random=6179&columns=nb_visits%2Cnb_uniq_visitors&token_auth='.$this->authToken,
161
                'avgvisitimg'            => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&showtitle=1&random=6179&columns=avg_time_on_site&token_auth='.$this->authToken,
162
                'bouncerateimg'          => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=bounce_rate&token_auth='.$this->authToken,
163
                'actions_per_visit_img'  => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=nb_actions_per_visit&token_auth='.$this->authToken,
164
                'pageviewimg'            => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=nb_pageviews%2Cnb_uniq_pageviews&token_auth='.$this->authToken,
165
                'searchesandkeywordsimg' => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=nb_searches%2Cnb_keywords&token_auth='.$this->authToken,
166
                'downloadsimg'           => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=nb_downloads%2Cnb_uniq_downloads&token_auth='.$this->authToken,
167
                'outlinksimg'            => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=nb_outlinks%2Cnb_uniq_outlinks&token_auth='.$this->authToken,
168
                'maxactionsimg'          => $matomoUrl.'/index.php?forceView=1&viewDataTable=sparkline&module=API&action=get&idSite='.$this->siteId.'&period='.$period.'&date='.$imgDate.'&columns=max_actions&token_auth='.$this->authToken,
169
                'data'                   => $data,
170
            ]
171
        );
172
    }
173
174
    public function getReferrers(Request $request)
175
    {
176
        $query_factory = QueryFactory::create($this->matomoUrl);
177
178
        $query_factory
179
            ->set('idSite', $this->siteId)
180
            ->set('token_auth', $this->authToken);
181
182
        $date = $this->getDateOrPeriodFromRequest($request);
183
        $period = $this->getDateOrPeriodFromRequest($request, true);
184
185
        $referrers = $query_factory->getQuery('Referrers.getAll')
186
            ->setParameter('date', $date)
187
            ->setParameter('period', $period)
188
            ->execute()
189
            ->getResponse();
190
191
        return response()->json(
192
            [
193
                'data' => $referrers,
194
            ]
195
        );
196
    }
197
198
    private function getDateOrPeriodFromRequest(Request $request, $periodCheck = false)
199
    {
200
        $data = $request->all()['value'];
201
        $date = strtolower($data['range']);
202
        $period = 'day';
203
204
        if (!isset($data['y2'], $data['m2'], $data['d2'])) {
205
            return $periodCheck ? $period : $date;
206
        }
207
208
        $range = [
209
            'start' => $data['y2'].'-'.$data['m2'].'-'.$data['d2'],
210
            'end'   => $data['y1'].'-'.$data['m1'].'-'.$data['d1'],
211
        ];
212
213
        $now = Carbon::now();
214
        $start = Carbon::createFromFormat('Y-m-d', $range['start']);
215
        $end = Carbon::createFromFormat('Y-m-d', $range['end']);
216
217
        $difference = $now->diffInDays($end); // difference in days between end date and now
218
        $diffStartToEnd = $start->diffInDays($end); //difference in days between start date and end date
219
220
        if ($diffStartToEnd == 6) {
221
            $period = 'week';
222
            $date = 'last7';
223
        }
224
225
        if ($diffStartToEnd == 29) {
226
            $period = 'month';
227
            $date = 'last30';
228
        }
229
230
        if ($difference > 0) {
231
            $period = 'range';
232
            $date = $range['start'].','.$range['end'];
233
        }
234
235
        return $periodCheck ? $period : $date;
236
    }
237
}