From 32f0677dbca9e3347b931c1d0105eb37aa57e90d Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Fri, 25 Jun 2021 16:21:17 +0200 Subject: [eventlog] Add event filtering and notification system --- modules-available/eventlog/hooks/cron.inc.php | 24 ++ .../eventlog/inc/filterruleprocessor.inc.php | 264 +++++++++++++++++++ .../eventlog/inc/notificationtransport.inc.php | 279 +++++++++++++++++++++ modules-available/eventlog/install.inc.php | 41 +++ modules-available/eventlog/page.inc.php | 69 +++-- modules-available/eventlog/pages/log.inc.php | 57 +++++ .../eventlog/pages/mailconfigs.inc.php | 98 ++++++++ modules-available/eventlog/pages/rules.inc.php | 172 +++++++++++++ .../eventlog/pages/transports.inc.php | 176 +++++++++++++ .../eventlog/permissions/permissions.json | 12 + modules-available/eventlog/templates/_page.html | 1 + modules-available/eventlog/templates/heading.html | 1 - .../templates/page-filters-edit-mailconfig.html | 54 ++++ .../eventlog/templates/page-filters-edit-rule.html | 102 ++++++++ .../templates/page-filters-edit-transport.html | 190 ++++++++++++++ .../templates/page-filters-mailconfigs.html | 42 ++++ .../eventlog/templates/page-filters-rules.html | 44 ++++ .../templates/page-filters-transports.html | 45 ++++ .../eventlog/templates/page-header.html | 16 ++ 19 files changed, 1645 insertions(+), 42 deletions(-) create mode 100644 modules-available/eventlog/inc/filterruleprocessor.inc.php create mode 100644 modules-available/eventlog/inc/notificationtransport.inc.php create mode 100644 modules-available/eventlog/pages/log.inc.php create mode 100644 modules-available/eventlog/pages/mailconfigs.inc.php create mode 100644 modules-available/eventlog/pages/rules.inc.php create mode 100644 modules-available/eventlog/pages/transports.inc.php create mode 100644 modules-available/eventlog/templates/page-filters-edit-mailconfig.html create mode 100644 modules-available/eventlog/templates/page-filters-edit-rule.html create mode 100644 modules-available/eventlog/templates/page-filters-edit-transport.html create mode 100644 modules-available/eventlog/templates/page-filters-mailconfigs.html create mode 100644 modules-available/eventlog/templates/page-filters-rules.html create mode 100644 modules-available/eventlog/templates/page-filters-transports.html create mode 100644 modules-available/eventlog/templates/page-header.html (limited to 'modules-available/eventlog') diff --git a/modules-available/eventlog/hooks/cron.inc.php b/modules-available/eventlog/hooks/cron.inc.php index 180bafd3..bf7ced17 100644 --- a/modules-available/eventlog/hooks/cron.inc.php +++ b/modules-available/eventlog/hooks/cron.inc.php @@ -2,4 +2,28 @@ if (mt_rand(1, 10) === 1) { Database::exec("DELETE FROM eventlog WHERE (UNIX_TIMESTAMP() - 86400 * 190) > dateline"); + // Keep at least 30 events or 7 days wirth of samples (whichever is more) + $types = Database::simpleQuery("SELECT type, Count(*) AS num, Min(dateline) as oldest + FROM `notification_sample` GROUP BY type"); + $cutoff = time() - 86400 * 7; + foreach ($types as $type) { + if ($type['num'] > 30 && $type['oldest'] < $cutoff) { + // This type has more than 30 and the oldest one is older than 7 days + // find out which one takes priority + $thisCutoff = $cutoff; + $find = Database::queryFirst("SELECT dateline FROM notification_sample + WHERE type = :type AND dateline + ORDER BY dateline DESC + LIMIT 29, 1", + ['type' => $type['type']]); + // The 30th entry is older than 7 days? Bump the cutoff dateline back to this date, + // so we keep at least 30 entries + if ($find !== false && $find['dateline'] < $thisCutoff) { + $thisCutoff = $find['dateline']; + } + Database::exec("DELETE FROM notification_sample + WHERE type = :type AND dateline < :dateline", + ['type' => $type['type'], 'dateline' => $thisCutoff]); + } + } } diff --git a/modules-available/eventlog/inc/filterruleprocessor.inc.php b/modules-available/eventlog/inc/filterruleprocessor.inc.php new file mode 100644 index 00000000..f4a84ce1 --- /dev/null +++ b/modules-available/eventlog/inc/filterruleprocessor.inc.php @@ -0,0 +1,264 @@ +, = etc, or "regex" + * arg: what to match via op + * result: if not empty, a string that's added to the fired event. use %1% for the matched value (simple ops), + * or %n% for capture group of regex. supports a couple suffixes like b for bytes, which will turn + * a byte value into a human readable string, eg %1b% will turn 1234567 into 1.18MiB. + * ts = timestamp, d = duration. + */ + + /** + * @param string $type the event. Will either be client state like ~poweron, ~runstate etc. or a client log type + * @param array $data A structured array containing event specific data that can be matched. + */ + public static function applyFilterRules(string $type, array $data) + { + static $lastType; + if ($lastType !== $type) { + $lastType = $type; + $exists = Database::queryFirst("SELECT type + FROM notification_sample + WHERE type = :type AND dateline > UNIX_TIMESTAMP() - 3600 LIMIT 1", + ['type' => $type]); + if ($exists === false) { + Database::exec("INSERT INTO notification_sample (type, dateline, data) + VALUES (:type, UNIX_TIMESTAMP(), :data)", [ + 'type' => $type, + 'data' => json_encode($data), + ]); + } + } + $types = explode('-', $type); + for ($i = 1; $i < count($types); ++$i) { + $types[$i] = $types[$i-1] . '-' . $types[$i]; + } + $res = Database::simpleQuery("SELECT ruleid, datafilter, subject, message + FROM notification_rule + WHERE type IN (:types)", + ['types' => $types]); + // Iterate over all matching filter rules + foreach ($res as $rule) { + if (empty($rule['message']) && empty($rule['subject'])) { + error_log('Filter rule with empty subject and message'); + continue; + } + $filters = json_decode($rule['datafilter'], true); + $globalMatch = true; + $values = []; + // Iterate over all filter-paths of this rule + foreach ($filters['list'] as $key => $filter) { + $index = $filter['index'] ?? $key; + $path = explode('/', $filter['path']); + // Get all items from $data that match the path + $items = self::get($path, $data); + if (empty($items)) { + // If empty, add an empty string to result, so != can match + $items[] = ''; + } + // Iterate over matches in $data - can be multiple if path contains '*' + foreach ($items as $item) { + $match = self::matches($item, $filter); + if ($match === null) + continue; + // Combine if multiple matches + $values[$index] = self::combine($values[$index] ?? [], $match); + } + if (!isset($values[$index])) { + $globalMatch = false; + break; + } + } + if ($globalMatch) { + self::fireEvent($rule, $values); + } + } + } + + /** + * Fire event for given rule, fill templates with data from $values + */ + private static function fireEvent(array $rule, array $values) + { + $ruleid = (int)$rule['ruleid']; + $subject = self::fillTemplate($rule['subject'], $values); + $message = self::fillTemplate($rule['message'], $values); + $ids = Database::queryColumnArray("SELECT transportid + FROM notification_rule_x_transport sfxb + WHERE sfxb.ruleid = :ruleid", ['ruleid' => $ruleid]); + $group = NotificationTransport::newGroup(...$ids); + $group->fire($subject, $message, $values); + } + + /** + * Get value at given path from assoc array. Calls itself recursively until path + * is just one element. Supports special '*' path element, which will return all + * items at the current level. For this reason, the return value is always an array. + * This function is "hacky", as it tries to figure out whether the current key is + * 1) the last path element and 2) matches a known column from the machines array. + * If there exists no such key at the current level, it will be checked whether + * machineuuid (preferred) or clientip exist at the current level, and if so, they + * will be used to query the missing data from the database. + * + * @param array $path array of all the path elements + * @param array $data data to wade through, first element of $path should be in it + * @return array all the matched values + */ + private static function get(array $path, array &$data): array + { + if (empty($path)) + return []; + $pathElement = array_shift($path); + // Get everything on this level + if ($pathElement === '*') { + if (!is_array($data)) + return []; + $return = []; + if (empty($path)) { + // End, everything needs to be primitive types + foreach ($data as $elem) { + if (!is_array($elem)) { + $return[] = $elem; + } + } + } else { + // Expected to go deeper + foreach ($data as $elem) { + if (is_array($elem)) { + $return = array_merge($return, self::get($path, $elem)); + } + } + } + return $return; + } + if (!array_key_exists($pathElement, $data) + && (isset($data['clientip']) || isset($data['machineuuid'])) && in_array($pathElement, self::MACHINE_COLUMNS)) { + if ($pathElement !== 'machineuuid' && isset($data['machineuuid'])) { + $row = Database::queryFirst("SELECT " . implode(',', self::MACHINE_COLUMNS) + . " FROM machine WHERE machineuuid = :uuid", ['uuid' => $data['machineuuid']]); + } elseif ($pathElement !== 'clientip' && isset($data['clientip'])) { + $row = Database::queryFirst("SELECT " . implode(',', self::MACHINE_COLUMNS) + . " FROM machine WHERE clientip = :ip ORDER BY lastseen DESC LIMIT 1", ['ip' => $data['clientip']]); + } else { + $row = false; + } + if ($row !== false) { + error_log('Additional client data fetched on the fly'); + $data += $row; + } + } + if (!array_key_exists($pathElement, $data)) + return []; + if (empty($path) && !is_array($data[$pathElement])) + return [$data[$pathElement]]; + if (!empty($path) && is_array($data[$pathElement])) + return self::get($path, $data[$pathElement]); + return []; // No match + } + + /** + * @param string $item item to match, string or number as string + * @param array $filter filter struct [op, arg, result] + * @return ?array null if op doesn't match, processed result otherwise + */ + private static function matches(string $item, array $filter) + { + $ok = false; + switch ($filter['op']) { + case '*': + $ok = true; + break; + case '>': + $ok = $item > $filter['arg']; + break; + case '>=': + $ok = $item >= $filter['arg']; + break; + case '<': + $ok = $item < $filter['arg']; + break; + case '<=': + $ok = $item <= $filter['arg']; + break; + case '=': + $ok = $item == $filter['arg']; + break; + case '!=': + $ok = $item != $filter['arg']; + break; + case 'regex': + $ok = (bool)preg_match($filter['arg'], $item, $out); + break; + default: + EventLog::warning("Invalid filter OP: {$filter['op']}"); + } + if (!$ok) // No match + return null; + // Fake $out array for simple matches + if ($filter['op'] !== 'regex') { + $out = [1 => $item]; + } + return $out; + } + + private static function fillTemplate(string $template, array $values): string + { + return preg_replace_callback('/%([0-9]+)\.([0-9]+|[a-z][a-z0-9]*)\.?([a-z]*)%/', function($m) use ($values) { + if (!isset($values[$m[1]])) + return ''; + if (!isset($values[$m[1]][$m[2]])) + return ''; + $v = $values[$m[1]][$m[2]]; + $shift = 0; + switch ($m[3]) { + case 'gb': + $shift++; + case 'mb': + $shift++; + case 'kb': + $shift++; + case 'b': + return Util::readableFileSize($v, -1, $shift); + case 'ts': + return Util::prettyTime($v); + case 'd': + return Util::formatDuration($v); + case '': + break; + default: + $v .= '(unknown suffix ' . $m[3] . ')'; + } + return $v; + }, $template); + } + + private static function combine(array $a, array $b): array + { + foreach ($b as $k => $v) { + if (isset($a[$k])) { + $a[$k] .= ', ' . $v; + } else { + $a[$k] = $v; + } + } + return $a; + } + +} \ No newline at end of file diff --git a/modules-available/eventlog/inc/notificationtransport.inc.php b/modules-available/eventlog/inc/notificationtransport.inc.php new file mode 100644 index 00000000..499f6371 --- /dev/null +++ b/modules-available/eventlog/inc/notificationtransport.inc.php @@ -0,0 +1,279 @@ + $ids]); + } + + public abstract function __construct(array $data); + + public abstract function toString(): string; + + public abstract function fire(string $subject, string $message, array $raw): bool; + + public abstract function isValid(): bool; + +} + +class MailNotificationTransport extends NotificationTransport +{ + + /** @var int */ + private $mailConfigId; + + /** @var int[] */ + private $userIds; + + /** @var string */ + private $extraMails; + + public function __construct(array $data) + { + $this->mailConfigId = (int)($data['mail-config-id'] ?? 0); + $this->userIds = array_map(function ($i) { return (int)$i; }, $data['mail-users'] ?? []); + $this->extraMails = (string)($data['mail-extra-mails'] ?? ''); + } + + public function toString(): string + { + static $mailList = null; + if ($mailList === null) { + $mailList = Database::queryIndexedList("SELECT configid, host, senderaddress, replyto + FROM mail_config"); + } + $str = 'Via: ' . ($mailList[$this->mailConfigId]['host'] ?? '') + . ' as ' . ($mailList[$this->mailConfigId]['senderaddress'] ?? $mailList[$this->mailConfigId]['replyto'] ?? ''); + if (!empty($this->userIds)) { + $str .= ', Users: ' . count($this->userIds); + } + if (!empty($this->extraMails)) { + $str .= ', External: ' . substr_count($this->extraMails, '@'); + } + return $str; + } + + public function fire(string $subject, string $message, array $raw): bool + { + if (!$this->isValid()) + return false; + $addrsOut = []; + if (preg_match_all('/[^@\s]+@[^@\s]+/', $this->extraMails, $out)) { + $addrsOut = $out[0]; + } + if (!empty($this->userIds)) { + $mails = Database::queryColumnArray("SELECT email + FROM user + WHERE userid IN (:users)", + ['users' => $this->userIds]); + foreach ($mails as $mail) { + if (preg_match('/^[^@\s]+@[^@\s]+$/', $mail)) { + $addrsOut[] = $mail; + } + } + } + if (empty($addrsOut)) + return false; + Mailer::queue($this->mailConfigId, $addrsOut, $subject, $message); + return true; + } + + public function isValid(): bool + { + if ($this->mailConfigId === 0) + return false; + $mailer = Mailer::instanceFromConfig($this->mailConfigId); + return $mailer !== null; + } +} + +class IrcNotificationTransport extends NotificationTransport +{ + + private $server; + + private $serverPasswort; + + private $target; + + private $nickName; + + public function __construct(array $data) + { + $this->server = $data['irc-server'] ?? ''; + $this->serverPasswort = $data['irc-server-password'] ?? ''; + $this->target = $data['irc-target'] ?? ''; + $this->nickName = $data['irc-nickname'] ?? 'BWLP-' . mt_rand(10000, 99999); + } + + public function toString(): string + { + return '(' . $this->server . '), ' . $this->nickName . ' @ ' . $this->target; + } + + public function fire(string $subject, string $message, array $raw): bool + { + if (!$this->isValid()) + return false; + return !Taskmanager::isFailed(Taskmanager::submit('IrcNotification', [ + 'serverAddress' => $this->server, + 'serverPassword' => $this->serverPasswort, + 'channel' => $this->target, + 'message' => preg_replace('/[\r\n]+\s*/', ' ', $message), + 'nickName' => $this->nickName, + ])); + } + + public function isValid(): bool + { + return !empty($this->server) && !empty($this->target); + } +} + +class HttpNotificationTransport extends NotificationTransport +{ + + /** @var string */ + private $uri; + + /** @var string */ + private $method; + + /** @var string */ + private $postField; + + /** @var string */ + private $postFormat; + + public function __construct(array $data) + { + $this->uri = $data['http-uri'] ?? ''; + $this->method = $data['http-method'] ?? 'POST'; + $this->postField = $data['http-post-field'] ?? 'message=%TEXT%&subject=%SUBJECT%'; + $this->postFormat = $data['http-post-format'] ?? 'FORM'; + } + + public function toString(): string + { + return $this->uri . ' (' . $this->method . ')'; + } + + public function fire(string $subject, string $message, array $raw): bool + { + if (!$this->isValid()) + return false; + $url = str_replace(['%TEXT%', '%SUBJECT%'], [urlencode($message), urlencode($subject)], $this->uri); + if ($this->method === 'POST') { + switch ($this->postFormat) { + case 'FORM': + $body = str_replace(['%TEXT%', '%SUBJECT%'], [urlencode($message), urlencode($subject)], $this->postField); + $ctype = 'application/x-www-form-urlencoded'; + break; + case 'JSON': + $body = str_replace(['%TEXT%', '%SUBJECT%'], [json_encode($message), + json_encode($subject)], $this->postField); + $ctype = 'application/json'; + break; + default: + $out = []; + foreach ($raw as $k1 => $a) { + foreach ($a as $k2 => $v) { + $out["$k1.$k2"] = $v; + } + } + $body = json_encode($out); + $ctype = 'application/json'; + } + } else { + $body = null; + $ctype = null; + } + return !Taskmanager::isFailed(Taskmanager::submit('HttpRequest', [ + 'url' => $url, + 'postData' => $body, + 'contentType' => $ctype, + ])); + } + + public function isValid(): bool + { + return !empty($this->uri); + } +} + +class GroupNotificationTransport extends NotificationTransport +{ + + /** @var int[] list of contained notification transports */ + private $list; + + public function __construct(array $data) + { + $this->list = array_map(function ($i) { return (int)$i; }, $data['group-list'] ?? []); + } + + public function toString(): string + { + static $groupList = null; + if ($groupList === null) { + $groupList = Database::queryKeyValueList("SELECT transportid, title FROM notification_backend"); + } + $out = array_map(function ($i) use ($groupList) { return $groupList[$i] ?? "#$i"; }, $this->list); + return implode(', ', $out); + } + + public function fire(string $subject, string $message, array $raw): bool + { + // This is static, so recursing into groups will keep track of ones we already saw + static $done = false; + $first = ($done === false); + if ($first) { // Non-recursive call, init list + $done = []; + } + $list = array_diff($this->list, $done); + if (!empty($list)) { + $done = array_merge($done, $list); + $res = Database::simpleQuery("SELECT data FROM notification_backend WHERE transportid IN (:ids)", + ['ids' => $list]); + foreach ($res as $row) { + $data = json_decode($row['data'], true); + if (is_array($data)) { + $inst = NotificationTransport::getInstance($data); + if ($inst !== null) { + $inst->fire($subject, $message, $raw); + } + } + } + } + if ($first) { + $done = false; // Outer-most call, reset + } + return true; + } + + public function isValid(): bool + { + // Do we really care about empty groups? They might be pointless, but not really invalid + // We could consider groups containing invalid IDs as invalid, but that would mean that we + // potentially ignore all the other existing IDs in this group, as it would never fire + return true; + } +} \ No newline at end of file diff --git a/modules-available/eventlog/install.inc.php b/modules-available/eventlog/install.inc.php index e5fd32f6..3d252138 100644 --- a/modules-available/eventlog/install.inc.php +++ b/modules-available/eventlog/install.inc.php @@ -13,6 +13,41 @@ KEY `dateline` (`dateline`), KEY `logtypeid` (`logtypeid`,`dateline`) "); +$res[] = tableCreate('notification_rule', ' + `ruleid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, + `title` varchar(100) NOT NULL, + `description` text, + `type` varchar(40) NOT NULL CHARACTER SET ascii, + `datafilter` blob NOT NULL, + `subject` varchar(200) NOT NULL, + `message` text NOT NULL, + PRIMARY KEY (`ruleid`), + KEY `type` (`type`) +'); + +$res[] = tableCreate('notification_backend', ' + `transportid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, + `title` varchar(100) NOT NULL, + `description` text, + `data` blob, + PRIMARY KEY (`transportid`), + KEY (`title`) +'); + +$res[] = tableCreate('notification_rule_x_transport', ' + `ruleid` int(10) UNSIGNED NOT NULL, + `transportid` int(10) UNSIGNED NOT NULL, + PRIMARY KEY (`ruleid`, `transportid`), + KEY (`transportid`) +'); + +$res[] = tableCreate('notification_sample', ' + `type` varchar(40) CHARACTER SET ascii NOT NULL, + `dateline` int(10) UNSIGNED NOT NULL, + `data` blob, + KEY (`type`, `dateline`) +'); + // Update path if (!tableHasColumn('eventlog', 'extra')) { @@ -22,6 +57,12 @@ if (!tableHasColumn('eventlog', 'extra')) { $res[] = UPDATE_DONE; } +// 2021-06-15: Add constraints to filter/backend stuff +$res[] = tableAddConstraint('notification_rule_x_transport', 'ruleid', + 'notification_rule', 'ruleid', 'ON UPDATE CASCADE ON DELETE CASCADE'); +$res[] = tableAddConstraint('notification_rule_x_transport', 'transportid', + 'notification_backend', 'transportid', 'ON UPDATE CASCADE ON DELETE CASCADE'); + // Create response for browser if (in_array(UPDATE_DONE, $res)) { diff --git a/modules-available/eventlog/page.inc.php b/modules-available/eventlog/page.inc.php index 250e1b24..9006c3c5 100644 --- a/modules-available/eventlog/page.inc.php +++ b/modules-available/eventlog/page.inc.php @@ -3,56 +3,43 @@ class Page_EventLog extends Page { + private $show; + protected function doPreprocess() { User::load(); - User::assertPermission('view'); - User::setLastSeenEvent(Property::getLastWarningId()); - } - protected function doRender() - { - Render::addTemplate("heading"); - $lines = array(); - $paginate = new Paginate("SELECT logid, dateline, logtypeid, description, extra FROM eventlog ORDER BY logid DESC", 50); - $res = $paginate->exec(); - foreach ($res as $row) { - $row['date'] = Util::prettyTime($row['dateline']); - $row['icon'] = $this->typeToIcon($row['logtypeid']); - $row['color'] = $this->typeToColor($row['logtypeid']); - $lines[] = $row; + $this->show = Request::any('show', false, 'string'); + if ($this->show === false && Request::isGet()) { + if (User::hasPermission('view')) { + $this->show = 'log'; + } elseif (User::hasPermission('filter.rules.view')) { + $this->show = 'rules'; + } else { + User::assertPermission('filter.transports.view'); + $this->show = 'transports'; + } } - - $paginate->render('_page', array( - 'list' => $lines - )); - } - - private function typeToIcon($type) - { - switch ($type) { - case 'info': - return 'ok'; - case 'warning': - return 'exclamation-sign'; - case 'failure': - return 'remove'; - default: - return 'question-sign'; + if ($this->show !== false) { + $this->show = preg_replace('/[^a-z0-9_\-]/', '', $this->show); + if (!file_exists('modules/eventlog/pages/' . $this->show . '.inc.php')) { + Message::addError('main.invalid-action', $this->show); + Util::redirect('?do=eventlog'); + } else { + require_once 'modules/eventlog/pages/' . $this->show . '.inc.php'; + SubPage::doPreprocess(); + } + } + if (Request::isPost()) { + Util::redirect('?do=eventlog&show=' . $this->show); } } - private function typeToColor($type) + protected function doRender() { - switch ($type) { - case 'info': - return ''; - case 'warning': - return 'orange'; - case 'failure': - return 'red'; - default: - return ''; + Render::addTemplate('page-header', ['active_' . $this->show => 'active']); + if ($this->show !== false) { + SubPage::doRender(); } } diff --git a/modules-available/eventlog/pages/log.inc.php b/modules-available/eventlog/pages/log.inc.php new file mode 100644 index 00000000..a48b4a95 --- /dev/null +++ b/modules-available/eventlog/pages/log.inc.php @@ -0,0 +1,57 @@ +exec(); + foreach ($res as $row) { + $row['date'] = Util::prettyTime($row['dateline']); + $row['icon'] = self::typeToIcon($row['logtypeid']); + $row['color'] = self::typeToColor($row['logtypeid']); + $lines[] = $row; + } + + $paginate->render('_page', array( + 'list' => $lines + )); + } + + private static function typeToIcon($type) + { + switch ($type) { + case 'info': + return 'ok'; + case 'warning': + return 'exclamation-sign'; + case 'failure': + return 'remove'; + default: + return 'question-sign'; + } + } + + private static function typeToColor($type) + { + switch ($type) { + case 'info': + return ''; + case 'warning': + return 'orange'; + case 'failure': + return 'red'; + default: + return ''; + } + } + +} \ No newline at end of file diff --git a/modules-available/eventlog/pages/mailconfigs.inc.php b/modules-available/eventlog/pages/mailconfigs.inc.php new file mode 100644 index 00000000..6d5d20b6 --- /dev/null +++ b/modules-available/eventlog/pages/mailconfigs.inc.php @@ -0,0 +1,98 @@ +', '>=', 'regex']; + + public static function doPreprocess() + { + if (Request::isPost()) { + $action = Request::post('action'); + if ($action === 'save-mailconfig') { + self::saveMailconfig(); + } elseif ($action === 'delete-mailconfig') { + self::deleteMailconfig(); + } else { + Message::addError('main.invalid-action', $action); + } + Util::redirect('?do=eventlog&show=mailconfigs'); + } + } + + private static function saveMailconfig() + { + User::assertPermission('filter.mailconfigs.edit'); + $id = Request::post('id', Request::REQUIRED, 'int'); + $data = [ + 'host' => Request::post('host', Request::REQUIRED, 'string'), + 'port' => Request::post('port', Request::REQUIRED, 'int'), + 'ssl' => Request::post('ssl', Request::REQUIRED, 'string'), + 'senderaddress' => Request::post('senderaddress', Request::REQUIRED, 'string'), + 'replyto' => Request::post('replyto', '', 'string'), + 'username' => Request::post('username', '', 'string'), + 'password' => Request::post('password', '', 'string'), + ]; + if ($id === 0) { + // NEW + Database::exec("INSERT INTO mail_config (host, port, `ssl`, senderaddress, replyto, username, password) + VALUES (:host, :port, :ssl, :senderaddress, :replyto, :username, :password)", $data); + } else { + // UPDATE + $data['configid'] = $id; + Database::exec("UPDATE mail_config SET host = :host, port = :port, `ssl` = :ssl, + senderaddress = :senderaddress, replyto = :replyto, username = :username, password = :password + WHERE configid = :configid", $data); + } + Message::addSuccess("event-mailconfig-saved", $id); + Util::redirect('?do=eventlog&show=mailconfigs'); + } + + private static function deleteMailconfig() + { + User::assertPermission('filter.mailconfigs.edit'); + $id = Request::post('id', Request::REQUIRED, 'int'); + Database::exec("DELETE FROM mail_config WHERE configid = :id", ['id' => $id]); + } + + /* + * + */ + + public static function doRender() + { + $id = Request::get('id', null, 'int'); + if ($id !== null) { + self::showMailconfigEditor($id); + } else { + // LIST + $data = []; + $data['configs'] = Database::queryAll('SELECT configid, host, port, `ssl`, senderaddress, replyto + FROM mail_config + ORDER BY host'); + Render::addTemplate('page-filters-mailconfigs', $data); + } + } + + /** + * @param int $id Config to edit. If id is 0, a new config will be created. + */ + private static function showMailconfigEditor(int $id) + { + if ($id !== 0) { + // EDIT + $data = Database::queryFirst('SELECT configid, host, port, `ssl`, senderaddress, replyto, + username, password + FROM mail_config + WHERE configid = :id', ['id' => $id]); + if ($data === false) { + Message::addError('invalid-mailconfig-id', $id); + Util::redirect('?do=eventlog&show=mailconfigs'); + } + } else { + $data = ['configid' => 0]; + } + Render::addTemplate('page-filters-edit-mailconfig', $data); + } + +} \ No newline at end of file diff --git a/modules-available/eventlog/pages/rules.inc.php b/modules-available/eventlog/pages/rules.inc.php new file mode 100644 index 00000000..131c4eb6 --- /dev/null +++ b/modules-available/eventlog/pages/rules.inc.php @@ -0,0 +1,172 @@ +', '>=', 'regex']; + + public static function doPreprocess() + { + if (Request::isPost()) { + $action = Request::post('action'); + if ($action === 'save-filter') { + self::saveRule(); + } elseif ($action === 'delete-filter') { + self::deleteRule(); + } else { + Message::addError('main.invalid-action', $action); + } + Util::redirect('?do=eventlog&show=rules'); + } + } + + private static function saveRule() + { + User::assertPermission('filter.rules.edit'); + $id = Request::post('id', Request::REQUIRED, 'int'); + $type = Request::post('type', Request::REQUIRED, 'string'); + $title = Request::post('title', Request::REQUIRED, 'string'); + $message = Request::post('message', Request::REQUIRED, 'string'); + $transports = Request::post('transports', [], 'array'); + $filters = Request::post('filter', Request::REQUIRED, 'array'); + $filters = array_filter($filters, function ($item) { + return is_array($item) && !empty($item['path']) && !empty($item['op']); + }); + foreach ($filters as $index => &$item) { + $item['index'] = $index; + } + unset($item); + if (empty($filters)) { + Message::addError('no-valid-filters'); + Util::redirect('?do=eventlog&show=rules'); + } + if ($id === 0) { + $id = null; + } + $data = [ + 'id' => $id, + 'type' => $type, + 'title' => $title, + 'data' => json_encode(['list' => array_values($filters)]), + 'subject' => Request::post('subject', '', 'string'), + 'message' => $message, + ]; + if ($id === null) { + // NEW + Database::exec("INSERT INTO notification_rule (ruleid, type, title, datafilter, subject, message) + VALUES (:id, :type, :title, :data, :subject, :message)", $data); + $id = Database::lastInsertId(); + } else { + Database::exec("UPDATE notification_rule SET type = :type, title = :title, datafilter = :data, + subject = :subject, message = :message + WHERE ruleid = :id", $data); + } + if (empty($transports)) { + Database::exec("DELETE FROM notification_rule_x_transport WHERE ruleid = :id", ['id' => $id]); + } else { + Database::exec("DELETE FROM notification_rule_x_transport + WHERE ruleid = :id AND transportid NOT IN (:transports)", + ['id' => $id, 'transports' => $transports]); + Database::exec("INSERT IGNORE INTO notification_rule_x_transport (ruleid, transportid) + VALUES :list", ['list' => array_map(function ($i) use ($id) { return [$id, $i]; }, $transports)]); + } + Message::addSuccess("event-rule-saved", $id); + Util::redirect('?do=eventlog&show=rules'); + } + + private static function deleteRule() + { + User::assertPermission('filter.rules.edit'); + $id = Request::post('id', Request::REQUIRED, 'int'); + Database::exec("DELETE FROM notification_rule WHERE ruleid = :id", ['id' => $id]); + } + + /* + * + */ + + public static function doRender() + { + $id = Request::get('id', null, 'int'); + if ($id !== null) { + self::showRuleEditor($id); + } else { + // LIST + $data = []; + $data['filters'] = Database::queryAll('SELECT ruleid, type, title, datafilter, + Count(transportid) AS useCount + FROM notification_rule + LEFT JOIN notification_rule_x_transport sfxb USING (ruleid) + GROUP BY ruleid, title + ORDER BY title, ruleid'); + Render::addTemplate('page-filters-rules', $data); + } + } + + /** + * @param int $id Rule to edit. If id is 0, a new rule will be created. + */ + private static function showRuleEditor(int $id) + { + // EDIT + $index = 0; + $existing = []; + if ($id !== 0) { + $data = Database::queryFirst('SELECT ruleid, title, type, datafilter, subject, message + FROM notification_rule WHERE ruleid = :id', ['id' => $id]); + if ($data === false) { + Message::addError('invalid-rule-id', $id); + Util::redirect('?do=eventlog&show=rules'); + } + $list = json_decode($data['datafilter'], true); + if (!is_array($list['list'])) { + $list['list'] = []; + } + foreach ($list['list'] as $item) { + if (isset($item['index'])) { + $existing[] = $item['index']; + } + } + foreach ($list['list'] as &$item) { + if (!isset($item['index'])) { + while (in_array($index, $existing)) { + $index++; + } + $item['index'] = $index++; + } + $item['operators'] = []; + foreach (self::OP_LIST as $op) { + $item['operators'][] = [ + 'name' => $op, + 'selected' => ($op === $item['op']) ? 'selected' : '', + ]; + } + } + $data['filter'] = $list['list']; + } else { + $data = ['filter' => [], 'ruleid' => 0]; + } + for ($i = 0; $i < 2; ++$i) { + while (in_array($index, $existing)) { + $index++; + } + $data['filter'][] = [ + 'index' => $index++, + 'operators' => array_map(function ($item) { return ['name' => $item]; }, self::OP_LIST), + ]; + } + // Add suggestions for type + $data['types'] = Database::queryColumnArray("SELECT DISTINCT type + FROM notification_sample + ORDER BY type"); + // + Module::isAvailable('bootstrap_multiselect'); + $data['transports'] = Database::queryAll("SELECT nb.transportid, nb.title, + IF(sfxb.ruleid IS NULL, '', 'selected') AS selected + FROM notification_backend nb + LEFT JOIN notification_rule_x_transport sfxb ON (sfxb.transportid = nb.transportid AND sfxb.ruleid = :id)", + ['id' => $id]); + Render::addTemplate('page-filters-edit-rule', $data); + } + +} \ No newline at end of file diff --git a/modules-available/eventlog/pages/transports.inc.php b/modules-available/eventlog/pages/transports.inc.php new file mode 100644 index 00000000..b72f36f9 --- /dev/null +++ b/modules-available/eventlog/pages/transports.inc.php @@ -0,0 +1,176 @@ + [Request::REQUIRED, 'string', ['mail', 'irc', 'http', 'group']], + 'mail-config-id' => [0, 'int'], + 'mail-users' => [[], 'int[]'], + 'mail-extra-mails' => ['', 'string'], + 'irc-server' => ['', 'string'], + 'irc-server-password' => ['', 'string'], + 'irc-target' => ['', 'string'], + 'irc-nickname' => ['', 'string'], + 'http-uri' => ['', 'string'], + 'http-method' => ['', 'string', ['GET', 'POST']], + 'http-post-field' => ['', 'string'], + 'http-post-format' => ['', 'string', ['FORM', 'JSON', 'JSON_AUTO']], + 'group-list' => [[], 'int[]'], + ]; + $data = []; + foreach ($types as $key => $def) { + if (substr($def[1], -1) === ']') { + $type = substr($def[1], 0, -2); + $array = true; + } else { + $type = $def[1]; + $array = false; + } + if ($array) { + $value = Request::post($key, [], 'array'); + foreach ($value as &$v) { + settype($v, $type); + if (isset($def[2]) && !in_array($v, $def[2])) { + Message::addWarning('main.value-invalid', $key, $v); + } + } + } else { + $value = Request::post($key, $def[0], $type); + if (isset($def[2]) && !in_array($value, $def[2])) { + Message::addWarning('main.value-invalid', $key, $value); + } + } + $data[$key] = $value; + } + //die(print_r($data)); + $params = [ + 'title' => Request::post('title', 'Backend', 'string'), + 'description' => Request::post('description', '', 'string'), + 'data' => json_encode($data), + ]; + if ($id === 0) { + $res = Database::exec("INSERT INTO notification_backend (title, description, data) + VALUES (:title, :description, :data)", $params); + $id = Database::lastInsertId(); + } else { + $params['transportid'] = $id; + $res = Database::exec("UPDATE notification_backend + SET title = :title, description = :description, data = :data + WHERE transportid = :transportid", $params); + } + if (empty($rules)) { + Database::exec("DELETE FROM notification_rule_x_transport WHERE transportid = :id", ['id' => $id]); + } else { + Database::exec("DELETE FROM notification_rule_x_transport + WHERE transportid = :id AND ruleid NOT IN (:rules)", + ['id' => $id, 'rules' => $rules]); + Database::exec("INSERT IGNORE INTO notification_rule_x_transport (ruleid, transportid) + VALUES :list", ['list' => array_map(function ($i) use ($id) { return [$i, $id]; }, $rules)]); + } + if ($res > 0) { + Message::addSuccess('transport-saved', $id); + } + Util::redirect('?do=eventlog&show=transports§ion=transports'); + } + + private static function deleteTransport() + { + User::assertPermission('filter.transports.edit'); + $id = Request::post('id', Request::REQUIRED, 'int'); + Database::exec("DELETE FROM notification_backend WHERE transportid = :id", ['id' => $id]); + } + + /* + * + */ + + public static function doRender() + { + $id = Request::get('id', null, 'int'); + if ($id !== null) { + self::showTransportEditor($id); + } else { + // LIST + $data = []; + $data['transports'] = []; + foreach (Database::queryAll('SELECT transportid, title, data, + Count(ruleid) AS useCount + FROM notification_backend nb + LEFT JOIN notification_rule_x_transport sfxb USING (transportid) + GROUP BY transportid, title + ORDER BY title, transportid') as $transport) { + $json = json_decode($transport['data'], true); + $transport['type'] = $json['type']; + $transport['details'] = NotificationTransport::getInstance($json); + $data['transports'][] = $transport; + } + Render::addTemplate('page-filters-transports', $data); + } + } + + /** + * @param int $id Transport to edit, 0 to create a new one + */ + private static function showTransportEditor(int $id) + { + if ($id !== 0) { + $entry = Database::queryFirst('SELECT transportid, title, description, data + FROM notification_backend + WHERE transportid = :id', ['id' => $id]); + if ($entry === false) { + Message::addError('invalid-transport-id', $id); + Util::redirect('?do=eventlog&show=transports§ion=transports'); + } + $entry['data'] = json_decode($entry['data'], true); + $entry[($entry['data']['type'] ?? '') . '_selected'] = 'selected'; + $entry[($entry['data']['http-method'] ?? '') . '_selected'] = 'selected'; + $entry[($entry['data']['http-post-format'] ?? '') . '_selected'] = 'selected'; + } else { + $entry = ['transportid' => $id]; + } + $entry['users'] = []; + foreach (Database::queryAll("SELECT userid, login, fullname, email FROM user ORDER BY login") as $row) { + $row['disabled'] = strpos($row['email'], '@') ? '' : 'disabled'; + $row['selected'] = in_array($row['userid'], $entry['data']['mail-users'] ?? []) ? 'selected' : ''; + $entry['users'][] = $row; + } + $entry['mailconfigs'] = []; + foreach (Database::queryAll("SELECT configid, host, port, senderaddress FROM mail_config") as $row) { + $row['selected'] = $row['configid'] == $entry['data']['mail-config-id'] ? 'selected' : ''; + $entry['mailconfigs'][] = $row; + } + foreach (Database::queryAll("SELECT transportid, title FROM notification_backend") as $row) { + $row['selected'] = in_array($row['transportid'], ($entry['data']['group-list'] ?? [])) ? 'selected' : ''; + $entry['backends'][] = $row; + } + Module::isAvailable('bootstrap_multiselect'); + $entry['rules'] = Database::queryAll("SELECT sf.ruleid, sf.title, + IF(sfxb.transportid IS NULL, '', 'selected') AS selected + FROM notification_rule sf + LEFT JOIN notification_rule_x_transport sfxb ON (sf.ruleid = sfxb.ruleid AND sfxb.transportid = :id)", + ['id' => $id]); + Render::addTemplate('page-filters-edit-transport', $entry); + } + +} \ No newline at end of file diff --git a/modules-available/eventlog/permissions/permissions.json b/modules-available/eventlog/permissions/permissions.json index a1748957..e155458c 100644 --- a/modules-available/eventlog/permissions/permissions.json +++ b/modules-available/eventlog/permissions/permissions.json @@ -1,5 +1,17 @@ { "view": { "location-aware": false + }, + "filter.rules.view": { + "location-aware": false + }, + "filter.rules.edit": { + "location-aware": false + }, + "filter.transports.view": { + "location-aware": false + }, + "filter.transports.edit": { + "location-aware": false } } \ No newline at end of file diff --git a/modules-available/eventlog/templates/_page.html b/modules-available/eventlog/templates/_page.html index 6be0bbb8..facdd205 100644 --- a/modules-available/eventlog/templates/_page.html +++ b/modules-available/eventlog/templates/_page.html @@ -1,3 +1,4 @@ +

{{lang_eventLog}}

{{{pagenav}}} diff --git a/modules-available/eventlog/templates/heading.html b/modules-available/eventlog/templates/heading.html index 37612a77..e69de29b 100644 --- a/modules-available/eventlog/templates/heading.html +++ b/modules-available/eventlog/templates/heading.html @@ -1 +0,0 @@ -

{{lang_eventLog}}

\ No newline at end of file diff --git a/modules-available/eventlog/templates/page-filters-edit-mailconfig.html b/modules-available/eventlog/templates/page-filters-edit-mailconfig.html new file mode 100644 index 00000000..07d6e9c0 --- /dev/null +++ b/modules-available/eventlog/templates/page-filters-edit-mailconfig.html @@ -0,0 +1,54 @@ +

{{title}}

+ + + + + +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+
+ + {{lang_cancel}} + + +
+ \ No newline at end of file diff --git a/modules-available/eventlog/templates/page-filters-edit-rule.html b/modules-available/eventlog/templates/page-filters-edit-rule.html new file mode 100644 index 00000000..72a53e9a --- /dev/null +++ b/modules-available/eventlog/templates/page-filters-edit-rule.html @@ -0,0 +1,102 @@ +

{{title}}

+ + + + + +
+
+ + + + {{#types}} + + {{/types}} + +
+
+ + +
+
+
+
+ + +
+
+ {{#filter}} +
+ + + + + +
+ {{/filter}} +
+

{{lang_hintRegex}}

+
+
+ + +
+
+ + +

+ {{lang_messageTemplateHelp}} Platzhalter %zeile.n%, blabla.... +

+
+
+ + {{lang_cancel}} + + +
+ + + \ No newline at end of file diff --git a/modules-available/eventlog/templates/page-filters-edit-transport.html b/modules-available/eventlog/templates/page-filters-edit-transport.html new file mode 100644 index 00000000..77213b28 --- /dev/null +++ b/modules-available/eventlog/templates/page-filters-edit-transport.html @@ -0,0 +1,190 @@ +

{{lang_editFilter}} {{#title}}–{{/title}} {{title}}

+ + + + + +
+
+ + +
+
+ + +
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+ + +
+
+
+ +
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+
+ +
+
+
+ + +

{{lang_uriUseSUBJECTandTEXThint}}

+
+
+ + +
+
+
+
+ + +

{{lang_postUseSUBJECTandTEXThint}}

+
+
+ + +
FORM-data: {{lang_formDataHelp}}
+
json string: {{lang_jsonStringHelp}}
+
{{lang_autoJson}}: {{lang_autoJsonHelp}}
+
templates +
+
+ +
+
+ +
+
+ + +
+
+
+
+ +
+ + +
+ +
+ + +
+ +
+ + {{lang_cancel}} + + +
+ + + \ No newline at end of file diff --git a/modules-available/eventlog/templates/page-filters-mailconfigs.html b/modules-available/eventlog/templates/page-filters-mailconfigs.html new file mode 100644 index 00000000..08901f87 --- /dev/null +++ b/modules-available/eventlog/templates/page-filters-mailconfigs.html @@ -0,0 +1,42 @@ + + + +
+ + + + + + + + + + + {{#configs}} + + + + + + + + {{/configs}} + +
{{lang_id}}{{lang_host}}{{lang_ssl}}{{lang_senderAddress}}{{lang_edit}}
{{configid}}{{host}}:{{port}}{{ssl}}{{senderaddress}}{{^senderaddress}}{{replyto}}{{/senderaddress}} + + + + +
+ + + + \ No newline at end of file diff --git a/modules-available/eventlog/templates/page-filters-rules.html b/modules-available/eventlog/templates/page-filters-rules.html new file mode 100644 index 00000000..524e71b2 --- /dev/null +++ b/modules-available/eventlog/templates/page-filters-rules.html @@ -0,0 +1,44 @@ +
+ + + + + + + + + + + + + + + {{#filters}} + + + + + + + + + {{/filters}} + +
{{lang_id}}{{lang_type}}{{lang_title}}{{lang_edit}}
{{ruleid}}{{type}}{{title}}{{useCount}} + + + + +
+ +
+ + \ No newline at end of file diff --git a/modules-available/eventlog/templates/page-filters-transports.html b/modules-available/eventlog/templates/page-filters-transports.html new file mode 100644 index 00000000..34015f2f --- /dev/null +++ b/modules-available/eventlog/templates/page-filters-transports.html @@ -0,0 +1,45 @@ +
+ + + + + + + + + + + + + + + {{#transports}} + + + + + + + + + {{/transports}} + +
{{lang_id}}{{lang_type}}{{lang_title}}{{lang_details}}{{lang_edit}}
{{transportid}}{{type}}{{title}}{{details.toString}}{{useCount}} + + + + +
+ +
+ + \ No newline at end of file diff --git a/modules-available/eventlog/templates/page-header.html b/modules-available/eventlog/templates/page-header.html new file mode 100644 index 00000000..c3595350 --- /dev/null +++ b/modules-available/eventlog/templates/page-header.html @@ -0,0 +1,16 @@ +

{{lang_logAndEvents}}

+ + \ No newline at end of file -- cgit v1.2.3-55-g7522