xref: /plugin/botmon/action.php (revision a3c46a2de214b554d1db8cde55322bc5f69dedaf)
1<?php
2
3use dokuwiki\Extension\EventHandler;
4use dokuwiki\Extension\Event;
5use dokuwiki\Logger;
6
7/**
8 * Action Component for the Bot Monitoring Plugin
9 *
10 * @license	GPL 3 (http://www.gnu.org/licenses/gpl.html)
11 * @author	 Sascha Leib <sascha.leib(at)kolmio.com>
12 */
13
14class action_plugin_botmon extends DokuWiki_Action_Plugin {
15
16	/**
17	 * Registers a callback functions
18	 *
19	 * @param EventHandler $controller DokuWiki's event controller object
20	 * @return void
21	 */
22	public function register(EventHandler $controller) {
23
24		// insert header data into the page:
25		$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'insertHeader');
26
27		// write to the log after the page content was displayed:
28		$controller->register_hook('TPL_CONTENT_DISPLAY', 'AFTER', $this, 'writeServerLog');
29
30	}
31
32	/* session information */
33	private $sessionId = null;
34	private $sessionType = '';
35	private $ipAddress = null;
36
37	/**
38	 * Inserts tracking code to the page header
39	 *
40	 * @param Event $event event object by reference
41	 * @return void
42	 */
43	public function insertHeader(Event $event, $param) {
44
45		global $INFO;
46
47		// populate the session id and type:
48		$this->getSessionInfo();
49
50		// is there a user logged in?
51		$username = ( !empty($INFO['userinfo']) && !empty($INFO['userinfo']['name']) ?  $INFO['userinfo']['name'] : '');
52
53		// build the tracker code:
54		$code = NL . DOKU_TAB . "document._botmon = {'t0': Date.now(), 'session': '" . json_encode($this->sessionId) . "'};" . NL;
55		if ($username) {
56			$code .= DOKU_TAB . 'document._botmon.user = "' . $username . '";'. NL;
57		}
58
59		// add the deferred script loader::
60		$code .= DOKU_TAB . "addEventListener('DOMContentLoaded', function(){" . NL;
61		$code .= DOKU_TAB . DOKU_TAB . "const e=document.createElement('script');" . NL;
62		$code .= DOKU_TAB . DOKU_TAB . "e.async=true;e.defer=true;" . NL;
63		$code .= DOKU_TAB . DOKU_TAB . "e.src='".DOKU_BASE."lib/plugins/botmon/client.js';" . NL;
64		$code .= DOKU_TAB . DOKU_TAB . "document.getElementsByTagName('head')[0].appendChild(e);" . NL;
65		$code .= DOKU_TAB . "});" . NL . DOKU_TAB;
66
67		$event->data['script'][] = ['_data' => $code];
68	}
69
70	/**
71	 * Writes data to the server log.
72	 *
73	 * @return void
74	 */
75	public function writeServerLog(Event $event, $param) {
76
77		global $conf;
78		global $INFO;
79
80		// is there a user logged in?
81		$username = ( !empty($INFO['userinfo']) && !empty($INFO['userinfo']['name'])
82					?  $INFO['userinfo']['name'] : '');
83
84
85
86		// clean the page ID
87		$pageId = preg_replace('/[\x00-\x1F]/', "\u{FFFD}", $INFO['id'] ?? '');
88
89		// create the log array:
90		$logArr = Array(
91			$this->ipAddress, /* remote IP */
92			$pageId, /* page ID */
93			$this->sessionId, /* Session ID */
94			$this->sessionType, /* session ID type */
95			$username, /* user name */
96			$_SERVER['HTTP_USER_AGENT'] ?? '', /* User agent */
97			$_SERVER['HTTP_REFERER'] ?? '', /* HTTP Referrer */
98			substr($conf['lang'],0,2), /* page language */
99			implode(',', array_unique(array_map( function($it) { return substr($it,0,2); }, explode(',',trim($_SERVER['HTTP_ACCEPT_LANGUAGE'], " \t;,*"))))), /* accepted client languages */
100			$this->getCountryCode() /* GeoIP country code */
101		);
102
103		//* create the log line */
104		$filename = __DIR__ .'/logs/' . gmdate('Y-m-d') . '.srv.txt'; /* use GMT date for filename */
105		$logline = gmdate('Y-m-d H:i:s'); /* use GMT time for log entries */
106		foreach ($logArr as $tab) {
107			$logline .= "\t" . $tab;
108		};
109
110		/* write the log line to the file */
111		$logfile = fopen($filename, 'a');
112		if (!$logfile) die();
113		if (fwrite($logfile, $logline . "\n") === false) {
114			fclose($logfile);
115			die();
116		}
117
118		/* Done */
119		fclose($logfile);
120	}
121
122	private function getCountryCode() {
123
124		$country = ( $this->ipAddress == 'localhost' ? 'local' : 'ZZ' ); // default if no geoip is available!
125
126		$lib = $this->getConf('geoiplib'); /* which library to use? (can only be phpgeoip or disabled) */
127
128		try {
129
130			// use GeoIP module?
131			if ($lib == 'phpgeoip' && extension_loaded('geoip') && geoip_db_avail(GEOIP_COUNTRY_EDITION)) { // Use PHP GeoIP module
132				$result = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
133				$country = ($result ? $result : $country);
134			}
135		} catch (Exception $e) {
136			Logger::error('BotMon Plugin: GeoIP Error', $e->getMessage());
137		}
138
139		return $country;
140	}
141
142	private function getSessionInfo() {
143
144		$this->ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
145		if ($this->ipAddress == '127.0.0.1' || $this->ipAddress == '::1') $this->ipAddress = 'localhost';
146
147		// what is the session identifier?
148		if (isset($_SESSION)) {
149			$sesKeys = array_keys($_SESSION); /* DokuWiki Session ID preferred */
150			foreach ($sesKeys as $key) {
151				if (substr($key, 0, 2) == 'DW') {
152					$this->sessionId = $key;
153					$this->sessionType = 'dw';
154					return;
155				}
156			}
157		}
158		if (!$this->sessionId) { /* no DokuWiki Session ID, try PHP session ID */
159			$this->sessionId = session_id();
160			$this->sessionType = 'php';
161		}
162		if (!$this->sessionId && $this->ipAddress) { /* no PHP session ID, try IP address */
163			$this->sessionId = $this->ipAddress;
164			$this->sessionType = 'ip';
165		}
166		if (!$this->sessionId) { /* if everything else fails, just us a random ID */
167			$this->sessionId = rand(1000000, 9999999);
168			$this->sessionType = 'rand';
169		}
170	}
171}