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 // clean the page ID 85 $pageId = preg_replace('/[\x00-\x1F]/', "\u{FFFD}", $INFO['id'] ?? ''); 86 87 // create the log array: 88 $logArr = Array( 89 $this->ipAddress, /* remote IP */ 90 $pageId, /* page ID */ 91 $this->sessionId, /* Session ID */ 92 $this->sessionType, /* session ID type */ 93 $username, /* user name */ 94 $_SERVER['HTTP_USER_AGENT'] ?? '', /* User agent */ 95 $_SERVER['HTTP_REFERER'] ?? '', /* HTTP Referrer */ 96 substr($conf['lang'],0,2), /* page language */ 97 implode(',', array_unique(array_map( function($it) { return substr($it,0,2); }, explode(',',trim($_SERVER['HTTP_ACCEPT_LANGUAGE'], " \t;,*"))))), /* accepted client languages */ 98 $this->getCountryCode() /* GeoIP country code */ 99 ); 100 101 //* create the log line */ 102 $filename = __DIR__ .'/logs/' . gmdate('Y-m-d') . '.srv.txt'; /* use GMT date for filename */ 103 $logline = gmdate('Y-m-d H:i:s'); /* use GMT time for log entries */ 104 foreach ($logArr as $tab) { 105 $logline .= "\t" . $tab; 106 }; 107 108 /* write the log line to the file */ 109 $logfile = fopen($filename, 'a'); 110 if (!$logfile) die(); 111 if (fwrite($logfile, $logline . "\n") === false) { 112 fclose($logfile); 113 die(); 114 } 115 116 /* Done */ 117 fclose($logfile); 118 } 119 120 private function getCountryCode() { 121 122 $country = ( $this->ipAddress == 'localhost' ? 'local' : 'ZZ' ); // default if no geoip is available! 123 124 $lib = $this->getConf('geoiplib'); /* which library to use? (can only be phpgeoip or disabled) */ 125 126 try { 127 128 // use GeoIP module? 129 if ($lib == 'phpgeoip' && extension_loaded('geoip') && geoip_db_avail(GEOIP_COUNTRY_EDITION)) { // Use PHP GeoIP module 130 $result = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']); 131 $country = ($result ? $result : $country); 132 } 133 } catch (Exception $e) { 134 Logger::error('BotMon Plugin: GeoIP Error', $e->getMessage()); 135 } 136 137 return $country; 138 } 139 140 private function getSessionInfo() { 141 142 $this->ipAddress = $_SERVER['REMOTE_ADDR'] ?? null; 143 if ($this->ipAddress == '127.0.0.1' || $this->ipAddress == '::1') $this->ipAddress = 'localhost'; 144 145 // what is the session identifier? 146 if (isset($_SESSION)) { 147 $sesKeys = array_keys($_SESSION); /* DokuWiki Session ID preferred */ 148 foreach ($sesKeys as $key) { 149 if (substr($key, 0, 2) == 'DW') { 150 $this->sessionId = $key; 151 $this->sessionType = 'dw'; 152 return; 153 } 154 } 155 } 156 if (!$this->sessionId) { /* no DokuWiki Session ID, try PHP session ID */ 157 $this->sessionId = session_id(); 158 $this->sessionType = 'php'; 159 } 160 if (!$this->sessionId && $this->ipAddress) { /* no PHP session ID, try IP address */ 161 $this->sessionId = $this->ipAddress; 162 $this->sessionType = 'ip'; 163 } 164 if (!$this->sessionId) { /* if everything else fails, just us a random ID */ 165 $this->sessionId = rand(1000000, 9999999); 166 $this->sessionType = 'rand'; 167 } 168 } 169}