Passed
Pull Request — master (#18)
by
unknown
17:50
created

MatomoController   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 208
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 129
c 0
b 0
f 0
dl 0
loc 208
rs 10
wmc 19

7 Methods

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