summaryrefslogtreecommitdiffstats
path: root/modules-available/statistics/inc/filter.inc.php
blob: 46de467b4fd7bcebec6dcfa97374494087674bba (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php

/* base class with rudimentary SQL generation abilities.
 * WARNING: argument is escaped, but $column and $operator are passed unfiltered into SQL */

class Filter
{
	/**
	 * Delimiter for js_selectize filters
	 */
	const DELIMITER = '~,~';

	public $column;
	public $operator;
	public $argument;

	private static $keyCounter = 0;

	public static function getNewKey($colname)
	{
		return $colname . '_' . (self::$keyCounter++);
	}

	public function __construct($column, $operator, $argument = null)
	{
		$this->column = trim($column);
		$this->operator = trim($operator);
		$this->argument = is_array($argument) ? $argument : trim($argument);
	}

	/* returns a where clause and adds needed operators to the passed array */
	public function whereClause(&$args, &$joins)
	{
		$key = Filter::getNewKey($this->column);
		$addendum = '';

		/* check if we have to do some parsing*/
		if (Page_Statistics::$columns[$this->column]['type'] === 'date') {
			$args[$key] = strtotime($this->argument);
		} else {
			$args[$key] = $this->argument;
			if ($this->operator === '~' || $this->operator === '!~') {
				$args[$key] = str_replace(array('=', '_', '%', '*', '?'), array('==', '=_', '=%', '%', '_'), $args[$key]);
				$addendum = " ESCAPE '='";
			}
		}

		$op = $this->operator;
		if ($this->operator == '~') {
			$op = 'LIKE';
		} elseif ($this->operator == '!~') {
			$op = 'NOT LIKE';
		}

		return $this->column . ' ' . $op . ' :' . $key . $addendum;
	}

	/* parse a query into an array of filters */
	public static function parseQuery($query)
	{
		$operators = ['<=', '>=', '!=', '!~', '=', '~', '<', '>'];
		$filters = [];
		if (empty($query))
			return $filters;
		foreach (explode(self::DELIMITER, $query) as $q) {
			$q = trim($q);
			if (empty($q))
				continue;
			// Special case: User pasted UUID, turn into filter
			if (preg_match('/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/', $q)) {
				$filters[] = new Filter('machineuuid', '=', $q);
				continue;
			}
			// Special case: User pasted IP, turn into filter
			if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $q)) {
				$filters[] = new Filter('clientip', '=', $q);
				continue;
			}
			/* find position of first operator */
			$pos = 10000;
			$operator = false;
			foreach ($operators as $op) {
				$newpos = strpos($q, $op);
				if ($newpos > -1 && ($newpos < $pos)) {
					$pos = $newpos;
					$operator = $op;
				}
			}
			if ($pos == 10000) {
				error_log("couldn't find operator in segment " . $q);
				/* TODO */
				continue;
			}
			$lhs = trim(substr($q, 0, $pos));
			$rhs = trim(substr($q, $pos + strlen($operator)));

			if ($lhs === 'gbram') {
				$filters[] = new RamGbFilter($operator, $rhs);
			} elseif ($lhs === 'runtime') {
				$filters[] = new RuntimeFilter($operator, $rhs);
			} elseif ($lhs === 'state') {
				$filters[] = new StateFilter($operator, $rhs);
			} elseif ($lhs === 'hddgb') {
				$filters[] = new Id44Filter($operator, $rhs);
			} elseif ($lhs === 'location') {
				$filters[] = new LocationFilter($operator, $rhs);
			} elseif ($lhs === 'subnet') {
				$filters[] = new SubnetFilter($operator, $rhs);
			} else {
				if (array_key_exists($lhs, Page_Statistics::$columns) && Page_Statistics::$columns[$lhs]['column']) {
					$filters[] = new Filter($lhs, $operator, $rhs);
				} else {
					Message::addError('invalid-filter-key', $lhs);
				}
			}
		}

		return $filters;
	}
}

