|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace WebApp\DataModel; |
| 4 | + |
| 5 | +use TgUtils\Date; |
| 6 | +use TgDatabase\Restrictions; |
| 7 | +use WebApp\WebAppException; |
| 8 | + |
| 9 | +/** DataModel class for access logs */ |
| 10 | +class AccessLogDAO extends \TgDatabase\DAO { |
| 11 | + |
| 12 | + public function __construct($database, $checkTable = FALSE) { |
| 13 | + parent::__construct($database, '#__access_log', 'WebApp\\DataModel\\AccessLog', 'uid', $checkTable); |
| 14 | + } |
| 15 | + |
| 16 | + public function createTable() { |
| 17 | + // Create it (try) |
| 18 | + $sql = |
| 19 | + 'CREATE TABLE '.$this->database->quoteName($this->tableName).' ( '. |
| 20 | + '`uid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, '. |
| 21 | + '`session_id` VARCHAR(50) NOT NULL COMMENT \'ID of session\', '. |
| 22 | + '`log_time` DATETIME NOT NULL COMMENT \'When was access logged\', '. |
| 23 | + '`response_code` INT(5) UNSIGNED NOT NULL COMMENT \'HTTP Response Code\', '. |
| 24 | + '`method` VARCHAR(10) NOT NULL COMMENT \'HTTP method\', '. |
| 25 | + '`path` VARCHAR(200) NOT NULL COMMENT \'Path and params\', '. |
| 26 | + '`referer` VARCHAR(200) COMMENT \'Referer if given\', '. |
| 27 | + '`ua` VARCHAR(200) COMMENT \'User Agent\', '. |
| 28 | + '`user_id` INT(10) UNSIGNED NOT NULL COMMENT \'User ID if known\', '. |
| 29 | + 'PRIMARY KEY (`uid`) '. |
| 30 | + ') ENGINE = InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT = \'Access Log\''; |
| 31 | + $res = $this->database->query($sql); |
| 32 | + if ($res === FALSE) { |
| 33 | + throw new WebAppException('Cannot create access log table: '.$this->database->error()); |
| 34 | + } |
| 35 | + return TRUE; |
| 36 | + } |
| 37 | + |
| 38 | + public function log($userId = 0, $request = NULL) { |
| 39 | + if ($request == NULL) $request = \TgUtils\Request::getRequest(); |
| 40 | + if ($request != NULL) { |
| 41 | + $obj = new AccessLog(); |
| 42 | + $obj->session_id = session_id(); |
| 43 | + $obj->log_time = new \TgUtils\Date(time(), WFW_TIMEZONE); |
| 44 | + $obj->response_code = http_response_code(); |
| 45 | + $obj->method = $request->method; |
| 46 | + $obj->path = $request->originalUri; |
| 47 | + $obj->referer = $request->getHeader('referer'); |
| 48 | + $obj->ua = $request->getHeader('user-agent'); |
| 49 | + $obj->user_id = $userId; |
| 50 | + $this->create($obj); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments