-
Notifications
You must be signed in to change notification settings - Fork 14
/
Controller.php
540 lines (534 loc) · 28.4 KB
/
Controller.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\GoogleAnalyticsImporter;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\DataTable\Renderer\Json;
use Piwik\Date;
use Piwik\Nonce;
use Piwik\Notification;
use Piwik\Piwik;
use Piwik\Plugins\ConnectAccounts\Strategy\Google\GoogleConnect;
use Piwik\Plugins\GoogleAnalyticsImporter\Commands\ImportGA4Reports;
use Piwik\Plugins\GoogleAnalyticsImporter\Google\Authorization;
use Piwik\Plugins\GoogleAnalyticsImporter\Google\AuthorizationGA4;
use Piwik\Plugins\GoogleAnalyticsImporter\Input\EndDate;
use Piwik\Plugins\MobileAppMeasurable\Type;
use Piwik\Plugins\SitesManager\SiteContentDetection\GoogleAnalytics3;
use Piwik\Plugins\SitesManager\SiteContentDetection\GoogleAnalytics4;
use Piwik\Site;
use Piwik\SettingsPiwik;
use Piwik\Url;
use Piwik\Log\LoggerInterface;
use Piwik\Plugins\SitesManager\SitesManager;
class Controller extends \Piwik\Plugin\ControllerAdmin
{
public const OAUTH_STATE_NONCE_NAME = 'GoogleAnalyticsImporter.oauthStateNonce';
public function index($errorMessage = \false)
{
Piwik::checkUserHasSuperUserAccess();
$errorMessage = $errorMessage ?: Common::getRequestVar('error', '');
if (!empty($errorMessage)) {
if ($errorMessage === 'access_denied') {
$errorMessage = Piwik::translate('GoogleAnalyticsImporter_OauthFailedMessage');
} elseif ($errorMessage === 'jwt_validation_error') {
$errorMessage = Piwik::translate('General_ExceptionSecurityCheckFailed');
}
$notification = new Notification($errorMessage);
$notification->context = Notification::CONTEXT_ERROR;
$notification->type = Notification::TYPE_TRANSIENT;
Notification\Manager::notify('configureerror', $notification);
}
/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);
$authUrl = null;
$nonce = null;
$hasClientConfiguration = $authorization->hasClientConfiguration();
if ($hasClientConfiguration) {
try {
$googleClient = $authorization->getConfiguredClient();
} catch (\Exception $ex) {
$authorization->deleteClientConfiguration();
throw $ex;
}
$authUrl = $googleClient->createAuthUrl();
$nonce = Nonce::getNonce('GoogleAnalyticsImporter.deleteGoogleClientConfig', 1200);
} else {
$nonce = Nonce::getNonce('GoogleAnalyticsImporter.googleClientConfig', 1200);
}
$importStatus = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::class);
$statuses = $importStatus->getAllImportStatuses($checkKilledStatus = \true);
foreach ($statuses as &$status) {
if (isset($status['site']) && $status['site'] instanceof Site) {
$status['site'] = ['idsite' => $status['site']->getId(), 'name' => $status['site']->getName()];
}
}
$stopImportNonce = Nonce::getNonce('GoogleAnalyticsImporter.stopImportNonce', 1200);
$startImportNonce = Nonce::getNonce('GoogleAnalyticsImporter.startImportNonce', 1200);
$changeImportEndDateNonce = Nonce::getNonce('GoogleAnalyticsImporter.changeImportEndDateNonce', 1200);
$resumeImportNonce = Nonce::getNonce('GoogleAnalyticsImporter.resumeImportNonce', 1200);
$scheduleReImportNonce = Nonce::getNonce('GoogleAnalyticsImporter.scheduleReImport', 1200);
$maxEndDateDesc = null;
$endDate = StaticContainer::get(EndDate::class);
$maxEndDate = $endDate->getConfiguredMaxEndDate();
if ($maxEndDate == 'today' || $maxEndDate == 'now') {
$maxEndDateDesc = Piwik::translate('GoogleAnalyticsImporter_TodaysDate');
} else {
if ($maxEndDate == 'yesterday' || $maxEndDate == 'yesterdaySameTime') {
$maxEndDateDesc = Piwik::translate('GoogleAnalyticsImporter_YesterdaysDate');
} else {
if (!empty($maxEndDate)) {
$maxEndDateDesc = Date::factory($maxEndDate)->toString();
}
}
}
$isConnectAccountsActivated = \Piwik\Plugins\GoogleAnalyticsImporter\GoogleAnalyticsImporter::isConnectAccountsPluginActivated();
if ($isConnectAccountsActivated) {
$notification = new Notification(Piwik::translate('GoogleAnalyticsImporter_GoogleOauthCompleteWarning', ['<strong>', '</strong>']));
$notification->context = Notification::CONTEXT_WARNING;
$notification->raw = \true;
$notification->flags = Notification::FLAG_CLEAR;
Notification\Manager::notify('GoogleAnalyticsImporter_OauthCompletionWarning', $notification);
}
$configureConnectionProps = \Piwik\Plugins\GoogleAnalyticsImporter\GoogleAnalyticsImporter::getConfigureConnectProps($nonce);
$isClientConfigurable = StaticContainer::get('GoogleAnalyticsImporter.isClientConfigurable');
return $this->renderTemplate(
'index',
[
'isClientConfigurable' => $isClientConfigurable,
'isConfigured' => $authorization->hasAccessToken(),
'auth_nonce' => Nonce::getNonce('gaimport.auth', 1200),
'hasClientConfiguration' => $hasClientConfiguration,
'nonce' => $nonce,
'statuses' => $statuses,
'stopImportNonce' => $stopImportNonce,
'startImportNonce' => $startImportNonce,
'changeImportEndDateNonce' => $changeImportEndDateNonce,
'resumeImportNonce' => $resumeImportNonce,
'scheduleReImportNonce' => $scheduleReImportNonce,
'maxEndDateDesc' => $maxEndDateDesc,
'importOptionsUA' => array(
'ua' => Piwik::translate('GoogleAnalyticsImporter_SelectImporterUATitle')),
'importOptionsGA4' => [
'ga4' => Piwik::translate('GoogleAnalyticsImporter_SelectImporterGA4Title')],
'extraCustomDimensionsField' => [
'field1' => [
'key' => 'gaDimension',
'title' => Piwik::translate('GoogleAnalyticsImporter_GADimension'),
'uiControl' => 'text',
'availableValues' => null
],
'field2' => [
'key' => 'dimensionScope',
'title' => Piwik::translate('GoogleAnalyticsImporter_DimensionScope'),
'uiControl' => 'select',
'availableValues' => [
'visit' => Piwik::translate('General_Visit'),
'action' => Piwik::translate('General_Action')]
]
],
'extraCustomDimensionsFieldGA4' => [
'field1' => [
'key' => 'ga4Dimension',
'title' => Piwik::translate('GoogleAnalyticsImporter_GA4Dimension'),
'uiControl' => 'text',
'availableValues' => null
],
'field2' => [
'key' => 'dimensionScope',
'title' => Piwik::translate('GoogleAnalyticsImporter_DimensionScope'),
'uiControl' => 'select',
'availableValues' => [
'visit' => Piwik::translate('General_Visit'),
'action' => Piwik::translate('General_Action')]
]
],
'streamIdsFieldGA4' => [
'field1' => [
'key' => 'streamId',
'title' => Piwik::translate('GoogleAnalyticsImporter_StreamId'),
'uiControl' => 'text',
'availableValues' => null
]
],
'extensions' => self::getComponentExtensions(),
'configureConnectionProps' => $configureConnectionProps
]
);
}
public function forwardToAuth()
{
Piwik::checkUserHasSuperUserAccess();
Nonce::checkNonce('gaimport.auth', Common::getRequestVar('auth_nonce'));
/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);
/** @var \Google\Client $client */
$client = $authorization->getConfiguredClient();
$state = Nonce::getNonce(self::OAUTH_STATE_NONCE_NAME, 900);
$client->setState($state);
$client->setPrompt('consent');
Url::redirectToUrl($client->createAuthUrl());
}
public function deleteClientCredentials()
{
Piwik::checkUserHasSuperUserAccess();
Nonce::checkNonce('GoogleAnalyticsImporter.deleteGoogleClientConfig', Common::getRequestVar('config_nonce'));
/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);
$config = $authorization->getClientConfiguration();
$authorization->deleteClientConfiguration();
Piwik::postEvent('GoogleAnalyticsImporter.removeClientConfiguration.end', [$config]);
// Redirect to index so that will be the URL and not the delete URL
Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified(['action' => 'index', 'code' => null, 'scope' => null, 'state' => null]));
}
/**
* Processes the response from google oauth service
*
* @return string
* @throws \Exception
*/
public function processAuthCode()
{
Piwik::checkUserHasSuperUserAccess();
$error = Common::getRequestVar('error', '');
$oauthCode = Common::getRequestVar('code', '');
$state = Common::getRequestVar('state');
if ($state && !empty($_SERVER['HTTP_REFERER']) && stripos($_SERVER['HTTP_REFERER'], 'https://accounts.google.') === 0) {
//We need to update this, else it will fail for referer like https://accounts.google.co.in
$_SERVER['HTTP_REFERER'] = 'https://accounts.google.com';
}
Nonce::checkNonce(self::OAUTH_STATE_NONCE_NAME, $state, 'google.com');
if ($error) {
return $this->index($error);
}
try {
/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);
$client = $authorization->getConfiguredClient();
$authorization->saveAccessToken($oauthCode, $client);
$config = $authorization->getClientConfiguration();
Piwik::postEvent('GoogleAnalyticsImporter.authorizedClientConfiguration.end', [$config]);
} catch (\Exception $e) {
return $this->index($this->getNotificationExceptionText($e));
}
// reload index action to prove everything is configured
$this->redirectToIndex('GoogleAnalyticsImporter', 'index');
}
public function configureClient()
{
Piwik::checkUserHasSuperUserAccess();
Nonce::checkNonce('GoogleAnalyticsImporter.googleClientConfig', Common::getRequestVar('config_nonce'));
if (\Piwik\Plugins\GoogleAnalyticsImporter\GoogleAnalyticsImporter::isConnectAccountsPluginActivated() && GoogleConnect::isStrategyActive()) {
GoogleConnect::disableMatomoCloudOverride();
}
/** @var Authorization $authorization */
$authorization = StaticContainer::get(Authorization::class);
$errorMessage = null;
try {
$config = Common::getRequestVar('client', '');
$config = Common::unsanitizeInputValue($config);
if (empty($config) && !empty($_FILES['clientfile'])) {
if (!empty($_FILES['clientfile']['error'])) {
throw new \Exception('Client file upload failed: ' . $_FILES['clientfile']['error']);
}
$file = $_FILES['clientfile']['tmp_name'];
if (!file_exists($file)) {
$logger = StaticContainer::get(LoggerInterface::class);
$logger->error('Client file upload failed: temporary file does not exist (path is {path})', ['path' => $file]);
throw new \Exception('Client file upload failed: temporary file does not exist');
}
$config = file_get_contents($_FILES['clientfile']['tmp_name']);
}
$authorization->validateConfig($config);
$authorization->saveConfig($config);
Piwik::postEvent('GoogleAnalyticsImporter.addClientConfiguration.end', [$config]);
} catch (\Exception $ex) {
$errorMessage = $this->getNotificationExceptionText($ex);
$errorMessage = substr($errorMessage, 0, 1024);
}
$modifiedParameters = ['action' => 'index', 'error' => $errorMessage];
$hashParams = '';
$isNoDataPage = Common::getRequestVar('isNoDataPage', '');
if ($isNoDataPage) {
$hashParams = '#?activeTab=googleanalyticsimporter';
$modifiedParameters = ['module' => 'CoreHome', 'action' => 'index'];
}
Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified($modifiedParameters) . $hashParams);
}
public function deleteImportStatus()
{
Piwik::checkUserHasSuperUserAccess();
$this->checkTokenInUrl();
Json::sendHeaderJSON();
try {
Nonce::checkNonce('GoogleAnalyticsImporter.stopImportNonce', Common::getRequestVar('nonce'));
$idSite = Common::getRequestVar('idSite', null, 'int');
/** @var ImportStatus $importStatus */
$importStatus = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::class);
$status = $importStatus->getImportStatus($idSite);
$importStatus->deleteStatus($idSite);
echo json_encode(['result' => 'ok']);
Piwik::postEvent('GoogleAnalyticsImporter.deleteImportStatus.end', [$status]);
} catch (\Exception $ex) {
$this->logException($ex, __FUNCTION__);
$notification = new Notification($this->getNotificationExceptionText($ex));
$notification->type = Notification::TYPE_TRANSIENT;
$notification->context = Notification::CONTEXT_ERROR;
$notification->title = Piwik::translate('General_Error');
Notification\Manager::notify('GoogleAnalyticsImporter_deleteImportStatus_failure', $notification);
}
}
public function changeImportEndDate()
{
Piwik::checkUserHasSuperUserAccess();
$this->checkTokenInUrl();
Json::sendHeaderJSON();
try {
Nonce::checkNonce('GoogleAnalyticsImporter.changeImportEndDateNonce', Common::getRequestVar('nonce'));
$idSite = Common::getRequestVar('idSite', null, 'int');
$endDate = Common::getRequestVar('endDate', '', 'string');
$inputEndDate = StaticContainer::get(EndDate::class);
$endDate = $inputEndDate->limitMaxEndDateIfNeeded($endDate);
/** @var ImportStatus $importStatus */
$importStatus = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::class);
$status = $importStatus->getImportStatus($idSite);
$importStatus->setImportDateRange($idSite, empty($status['import_range_start']) ? null : Date::factory($status['import_range_start']), empty($endDate) ? null : Date::factory($endDate));
echo json_encode(['result' => 'ok']);
} catch (\Exception $ex) {
$this->logException($ex, __FUNCTION__);
$notification = new Notification($this->getNotificationExceptionText($ex));
$notification->type = Notification::TYPE_TRANSIENT;
$notification->context = Notification::CONTEXT_ERROR;
$notification->title = Piwik::translate('General_Error');
Notification\Manager::notify('GoogleAnalyticsImporter_changeImportEndDate_failure', $notification);
}
}
public function startImportGA4()
{
Piwik::checkUserHasSuperUserAccess();
$this->checkTokenInUrl();
Json::sendHeaderJSON();
try {
Nonce::checkNonce('GoogleAnalyticsImporter.startImportNonce', Common::getRequestVar('nonce'));
$startDate = trim(Common::getRequestVar('startDate', ''));
if (!empty($startDate)) {
$startDate = Date::factory($startDate . ' 00:00:00');
}
$endDate = trim(Common::getRequestVar('endDate', ''));
$inputEndDate = StaticContainer::get(EndDate::class);
$endDate = $inputEndDate->limitMaxEndDateIfNeeded($endDate);
if (!empty($endDate)) {
$endDate = Date::factory($endDate)->getStartOfDay();
}
// set credentials in google client
$googleAuth = StaticContainer::get(AuthorizationGA4::class);
/** @var ImporterGA4 $importer */
$importer = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImporterGA4::class);
$importer->setGAClient($googleAuth->getClient());
$importer->setGAAdminClient($googleAuth->getAdminClient());
$propertyId = trim(Common::getRequestVar('propertyId'));
ImportGA4Reports::validatePropertyID($propertyId);
$isMobileApp = Common::getRequestVar('isMobileApp', 0, 'int') == 1;
$timezone = trim(Common::getRequestVar('timezone', '', 'string'));
$extraCustomDimensions = Common::getRequestVar('extraCustomDimensions', [], $type = 'array');
$streamIds = $this->getStreamIdsFromRequest();
$isVerboseLoggingEnabled = Common::getRequestVar('isVerboseLoggingEnabled', 0, $type = 'int') == 1;
$forceCustomDimensionSlotCheck = Common::getRequestVar('forceCustomDimensionSlotCheck', 1, $type = 'int') == 1;
$idSite = $importer->makeSite($propertyId, $timezone, $isMobileApp ? Type::ID : \Piwik\Plugins\WebsiteMeasurable\Type::ID, $extraCustomDimensions, $forceCustomDimensionSlotCheck, $streamIds);
try {
if (empty($idSite)) {
throw new \Exception("Unable to import site entity.");
// sanity check
}
/** @var ImportStatus $importStatus */
$importStatus = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::class);
if (!empty($startDate) || !empty($endDate)) {
// we set the last imported date to one day before the start date
$importStatus->setImportDateRange($idSite, $startDate ?: null, $endDate ?: null);
}
if ($isVerboseLoggingEnabled) {
$importStatus->setIsVerboseLoggingEnabled($idSite, $isVerboseLoggingEnabled);
}
// start import now since the scheduled task may not run until tomorrow
$status = $importStatus->getImportStatus($idSite);
\Piwik\Plugins\GoogleAnalyticsImporter\Tasks::startImportGA4($status);
Piwik::postEvent('GoogleAnalyticsImporter.startImportGA4.end', [$status]);
} catch (\Exception $ex) {
$importStatus->erroredImport($idSite, $ex->getMessage());
throw $ex;
}
echo json_encode(['result' => 'ok']);
} catch (\Exception $ex) {
$this->logException($ex, __FUNCTION__);
$notification = new Notification($this->getNotificationExceptionText($ex));
$notification->type = Notification::TYPE_TRANSIENT;
$notification->context = Notification::CONTEXT_ERROR;
$notification->title = Piwik::translate('General_Error');
Notification\Manager::notify('GoogleAnalyticsImporter_startImport_failure', $notification);
}
}
public function resumeImport()
{
Piwik::checkUserHasSuperUserAccess();
$this->checkTokenInUrl();
Json::sendHeaderJSON();
try {
Nonce::checkNonce('GoogleAnalyticsImporter.resumeImportNonce', Common::getRequestVar('nonce'));
$idSite = Common::getRequestVar('idSite', null, 'int');
$isGA4 = Common::getRequestVar('isGA4', 0, 'int') == 1;
new Site($idSite);
/** @var ImportStatus $importStatus */
$importStatus = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::class);
$status = $importStatus->getImportStatus($idSite);
if ($status['status'] == \Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::STATUS_FINISHED) {
throw new \Exception("This import cannot be resumed since it is finished.");
}
if ($status['status'] != \Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::STATUS_FUTURE_DATE_IMPORT_PENDING) {
// If we do not check this, future import dates will not be processed, and it will be marked as finished
$importStatus->resumeImport($idSite);
}
if ($isGA4) {
\Piwik\Plugins\GoogleAnalyticsImporter\Tasks::startImportGA4($status);
}
echo json_encode(['result' => 'ok']);
Piwik::postEvent('GoogleAnalyticsImporter.resumeImport.end', [$status]);
} catch (\Exception $ex) {
$this->logException($ex, __FUNCTION__);
$notification = new Notification($this->getNotificationExceptionText($ex));
$notification->type = Notification::TYPE_TRANSIENT;
$notification->context = Notification::CONTEXT_ERROR;
$notification->title = Piwik::translate('General_Error');
Notification\Manager::notify('GoogleAnalyticsImporter_resumeImport_failure', $notification);
}
}
public function scheduleReImport()
{
Piwik::checkUserHasSuperUserAccess();
$this->checkTokenInUrl();
Json::sendHeaderJSON();
try {
Nonce::checkNonce('GoogleAnalyticsImporter.scheduleReImport', Common::getRequestVar('nonce'));
$idSite = Common::getRequestVar('idSite', null, 'int');
new Site($idSite);
$isGA4 = Common::getRequestVar('isGA4', 0, 'int') == 1;
if (!$isGA4) {
throw new \Exception('Reimport for GA3 is disabled, as it will lead to data loss for already imported date ranges.');
}
$startDate = Common::getRequestVar('startDate', null, 'string');
$startDate = Date::factory($startDate);
$endDate = Common::getRequestVar('endDate', null, 'string');
$inputEndDate = StaticContainer::get(EndDate::class);
$endDate = $inputEndDate->limitMaxEndDateIfNeeded($endDate);
$endDate = Date::factory($endDate);
/** @var ImportStatus $importStatus */
$importStatus = StaticContainer::get(\Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus::class);
$status = $importStatus->getImportStatus($idSite);
//For UI test to work properly after an error
if ($isGA4 && defined('PIWIK_TEST_MODE') && $status['import_range_end'] === '2019-07-02') {
$importStatus->setImportDateRange($idSite, $startDate, $endDate);
}
$importStatus->reImportDateRange($idSite, $startDate, $endDate);
$importStatus->resumeImport($idSite);
// start import now since the scheduled task may not run until tomorrow
if ($isGA4) {
\Piwik\Plugins\GoogleAnalyticsImporter\Tasks::startImportGA4($importStatus->getImportStatus($idSite));
}
echo json_encode(['result' => 'ok']);
$status = $importStatus->getImportStatus($idSite);
Piwik::postEvent('GoogleAnalyticsImporter.scheduleReImport.end', [$status]);
} catch (\Exception $ex) {
$this->logException($ex, __FUNCTION__);
$notification = new Notification($this->getNotificationExceptionText($ex));
$notification->type = Notification::TYPE_TRANSIENT;
$notification->context = Notification::CONTEXT_ERROR;
$notification->title = Piwik::translate('General_Error');
Notification\Manager::notify('GoogleAnalyticsImporter_rescheduleImport_failure', $notification);
}
}
private function logException(\Throwable $ex, $functionName)
{
StaticContainer::get(LoggerInterface::class)->debug('Encountered exception in GoogleAnalyticsImporter.{function} controller method: {exception}', ['exception' => $ex, 'function' => $functionName]);
}
private function getNotificationExceptionText(\Exception $e)
{
$message = $e->getMessage();
$messageContent = @json_decode($message, \true);
if (\Piwik_ShouldPrintBackTraceWithMessage()) {
$message .= "\n" . $e->getTraceAsString();
} else {
if (isset($messageContent['error']['message'])) {
$message = $messageContent['error']['message'];
}
}
return $message;
}
public function pendingImports()
{
$pendingImports = \Piwik\Plugins\GoogleAnalyticsImporter\GoogleAnalyticsImporter::canDisplayImportPendingNotice();
return json_encode($pendingImports);
}
/**
* Helps to determine whether to show notification to configure GA import
* To show a notification, User should be admin and some data should have tracked and no import has configured as well as GA has been detected on the site
* @return Json
*/
public function displayConfigureImportNotification()
{
$showNotification = \false;
$settingsUrl = '';
$currentIdSite = Common::getRequestVar('idSite', -1);
if (Piwik::hasUserSuperUserAccess() && SitesManager::hasTrackedAnyTraffic($currentIdSite) && class_exists(\Piwik\SiteContentDetector::class)) {
$importStatus = new \Piwik\Plugins\GoogleAnalyticsImporter\ImportStatus();
try {
$status = $importStatus->getAllImportStatuses();
} catch (\Exception $exception) {
$status = [];
//No Import is configured
}
if (empty($status)) {
$siteContentDetector = new \Piwik\SiteContentDetector();
$siteContentDetector->detectContent([GoogleAnalytics4::getId()], $currentIdSite);
if ($siteContentDetector->wasDetected(GoogleAnalytics3::getId()) || $siteContentDetector->wasDetected(GoogleAnalytics4::getId())) {
$showNotification = \true;
$settingsUrl = SettingsPiwik::getPiwikUrl() . 'index.php?' . Url::getQueryStringFromParameters(['idSite' => $currentIdSite, 'module' => 'GoogleAnalyticsImporter', 'action' => 'index']);
}
}
}
return json_encode(['showNotification' => $showNotification, 'configureURL' => $settingsUrl]);
}
/**
* Get the map of component extensions to be passed into the Vue template. This allows other plugins to provide
* content to display in the template. In this case this plugin will display one component, but that can be
* overridden by the ConnectAccounts plugin to display a somewhat different component. This is doing something
* similar to what we use {{ postEvent('MyPlugin.MyEventInATemplate) }} for in Twig templates.
*
* @return array Map of component extensions. Like [ [ 'plugin' => 'PluginName', 'component' => 'ComponentName' ] ]
* See {@link https://developer.matomo.org/guides/in-depth-vue#allowing-plugins-to-add-content-to-your-vue-components the developer documentation} for more information.
*/
public static function getComponentExtensions($isNoDataPage = \false): array
{
$componentExtensions = [];
Piwik::postEvent('GoogleAnalyticsImporter.getGoogleConfigComponentExtensions', [&$componentExtensions, $isNoDataPage]);
return $componentExtensions;
}
private function getStreamIdsFromRequest()
{
$request = \Piwik\Request::fromRequest();
$streamIds = $request->getArrayParameter('streamIds', []);
$ids = [];
if (!empty($streamIds)) {
foreach ($streamIds as $value) {
if (!empty($value['streamId'])) {
$ids[] = $value['streamId'];
}
}
}
return $ids;
}
}