File: IcingaApiSearchIdo.php

package info (click to toggle)
icinga 1.0.2-2%2Bsqueeze1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 33,952 kB
  • ctags: 13,294
  • sloc: xml: 154,821; ansic: 99,198; sh: 14,585; sql: 5,852; php: 5,126; perl: 2,838; makefile: 1,268
file content (531 lines) | stat: -rw-r--r-- 15,358 bytes parent folder | download | duplicates (2)
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php

/**
 * 
 * @author Christian Doebler <christian.doebler@netways.de>
 *
 */
class IcingaApiSearchIdo
	extends IcingaApiSearch {

	/*
	 * VARIABLES
	 */

	

	/*
	 * METHODS
	 */

	/**
	 * class constructor
	 *
	 * @param	void
	 * @return	void
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	public function __construct () {
		parent::__construct();
		return $this;
	}

	/**
	 * sets the table prefix
	 *
	 * @param	string		$prefix				table prefix
	 * @return	void
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	public function setTablePrefix ($prefix = null) {
		$this->ifSettings->tablePrefix = $prefix;
	}

	/**
	 * processes custom filter and returns it
	 *
	 * @param	void
	 * @return	string							custom filter
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	private function getFilterAppendix () {
		$customFilter = null;

		foreach ($this->searchFilterAppend as $currentFilter) {
			$conditionPrefix = '${';
			$numFilterMatches = 0;
			$filterMatches = array();

			if(strpos($currentFilter, '${') !== false) {
				$filterPattern = '/\\' . $conditionPrefix . '([^}]+)}/';
				$numFilterMatches = preg_match_all($filterPattern, $currentFilter, $filterMatches);
			}

			if ($numFilterMatches) {
				for ($x = 0; $x < $numFilterMatches; $x++) {
					$match = $filterMatches[0][$x];
					$column = $filterMatches[1][$x];

					if (($column = $this->getColumn($column)) !== false) {
						$currentFilter = str_replace($match, $column, $currentFilter);
					} else {
						throw new IcingaApiSearchIdoException('getFilterAppendix(): unknown column "' . $column . '"!');
						return null;
					}
				}
				$customFilter .= $currentFilter;
			}
		}

		return $customFilter;
	}

	/**
	 * creates where statement for database query
	 *
	 * @param	void 
	 * @return	array							associative array w/ where statement and corresponding values
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	public function createQueryFilter () {

		$whereStatementArray = array();
		$whereStatementValues = array();

		foreach ($this->searchFilter as $key => $filterData) {

			$tmpStatementArray = array();

			foreach ($filterData as $matchType => $valueArray) {

				// create template for current part of where statement
				$separator = $key . ' ' . $matchType . ' ?';
				$numValues = count($valueArray);
				for ($x = 0; $x < $numValues; $x++) {
					array_push($tmpStatementArray, $separator);
				}

				// populate value array
				$whereStatementValues = array_merge($whereStatementValues, $valueArray);

				// create temporary statement
				$tmpStatement = '(' . implode(' or ', $tmpStatementArray) . ')';

			}

			// extend final where statement
			array_push($whereStatementArray, $tmpStatement);

		}

		// create final array
		$whereStatement = 'and ' . implode(' and ', $whereStatementArray);

		$returnData = array (
			'statement'	=> $whereStatement,
			'values'	=> $whereStatementValues,
		);

		return $returnData;

	}

	/**
	 * applies a search type to search columns
	 * @param	string				$fields			fields to extend by search type
	 * @return	string								modified fields
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	private function applySearchType ($fields) {
		switch ($this->searchType) {
			case IcingaApi::SEARCH_TYPE_COUNT:
				$fieldsArray = explode(' ', $fields);
				$countFieldsArray = count($fieldsArray);
				if ($countFieldsArray > 2) {
					throw new IcingaApiSearchException('applySearchType(): invalid number of columns for use of \'count\'!');
				} else {
					$suffix = 'COUNT';
					if ($countFieldsArray == 2) {
						$suffix .= '_' . $fieldsArray[1];
					}
					$fields = 'count(distinct ' . $fieldsArray[0] . ') ' . $suffix;
				}
				break;
		}
		return $fields;
	}

	/**
	 * creates a column to insert into query and pushes it onto the processed stack
	 * @param	string		$columnKey				key that identifies the current column
	 * @return	string								processed column; boolean false on error
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	protected function getColumn ($columnKey) {
		$columnProcessed = false;

		if (array_key_exists($columnKey, $this->ifSettings->columns)) {

			if (array_key_exists($columnKey, $this->columnsProcessed)) {
				$columnProcessed = $this->columnsProcessed[$columnKey];
			} else {
				$table = $this->ifSettings->columns[$columnKey][0];
				$column = $this->ifSettings->columns[$columnKey][1];
				$function = (count($this->ifSettings->columns[$columnKey]) == 3) ?
								$this->ifSettings->columns[$columnKey][2] : false;

				// get TABLE.COLUMN string
				$columnProcessed = sprintf('%s.%s', $table, $column);
	
				// wrap up in function if necessary
				if ($function !== false) {
					$columnProcessed = sprintf ($function, $columnProcessed);
				}

				// store table and processed string for further processing
				if (!in_array($table, $this->joinTables)) {
					array_push($this->joinTables, $table);
				}
				$this->columnsProcessed[$columnKey] = $columnProcessed;
			}

		} else {
			throw new IcingaApiSearchException('getColumn(): Unknown column "' . $columnKey . '"!');
		}

		return $columnProcessed;
	}

	/**
	 * sets result columns for query
	 *
	 * @param	mixed		$columns			array of columns or column as string
	 * @return	IcingaApiSearchInterface
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	public function setResultColumns ($columns) {
		if (!is_array($columns)) {
			$columns = array($columns);
		}

		foreach ($columns as $currentColumn) {
			if (($processedColumn = $this->getColumn($currentColumn)) !== false) {
				array_push($this->resultColumnKeys, $currentColumn);
				array_push($this->resultColumnsNoAliases, $processedColumn);
				$processedColumn .= ' ' . $currentColumn;
				array_push($this->resultColumns, $processedColumn);
			}
		}

		return $this;
	}
	/**
	 * Returns an array containing the columns of the result
	 * 
	 * @return array
	 * @author Jannis Mosshammer <jannis.mosshammer@netways.de>
	 */
	public function getResultColumns() {
		return $this->resultColumnKeys;
	}

	/**
	 * replaces query variables by corresponding data
	 * @param	string			$query			query template
	 * @param	string			$variableName	name of query variable to replace by defined values
	 * @return	string							processed query
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	private function replaceQueryVariables ($query, $variableName) {

		$fieldDefaultMatches = array ();
		$variableValuesPrefix = false;
		$variableValuesTemplate = false;
		$variableValues = false;
		$variableNamePrefix = '${' . $variableName;

		if (strpos($query, $variableNamePrefix . ':') !== false) {
			$fieldPattern = '/\\' . $variableNamePrefix . ':([^}]+)}/';
			preg_match_all($fieldPattern, $query, $fieldDefaultMatches);
		}

		$loopCounter = 0;
		while ($loopCounter < 2 && $variableValues == false) {
			if ($loopCounter && count($fieldDefaultMatches)) {
				$variableValues = $fieldDefaultMatches[1][0];
			}

			switch ($variableName) {
				case 'FIELDS':
					if (!$loopCounter) {
						if (count($this->resultColumns)) {
							$variableValues = $this->applySearchType(implode(',', $this->resultColumns));
							if ($this->ifSettings->statements['fieldsSuffix'] !== false) {
								$variableValues .= $this->ifSettings->statements['fieldsSuffix'];
							}
						}
					} else {
						// add default values to joins
						$valuesLong = explode(',', $variableValues);
						foreach ($valuesLong as $currentValueLong) {
							$valueShort = explode(' ', trim($currentValueLong));
							list($table, $column) = explode('.', $valueShort[0]);
							if (!in_array($table, $this->joinTables)) {
								array_push($this->joinTables, $table);
							}
						}
					}
					break;

				case 'FILTER':
					// TODO: insert processing of default values
					break;

				case 'GROUPBY':
					if (!$loopCounter) {
						list($variableValuesTemplate, $variableValues) =
							$this->ifSettings->createQueryGroup($this->searchGroup, $this->resultColumnsNoAliases);
					} elseif ($variableValues !== false) {
						list($variableValuesTemplate, $variableValues) =
							$this->ifSettings->createQueryGroup(explode(',', $variableValues), $this->resultColumnsNoAliases);
					}
					break;

				case 'ORDERBY':
					if (!$loopCounter) {
						$variableValuesPrefix = $this->ifSettings->statements['order'];
						if (count($this->searchOrder)) {
							$this->searchOrder = implode(',', $this->searchOrder);
							$variableValues = $this->searchOrder;
						}
					} elseif ($variableValues !== false) {
						$this->searchOrder = $variableValues;
					}
					break;

				case 'LIMIT':
					if (!$loopCounter) {
						list($variableValuesTemplate, $variableValues) =
							$this->ifSettings->createQueryLimit($this->searchLimit);
					} elseif ($variableValues !== false) {
						$this->searchLimit = explode(',', $variableValues);
					}
					break;
			}

			$loopCounter++;
		}

		$variableNameComplete = (count($fieldDefaultMatches)) ? $fieldDefaultMatches[0][0] : $variableNamePrefix . '}';

		if (!empty($variableValues)) {
			if (!in_array($variableName, $this->ifSettings->clearVariables)) {
				if ($variableValuesPrefix !== false) {
					$variableValues = $variableValuesPrefix . $variableValues;
				}
				if ($variableValuesTemplate !== false) {
					$variableValues = sprintf (
						$variableValuesTemplate,
						$variableValues
					);
				}
			} else {
				$variableValues = null;
			}
		} else {
			$variableValues = null;
		}

		$query = str_replace($variableNameComplete, $variableValues, $query);

		return $query;

	}

	/**
	 * set joins in query by checking available column tables to reduce overhead
	 * @param	string		$query					base query to process
	 * @return	string								processed query with joins
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	private function setQueryJoins ($query) {
		$conditionPrefix = '${if_table:';
		$numFilterMatches = 0;
		$filterMatches = array();

		if(strpos($query, '${') !== false) {
			$filterPattern = '/\\' . $conditionPrefix . '([^:]+):([^}]+)}/';
			$numFilterMatches = preg_match_all($filterPattern, $query, $filterMatches);
		}

		if ($numFilterMatches) {
			// resolve dependencies of joins
			foreach ($filterMatches[1] as $offset => $tables) {
				$tables = explode(',', $tables);
				if (in_array($tables[0], $this->joinTables)) {
					foreach ($tables as $currentTable) {
						if (!in_array($currentTable, $this->joinTables)) {
							array_push($this->joinTables, $currentTable);
						}
					}
				}
				$filterMatches[1][$offset] = $tables[0];
			}

			// activate joins and remove the ones not needed
			for ($x = 0; $x < $numFilterMatches; $x++) {
				$match = $filterMatches[0][$x];
				$table = $filterMatches[1][$x];
				$join = $filterMatches[2][$x];

				if (in_array($table, $this->joinTables)) {
					$query = str_replace($match, $join, $query);
				} else {
					$query = str_replace($match, null, $query);
				}
			}
		}

		return $query;
	}

	/**
	 * creates and executes database query
	 *
	 * @param	void
	 * @return	boolean							true on success otherwise false
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	public function executeQuery () {

		$success = true;

		if ($this->searchValid()) {

			// create base for query
			$query = $this->ifSettings->queryMap[$this->searchTarget];

			// add query fields
			$query = $this->replaceQueryVariables($query, 'FIELDS');

			// add filter
			if (count($this->searchFilter)) {
				$filterData = $this->createQueryFilter();
				$filterStatement = $filterData['statement'];
				$queryValues = $filterData['values'];
			} else {
				$filterStatement = null;
				$queryValues = array();
			}

			// add custom filter to append
			$filterStatement .= $this->getFilterAppendix();

			// replace query variable by filter
			$query = str_replace('${FILTER}', $filterStatement, $query);

			// add 'group by'
			$query = $this->replaceQueryVariables($query, 'GROUPBY');

			// add order
			$query = $this->replaceQueryVariables($query, 'ORDERBY');

			// add limit
			$query = $this->replaceQueryVariables($query, 'LIMIT');

			// set table prefixes
			$query = str_replace('${TABLE_PREFIX}', $this->ifSettings->tablePrefix, $query);

			// set query joins
			$query = $this->setQueryJoins($query);

			// postprocessing
			if ($this->ifSettings->postProcess === true) {
				$query = $this->ifSettings->postProcessQuery($query, $this->resultColumnKeys, $this->searchOrder, $this->searchLimit);
			}

			$dbResult = $this->connectionObject->query($query, $queryValues);

		} else {

			$success = false;

		}

		return $success;

	}

	/**
	 * (non-PHPdoc)
	 * @see objects/search/IcingaApiSearch#fetch()
	 * @author	Christian Doebler <christian.doebler@netways.de>
	 */
	public function fetch () {
		$object = false;

		$class = 'IcingaApiResultIdo';
		$object = new $class;

		if ($this->executeQuery()) {
			$object->setSearchObject($this->connectionObject->connectionStatement);
			$object->setDbType($this->connectionObject->getDbType());
			if ($this->resultType !== false) {
				$object->setResultType($this->resultType);
			}
			$object->next();
		}

		parent::fetch();
		return $object;
	}

	/**
	 * Map defining which table (shortcuts) will be fetched by which targets
	 */
	public $tableMap = array(
		self::TARGET_HOST => array('h','oh','i','hcg','cg','ocg','cgm','hg','hgm','ohg','cvsh'),
		self::TARGET_SERVICE => array('os','s','i','scg','cg','oc','ss','ocg','hs','sgm','sg','hs','oh','hgm','hg','ohg','cvsh','cvss','cvsc'),
		self::TARGET_HOSTGROUP => array('hg','ohg','hgm','oh'),
		self::TARGET_SERVICEGROUP => array('sg','osg','sgm','os'),
		self::TARGET_CONTACTGROUP => array('cg','ocg','cgm','oc','cvsc'),
		self::TARGET_TIMEPERIOD => array('otp','tp','otp'),
		self::TARGET_CUSTOMVARIABLE => array('cv','cvs'),
		self::TARGET_CONFIG => array('cfv'),
		self::TARGET_PROGRAM => array('pe'),
		self::TARGET_LOG => array('le'),
		self::TARGET_HOST_STATUS_SUMMARY => array('hs','oh','h','i','hcg','cg','cgm','oc','hgm','cvsh','cvsc'),
		self::TARGET_SERVICE_STATUS_SUMMARY => array('os','ss','s','i','scg','cg','cgm','oc','ocg','hs','oh','hgm','ohg','hg','cvsh','cvss','cvsc'),
		self::TARGET_HOST_STATUS_HISTORY => array('oh','sh','h','hcg','cg','ocg','cgm','hgm','hg','cvsh'),
		self::TARGET_SERVICE_STATUS_HISTORY => array('sh','os','s','oh','scg','cg','cgm','hgm','hg','ohg','cvsh','cvss'),
		self::TARGET_HOST_PARENTS => array('ohp','hph','h','oh'),
		self::TARGET_NOTIFICATIONS => array('n','on','s','h','oh','os'),
		self::TARGET_HOSTGROUP_SUMMARY => array('hg','ohg','hgm','oh','hs'),
		self::TARGET_SERVICEGROUP_SUMMARY => array('sg','osg','sgm','ss','os')
	);
	
	/**
	 * returns an array containing the names of all affected columns
	 * @return array
	 * @author Jannis Moßhammer <jannis.mosshammer@netways.de>
	 */
	public function getAffectedColumns() {
		$map = $this->tableMap[$this->getSearchTarget()];
		$affected = array();
		$columns = $this->ifSettings->columns;
		foreach($map as $table) {
			foreach($columns as $name=>$column) {
				if($column[0] == $table)
					$affected[] = $name;
			}
		}
		return $affected;
	}
	
	
}

// extend exceptions
class IcingaApiSearchIdoException extends IcingaApiSearchException {}

?>