xref: /plugin/botmon/pview.php (revision 13c9d29d29e7408533ebf30ae4ac2293f0f4dcda)
1<?php /* BOT MONITOR PLUGIN PAGE VIEW SCRIPT */
2
3/* parse the JSON payload */
4$json = json_decode($_POST['pageview'], true);
5if (!$json) {
6	http_response_code(400);
7	die("Error: Invalid JSON data sent to server.");
8}
9
10// what is the session identifier?
11$sessionId = $json['u'] ?? '';
12$sessionType = 'usr';
13if ($sessionId == '') {
14	$sessionId = $_COOKIE['DokuWiki'] ?? '';
15	$sessionType = 'dw';
16}
17if ($sessionId == '') {
18	$sessionId = $_SERVER['REMOTE_ADDR'] ?? '';
19	if ($sessionId == '127.0.0.1' || $sessionId == '::1') {
20		$sessionId = 'localhost';
21	}
22	$sessionType = 'ip';
23}
24
25/* build the resulting log line (ensure fixed column positions!) */
26$logArr = Array(
27	$_SERVER['REMOTE_ADDR'] ?? '', /* remote IP */
28	$json['pg'] ?? '', /* DW page ID */
29	$sessionId, /* Session ID */
30	$json['u'] ?? '', /* DW User id (if logged in) */
31	$json['lt'] ?? '', /* load time */
32	$json['r'] ?? '', /* Referrer URL */
33	$_SERVER['HTTP_USER_AGENT'] ?? '' /* User agent */
34	// $json['lg'] ?? '', /* browser language */
35	// $json['scr'] ?? '', /* Screen dimensions */
36	// $json['tz'] ?? '', /* timzone offset */
37	// $json['l'] ?? '', /* Accepted languages list */
38	// $json['url'] ?? '', /* Full request URL */
39	// $json['t'] ?? '' /* Page title */
40);
41
42/* create the log line */
43$filename = 'logs/' . gmdate('Y-m-d') . '.log.txt'; /* use server datetime */
44$logline = gmdate('Y-m-d H:i:s');
45foreach ($logArr as $val) {
46	$logline .= "\t" . $val;
47};
48
49/* write the log line to the file */
50$logfile = fopen($filename, 'a');
51if (!$logfile) {
52	http_response_code(500);
53	die("Error: Unable to open log file. Please check file permissions.");
54}
55
56if (fwrite($logfile, $logline . "\n") === false) {
57	http_response_code(500);
58	fclose($logfile);
59	die("Error: Could not write to log file.");
60}
61fclose($logfile);
62
63/* send a 202 response */
64http_response_code(202);
65echo "OK";