class RamGbFilter extends Filter
{
	public function __construct($operator, $argument)
	{
		parent::__construct('mbram', $operator, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		global $SIZE_RAM;
		$lower = floor(Page_Statistics::findBestValue($SIZE_RAM, (int)$this->argument, false) * 1024 - 100);
		$upper = ceil(Page_Statistics::findBestValue($SIZE_RAM, (int)$this->argument, true) * 1024 + 100);
		if ($this->operator == '=') {
			return " mbram BETWEEN $lower AND $upper";
		} elseif ($this->operator == '<') {
			return " mbram < $lower";
		} elseif ($this->operator == '<=') {
			return " mbram <= $upper";
		} elseif ($this->operator == '>') {
			return " mbram > $upper";
		} elseif ($this->operator == '>=') {
			return " mbram >= $lower";
		} elseif ($this->operator == '!=') {
			return " (mbram < $lower OR mbram > $upper)";
		} else {
			error_log("unimplemented operator in RamGbFilter: $this->operator");

			return ' 1';
		}
	}
}

class RuntimeFilter extends Filter
{
	public function __construct($operator, $argument)
	{
		parent::__construct('lastboot', $operator, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		global $SIZE_RAM;
		$upper = time() - (int)$this->argument * 3600;
		$lower = $upper - 3600;
		$common = "state IN ('OCCUPIED', 'IDLE', 'STANDBY') AND";
		if ($this->operator == '=') {
			return "$common ({$this->column} BETWEEN $lower AND $upper)";
		} elseif ($this->operator == '<') {
			return "$common {$this->column} > $upper";
		} elseif ($this->operator == '<=') {
			return "$common {$this->column} > $lower";
		} elseif ($this->operator == '>') {
			return "$common {$this->column} < $lower";
		} elseif ($this->operator == '>=') {
			return "$common {$this->column} < $upper";
		} elseif ($this->operator == '!=') {
			return "$common ({$this->column} < $lower OR {$this->column} > $upper)";
		} else {
			error_log("unimplemented operator in RuntimeFilter: $this->operator");
			return ' 1';
		}
	}
}

class Id44Filter extends Filter
{
	public function __construct($operator, $argument)
	{
		parent::__construct('id44mb', $operator, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		global $SIZE_ID44;
		if ($this->operator === '=' || $this->operator === '!=') {
			$lower = floor(Page_Statistics::findBestValue($SIZE_ID44, $this->argument, false) * 1024 - 100);
			$upper = ceil(Page_Statistics::findBestValue($SIZE_ID44, $this->argument, true) * 1024 + 100);
		} else {
			$lower = $upper = round($this->argument * 1024);
		}

		if ($this->operator === '=') {
			return " id44mb BETWEEN $lower AND $upper";
		} elseif ($this->operator === '!=') {
			return " id44mb < $lower OR id44mb > $upper";
		} elseif ($this->operator === '<=') {
			return " id44mb <= $upper";
		} elseif ($this->operator === '>=') {
			return " id44mb >= $lower";
		} elseif ($this->operator === '<') {
			return " id44mb < $lower";
		} elseif ($this->operator === '>') {
			return " id44mb > $upper";
		} else {
			error_log("unimplemented operator in Id44Filter: $this->operator");

			return ' 1';
		}
	}
}

class StateFilter extends Filter
{
	public function __construct($operator, $argument)
	{
		parent::__construct(null, $operator, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		$map = [ 'on' => ['IDLE', 'OCCUPIED'], 'off' => ['OFFLINE'], 'idle' => ['IDLE'], 'occupied' => ['OCCUPIED'], 'standby' => ['STANDBY'] ];
		$neg = $this->operator == '!=' ? 'NOT ' : '';
		if (array_key_exists($this->argument, $map)) {
			$key = Filter::getNewKey($this->column);
			$args[$key] = $map[$this->argument];
			return " machine.state $neg IN ( :$key ) ";
		} else {
			Message::addError('invalid-filter-argument', 'state', $this->argument);
			return ' 1';
		}
	}
}

class LocationFilter extends Filter
{
	public function __construct($operator, $argument)
	{
		parent::__construct('locationid', $operator, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		$recursive = (substr($this->operator, -1) === '~');
		$this->operator = str_replace('~', '=', $this->operator);

		if (is_array($this->argument)) {
			if ($recursive)
				Util::traceError('Cannot use ~ operator for location with array');
		} else {
			settype($this->argument, 'int');
		}
		$neg = $this->operator === '=' ? '' : 'NOT';
		if ($this->argument === 0) {
			return "machine.locationid IS $neg NULL";
		} else {
			$key = Filter::getNewKey($this->column);
			if ($recursive) {
				$args[$key] = array_keys(Location::getRecursiveFlat($this->argument));
			} else {
				$args[$key] = $this->argument;
			}
			return "machine.locationid $neg IN (:$key)";
		}
	}
}

class SubnetFilter extends Filter
{
	public function __construct($operator, $argument)
	{
		parent::__construct(null, $operator, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		$argument = preg_replace('/[^0-9\.:]/', '', $this->argument);
		return " clientip LIKE '$argument%'";
	}
}

class IsClientFilter extends Filter
{
	public function __construct($argument)
	{
		parent::__construct(null, null, $argument);
	}

	public function whereClause(&$args, &$joins)
	{
		if ($this->argument) {
			$joins[] = ' LEFT JOIN runmode USING (machineuuid)';
			return "(runmode.isclient <> 0 OR runmode.isclient IS NULL)";
		}
		$joins[] = ' INNER JOIN runmode USING (machineuuid)';
		return "runmode.isclient = 0";
	}
}