Matomo Heartbeat 2021 -
private function createHeartbeatTable() $sql = " CREATE TABLE IF NOT EXISTS matomo_heartbeat_sessions ( id INT AUTO_INCREMENT PRIMARY KEY, session_id VARCHAR(64) NOT NULL, visitor_id VARCHAR(64) NOT NULL, page_url TEXT, start_time DATETIME NOT NULL, last_heartbeat DATETIME NOT NULL, total_engaged_time INT DEFAULT 0, heartbeat_count INT DEFAULT 0, is_active BOOLEAN DEFAULT TRUE, INDEX idx_session (session_id), INDEX idx_visitor (visitor_id), INDEX idx_active (is_active) )"; $this->db->exec($sql);
public function getEngagementMetrics($dateFrom, $dateTo) $stmt = $this->db->prepare(" SELECT COUNT(DISTINCT session_id) as total_sessions, SUM(total_engaged_time) as total_engagement_seconds, AVG(total_engaged_time) as avg_engagement_seconds, AVG(heartbeat_count) as avg_heartbeats_per_session, COUNT(CASE WHEN total_engaged_time > 60 THEN 1 END) as long_sessions, COUNT(CASE WHEN total_engaged_time < 10 THEN 1 END) as bounce_sessions FROM matomo_heartbeat_sessions WHERE start_time BETWEEN ? AND ? AND is_active = 0 "); $stmt->execute([$dateFrom, $dateTo]); $metrics = $stmt->fetch(PDO::FETCH_ASSOC); if ($metrics['total_sessions'] > 0) $metrics['bounce_rate'] = ($metrics['bounce_sessions'] / $metrics['total_sessions']) * 100; $metrics['engagement_rate'] = ($metrics['long_sessions'] / $metrics['total_sessions']) * 100; return $metrics; matomo heartbeat
sendHeartbeat(type) const now = Date.now(); const timeSinceLastHeartbeat = (now - this.lastHeartbeatTime) / 1000; // Don't send heartbeat if too short if (timeSinceLastHeartbeat < this.options.minVisitLength && type === 'ongoing') return; const heartbeatData = action_name: 'Heartbeat', e_c: 'Engagement', e_a: type, e_n: 'User Activity', e_v: Math.floor(timeSinceLastHeartbeat), _cvar: JSON.stringify( heartbeat_interval: this.options.heartbeatInterval, time_on_page: Math.floor((now - this.visitStartTime) / 1000), total_engaged_time: this.totalEngagedTime + Math.floor((now - this.lastHeartbeatTime) / 1000) ) ; // Send to Matomo if (window._paq) window._paq.push(['trackEvent', heartbeatData.e_c, heartbeatData.e_a, heartbeatData.e_n, heartbeatData.e_v]); // Optional: track custom variable window._paq.push(['setCustomVariable', 1, 'HeartbeatType', type, 'page']); this.log(`Heartbeat sent: $type`, heartbeatData); this.lastHeartbeatTime = now; '/matomo
}
private function sendToMatomo($data) $url = $this->matomoUrl . '/matomo.php?' . http_build_query($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 2); // Quick timeout $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $httpCode === 200; '/matomo.php?' . http_build_query($data)

