summaryrefslogtreecommitdiffstats
path: root/modules-available/eventlog/pages/rules.inc.php
blob: 6e1fada2041bdc86a7e31f859a190b805f7c8261 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<?php

class SubPage
{

	const OP_LIST = ['*', '=', '!=', '<', '<=', '>', '>=', 'regex'];

	public static function doPreprocess()
	{
		if (Request::isPost()) {
			User::assertPermission('filter.rules.edit');
			$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', 400);
		}
		if ($id === 0) {
			$id = null;
		}
		$data = [
			'id' => $id,
			'type' => $type,
			'title' => $title,
			'description' => Request::post('description', '', 'string'),
			'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, title, description, type, datafilter, subject, message)
 				VALUES (:id, :title, :description, :type, :data, :subject, :message)", $data);
			$id = Database::lastInsertId();
		} else {
			Database::exec("UPDATE notification_rule SET type = :type, title = :title, description = :description, 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()
	{
		User::assertPermission('filter.rules.view');
		$action = Request::get('action');
		if ($action === 'editrule') {
			self::showRuleEditor();
		} else {
			// LIST
			$data = [];
			$data['filters'] = Database::queryAll('SELECT ruleid, type, title, description, datafilter, lasttime,
       			Count(transportid) AS useCount
				FROM notification_rule
				LEFT JOIN notification_rule_x_transport sfxb USING (ruleid)
				GROUP BY ruleid, title
				ORDER BY SIGN(Count(transportid)) DESC, title, ruleid');
			//usort($data['filters'])
			foreach ($data['filters'] as &$filter) {
				$filter['lasttime_s'] = ($filter['useCount'] > 0 && $filter['lasttime'] > 0) ? Util::prettyTime($filter['lasttime']) : '-';
			}
			Permission::addGlobalTags($data['perms'], null, ['filter.rules.edit']);
			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()
	{
		// EDIT
		User::assertPermission('filter.rules.edit');
		$filterIdx = 0;
		$knownIdxList = [];
		$id = Request::get('id', null, 'int');
		if ($id === 0) {
			// New entry
			$data = ['filter' => [], 'ruleid' => 0];
		} else {
			if ($id > 0) {
				$data = Database::queryFirst('SELECT ruleid, title, description, type, datafilter, subject, message, predefid
					FROM notification_rule WHERE ruleid = :id', ['id' => $id]);
				if ($data === false) {
					Message::addError('invalid-rule-id', $id);
					Util::redirect('?do=eventlog&show=rules');
				}
				$data['edit_warn'] = $data['predefid'] !== null;
				if (Request::get('copy', false, 'bool')) {
					$data['ruleid'] = 0;
					$data['title'] = '';
					$data['edit_warn'] = false;
				}
				$list = (array)json_decode($data['datafilter'], true);
				if (!is_array($list['list'])) {
					$list['list'] = [];
				}
			} else {
				// New from URL
				$data = [
					'ruleid' => 0,
					'type' => Request::get('type', Request::REQUIRED, 'string'),
					'subject' => Request::get('subject', '', 'string'),
					'message' => Request::get('message', '', 'string'),
				];
				$list = ['list' => []];
				foreach (Request::get('filter', [], 'array') as $key => $filter) {
					$list['list'][] = [
						'index' => $filterIdx++,
						'path' => $key,
						'op' => '=',
						'arg' => $filter,
					];
				}
				foreach (Request::get('exists', [], 'array') as $key) {
					$list['list'][] = [
						'index' => $filterIdx++,
						'path' => $key,
						'op' => '*',
					];
				}
			}
			foreach ($list['list'] as $item) {
				if (isset($item['index'])) {
					$knownIdxList[] = $item['index'];
				}
			}
			foreach ($list['list'] as &$item) {
				if (!isset($item['index'])) {
					while (in_array($filterIdx, $knownIdxList)) {
						$filterIdx++;
					}
					$item['index'] = $filterIdx++;
				}
				$item['operators'] = [];
				foreach (self::OP_LIST as $op) {
					$item['operators'][] = [
						'name' => $op,
						'selected' => ($op === $item['op']) ? 'selected' : '',
					];
				}
			}
			$data['filter'] = $list['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]);
		if (Module::isAvailable('statistics')) {
			// Filter keys to suggest for events with machineuuid in data
			$data['machine_keys'] = array_keys(FilterRuleProcessor::HW_QUERIES);
		}
		// Add a few empty rows at the bottom
		for ($i = 0; $i < 8; ++$i) {
			while (in_array($filterIdx, $knownIdxList)) {
				$filterIdx++;
			}
			$data['filter'][] = [
				'index' => $filterIdx++,
				'operators' => array_map(function ($item) { return ['name' => $item]; }, self::OP_LIST),
			];
		}
		Render::addTemplate('page-filters-edit-rule', $data);
	}

}