-
Notifications
You must be signed in to change notification settings - Fork 3
/
google_analytics_counter.module
73 lines (63 loc) · 2.52 KB
/
google_analytics_counter.module
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
<?php
/**
* @file
* Basic functions for this module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\google_analytics_counter\GoogleAnalyticsCounterCommon;
/**
* Implements hook_help().
*/
function google_analytics_counter_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.google_analytics_counter':
$output = file_get_contents(drupal_get_path('module', 'google_analytics_counter') . '/README.txt');;
return nl2br($output);
}
}
/**
* Implements hook_cron().
*/
function google_analytics_counter_cron() {
$config = \Drupal::config('google_analytics_counter.settings');
// Defaults to an hourly interval. Of course, cron has to be running
// at least hourly for this to work.
// $interval must contain value in seconds.
$interval = 60 * $config->get('cron_interval');
// We don't want to act every time cron runs (which could be every minute)
// so keep a time for the next run in a variable.
if (REQUEST_TIME >= \Drupal::state()->get('google_analytics_counter.last_cron_run') + $interval) {
/* @var \Drupal\google_analytics_counter\GoogleAnalyticsCounterCommon $service */
$service = Drupal::service('google_analytics_counter.common');
$queue = \Drupal::queue('google_analytics_counter_worker');
try {
if ($service->isAuthenticated()) {
// Fetch the first batch to see how many there are.
$results = $service->getChunkedResults();
$total = $results->results->totalResults;
// Save the total to show on the overview.
\Drupal::state()->set('google_analytics_counter.total_results', $total);
for($index = 0; $index < $total/$config->get('chunk_to_fetch'); $index++) {
// Add a queue item to fetch for all chunks.
$queue->createItem(['type' => 'fetch', 'index' => $index]);
}
// Queue all the published nodes to be counted
$ids = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->execute();
foreach ($ids as $nid) {
$queue->createItem(['type' => 'count', 'nid' => $nid]);
}
}
else {
\Drupal::logger('google_analytics_counter')->alert('Google Analytics Counter is not authenticated.');
}
}
catch (RuntimeException $e) {
\Drupal::logger('google_analytics_counter')->alert('Cron experienced a problem: ' . $e->getMessage());
}
\Drupal::state()->set('google_analytics_counter.last_cron_run', REQUEST_TIME);
}
}