-
Notifications
You must be signed in to change notification settings - Fork 0
/
page_hits.module
103 lines (95 loc) · 2.6 KB
/
page_hits.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
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
<?php
/**
* @file
* This module used for displaying page statistics.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Clear page_hits table.
*/
function page_hits_flush_all() {
\Drupal::database()->delete('page_hits')
->execute();
}
/**
* Return page hits by node id.
*/
function page_hits_get_data_by_nid($nid) {
$stats = [];
$db = \Drupal::database();
$query = $db->select('page_hits', 'p');
$query->fields('p');
$query->condition('p.nid', $nid);
$result = $query->execute()->fetchAll();
if (!empty($result)) {
return page_hits_calculate_stats($result);
}
return $stats;
}
/**
* Return page hits by page url.
*/
function page_hits_get_data_by_url($page_url) {
$stats = [];
$db = \Drupal::database();
$query = $db->select('page_hits', 'p');
$query->fields('p');
$query->condition('p.url', $page_url);
$result = $query->execute()->fetchAll();
if (!empty($result)) {
return page_hits_calculate_stats($result);
}
return $stats;
}
/**
* Calculate page hits.
*/
function page_hits_calculate_stats(array $result) {
$current_user = \Drupal::currentUser();
$stats = [];
$stats['unique_visits'] = 0;
$stats['total_visitor_by_user'] = 0;
$stats['total_visitor_in_week'] = 0;
$unique_visits = [];
foreach ($result as $value) {
if (!array_key_exists($value->session_id, $unique_visits)) {
$unique_visits[$value->session_id] += 1;
}
if (!empty($current_user) && !empty($current_user->id())) {
if ($value->uid == $current_user->id()) {
$stats['total_visitor_by_user'] += 1;
}
}
$first_day_of_the_week = 'Sunday';
$start_of_the_week = strtotime("Last $first_day_of_the_week");
if (strtolower(date('l')) === strtolower($first_day_of_the_week)) {
$start_of_the_week = strtotime('today');
}
$end_of_the_week = $start_of_the_week + (60 * 60 * 24 * 7) - 1;
if ($value->created >= $start_of_the_week && $value->created <= $end_of_the_week) {
$stats['total_visitor_in_week'] += 1;
}
}
foreach ($unique_visits as $value) {
$stats['unique_visits'] += $value;
}
$stats['ip'] = \Drupal::request()->getClientIp();
$stats['total_visitors'] = (!empty(count($result)) ? count($result) : 0);
return $stats;
}
/**
* Implements hook_help().
*/
function page_hits_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.page_hits':
$text = file_get_contents(dirname(__FILE__) . "/README.txt");
return '<pre>' . $text . '</pre>';
}
}
/**
* Page type.
*/
function page_hits_page_type() {
return \Drupal::request()->attributes->get('node');
}