1<?php
2// Pandora FMS - http://pandorafms.com
3// ==================================================
4// Copyright (c) 2005-2010 Artica Soluciones Tecnologicas
5// Please see http://pandorafms.org for full contribution list
6
7// This program is free software; you can redistribute it and/or
8// modify it under the terms of the GNU General Public License
9// as published by the Free Software Foundation for version 2.
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14
15class Events {
16	private $correct_acl = false;
17	private $acl = "ER";
18
19	private $default = true;
20	private $default_filters = array();
21
22	private $free_search = '';
23	private $hours_old = 8;
24	private $status = 3;
25	private $type = "all";
26	private $severity = -1;
27	private $filter = 0;
28	private $group = 0;
29	private $id_agent = 0;
30	private $all_events = false;
31
32	private $columns = null;
33
34	private $readOnly = false;
35
36	function __construct() {
37		$system = System::getInstance();
38
39		$this->columns = array('agent' => 1);
40
41		if ($system->checkACL($this->acl)) {
42			$this->correct_acl = true;
43		}
44		else {
45			$this->correct_acl = false;
46		}
47	}
48
49	public function setReadOnly() {
50		$this->readOnly = true;
51	}
52
53	public function ajax($parameter2 = false) {
54		$system = System::getInstance();
55
56		if (!$this->correct_acl) {
57			return;
58		}
59		else {
60			switch ($parameter2) {
61				case 'get_events':
62					if ($system->getRequest('agent_events', '0') == 1) {
63						$this->disabledColumns(array('agent'));
64						$filters = array('id_agent' => $system->getRequest('id_agent', 0));
65						$this->setFilters($filters);
66						$this->setReadOnly();
67						$this->eventsGetFilters();
68					}
69					else {
70						$this->eventsGetFilters();
71					}
72
73					$page = $system->getRequest('page', 0);
74
75					$system = System::getInstance();
76
77					$listEvents = $this->getListEvents($page);
78					$events_db = $listEvents['events'];
79					$total_events = $listEvents['total'];
80
81					$events = array();
82					$end = 1;
83					foreach ($events_db as $event) {
84						$end = 0;
85
86						switch ($event['estado']) {
87							case 0:
88								$img_st = "images/star_white.png";
89								break;
90							case 1:
91								$img_st = "images/tick_white.png";
92								break;
93							case 2:
94								$img_st = "images/hourglass_white.png";
95								break;
96						}
97
98						if($event['criticity'] == EVENT_CRIT_WARNING ||
99						$event['criticity'] == EVENT_CRIT_MAINTENANCE ||
100						$event['criticity'] == EVENT_CRIT_MINOR) {
101							$img_st = str_replace("white.png", "dark.png", $img_st);
102						}
103
104						$status_icon = html_print_image($img_st, true);
105
106						$row = array();
107						$row[] = '<b class="ui-table-cell-label">' . __('Event Name') . '</b><a href="javascript: openDetails(' . $event['id_evento'] . ')"><div class="event_name">' . io_safe_output($event['evento']) . '</div></a>';
108
109						if ($event["id_agente"] == 0) {
110							$agent_name = __('System');
111						}
112						else {
113							$agent_name = '<span class="nobold">' . ui_print_agent_name ($event["id_agente"], true, 'agent_small', '', false, '', '', false, false) . '</span>';
114						}
115
116						$row_1 = '<span class="events_agent">' . $agent_name . '</span>';
117						$row_1 .= '<span class="events_timestamp">' . $status_icon . '<br>' . ui_print_timestamp ($event['timestamp_rep'], true, array('units' => 'tiny')) . '</span>';
118
119						$row[] = $row_1;
120
121						$row[] = get_priority_class ($event["criticity"]);
122						$events[$event['id_evento']] = $row;
123					}
124
125					echo json_encode(array('end' => $end, 'events' => $events));
126
127					break;
128				case 'get_detail_event':
129					$system = System::getInstance();
130
131					$id_event = $system->getRequest('id_event', 0);
132
133					$event = events_get_event($id_event);
134					if ($event) {
135						//Check if it is a event from module.
136						if ($event['id_agentmodule'] > 0) {
137							$event['module_graph_link'] =
138								'<a data-ajax="false" href="index.php?page=module_graph&id=' . $event['id_agentmodule'] . '">' .
139								html_print_image('images/chart_curve.png', true, array ("style" => 'vertical-align: middle;')) .
140								'</a>';
141						}
142						else {
143							$event['module_graph_link'] = '<i>' . __('N/A') . '</i>';
144						}
145
146						if ($event['id_agente'] > 0) {
147							$event['agent'] = "<a style='color: black;'" .
148								"href='index.php?page=agent&id=" .
149								$event['id_agente'] . "'>" .
150								agents_get_name($event['id_agente']) .
151								"</a>";
152						}
153						else {
154							$event['agent'] = '<i>' . __('N/A') . '</i>';
155						}
156
157						$event['evento'] = io_safe_output($event['evento']);
158
159						$event['clean_tags'] = events_clean_tags($event['tags']);
160						$event["timestamp"] = date($system->getConfig("date_format"), strtotime($event["timestamp"]));
161						if (empty($event["owner_user"])) {
162							$event["owner_user"] = '<i>' . __('N/A') . '</i>';
163						}
164						else {
165							$user_owner = db_get_value('fullname', 'tusuario', 'id_user', $event["owner_user"]);
166							if (empty($user_owner)) {
167								$user_owner = $event['owner_user'];
168							}
169							$event["owner_user"] = $user_owner;
170						}
171
172						$event["event_type"] = events_print_type_description($event["event_type"], true);
173						$event["event_type"] .= ' ';
174						$event["event_type"] .= events_print_type_img ($event["event_type"], true);
175
176						if (!isset($group_rep))
177							$group_rep = 0;
178
179						if ($group_rep != 0) {
180							if ($event["event_rep"] <= 1) {
181								$event["event_repeated"] = '<i>' . __('No') . '</i>';
182							}
183							else {
184								$event["event_repeated"] = sprintf("%d Times",$event["event_rep"]);
185							}
186						}
187						else {
188							$event["event_repeated"] = '<i>' . __('No') . '</i>';
189						}
190
191						$event_criticity = get_priority_name ($event["criticity"]);
192
193						switch ($event["criticity"]) {
194							default:
195							case 0:
196								$img_sev = "images/status_sets/default/severity_maintenance.png";
197								break;
198							case 1:
199								$img_sev = "images/status_sets/default/severity_informational.png";
200								break;
201							case 2:
202								$img_sev = "images/status_sets/default/severity_normal.png";
203								break;
204							case 3:
205								$img_sev = "images/status_sets/default/severity_warning.png";
206								break;
207							case 4:
208								$img_sev = "images/status_sets/default/severity_critical.png";
209								break;
210							case 5:
211								$img_sev = "images/status_sets/default/severity_minor.png";
212								break;
213							case 6:
214								$img_sev = "images/status_sets/default/severity_major.png";
215								break;
216						}
217
218						$event["criticity"] = ' ' . $event_criticity;
219						$event["criticity"] .= html_print_image ($img_sev, true,
220							array ("class" => "image_status",
221								"width" => 12,
222								"height" => 12,
223								"title" => $event_criticity));
224
225						if ($event['estado'] == 1) {
226							$user_ack = db_get_value('fullname', 'tusuario', 'id_user', $event['id_usuario']);
227							if (empty($user_ack)) {
228								$user_ack = $event['id_usuario'];
229							}
230							$date_ack = date ($system->getConfig("date_format"), $event['ack_utimestamp']);
231							$event["acknowledged_by"] = $user_ack .
232								' (' . $date_ack . ')';
233						}
234						else {
235							$event["acknowledged_by"] = '<i>' . __('N/A') . '</i>';
236						}
237
238						// Get Status
239						switch ($event['estado']) {
240							case 0:
241								$img_st = "images/star_dark.png";
242								$title_st = __('New event');
243								break;
244							case 1:
245								$img_st = "images/tick.png";
246								$title_st = __('Event validated');
247								break;
248							case 2:
249								$img_st = "images/hourglass.png";
250								$title_st = __('Event in process');
251								break;
252						}
253						$event["status"] = $title_st;
254						$event["status"] .= ' ';
255						$event["status"] .= html_print_image($img_st,true);
256
257						$event["group"] = groups_get_name ($event["id_grupo"], true);
258						$event["group"] .= ui_print_group_icon ($event["id_grupo"], true);
259
260						$event["tags"] = tags_get_tags_formatted($event["tags"]);
261						if (empty($event["tags"])) {
262							$event["tags"] = '<i>'.__('N/A').'</i>';
263						}
264
265						$event_comments = db_get_value('user_comment', 'tevento', 'id_evento', $id_event);
266						$event_comments_array = array();
267						$event_comments_array = json_decode($event_comments, true);
268						// Support for new format only.
269						if (empty($event_comments_array)) {
270							$comment = '<i>'.__('N/A').'</i>';
271						} else {
272							$comment = '';
273							$event_comments_array = array_reverse($event_comments_array);
274							foreach($event_comments_array as $c) {
275								$comment .=  date ($system->getConfig("date_format"), $c['utimestamp']) . ' (' . $c['id_user'] . ')';
276								$c['comment'] = io_safe_output($c['comment']);
277								$c['comment'] = str_replace("\n", "<br>", $c['comment']);
278								$comment .= '<br>' . $c['comment'] . '<br>';
279							}
280						}
281
282						$event["comments"] = $comment;
283
284						echo json_encode(array('correct' => 1, 'event' => $event));
285					}
286					else {
287						echo json_encode(array('correct' => 0, 'event' => array()));
288					}
289					break;
290				case 'validate_event':
291					$system = System::getInstance();
292
293					$id_event = $system->getRequest('id_event', 0);
294
295					if (events_change_status($id_event, EVENT_VALIDATE)) {
296						echo json_encode(array('correct' => 1));
297					}
298					else {
299						echo json_encode(array('correct' => 0));
300					}
301					break;
302			}
303		}
304	}
305
306	public function disabledColumns($columns = null) {
307		if (!empty($columns)) {
308			foreach ($columns as $column) {
309				$this->columns[$column] = 1;
310			}
311		}
312	}
313
314	private function eventsGetFilters() {
315		$system = System::getInstance();
316		$user = User::getInstance();
317
318		$this->default_filters['severity'] = true;
319		$this->default_filters['group'] = true;
320		$this->default_filters['type'] = true;
321		$this->default_filters['status'] = true;
322		$this->default_filters['free_search'] = true;
323		$this->default_filters['hours_old'] = true;
324
325		$this->hours_old = $system->getRequest('hours_old', 8);
326		if ($this->hours_old != 8) {
327			$this->default = false;
328			$this->default_filters['hours_old'] = false;
329		}
330
331		$this->free_search = $system->getRequest('free_search', '');
332		if ($this->free_search != '') {
333			$this->default = false;
334			$this->default_filters['free_search'] = false;
335		}
336
337		$this->status = $system->getRequest('status', __("Status"));
338		if (($this->status === __("Status")) || ($this->status == 3)) {
339			$this->status = 3;
340		}
341		else {
342			$this->status = (int)$this->status;
343			$this->default = false;
344			$this->default_filters['status'] = false;
345		}
346
347		$this->type = $system->getRequest('type', __("Type"));
348		if ($this->type === __("Type")) {
349			$this->type = "all";
350		}
351		else {
352			$this->default = false;
353			$this->default_filters['type'] = false;
354		}
355
356		$this->group = $system->getRequest('group', __("Group"));
357		if (!$user->isInGroup($this->acl, $this->group)) {
358			$this->group = 0;
359		}
360		if (($this->group === __("Group")) || ($this->group == 0)) {
361			$this->group = 0;
362		}
363		else {
364			$this->default = false;
365			$this->default_filters['group'] = false;
366		}
367
368		$this->severity = $system->getRequest('severity', __("Severity"));
369		if ($this->severity === __("Severity")) {
370			$this->severity = -1;
371		}
372		else {
373			$this->default = false;
374			$this->default_filters['severity'] = false;
375		}
376
377		$this->filter = $system->getRequest('filter', __('Preset Filters'));
378		if (($this->filter === __("Preset Filters")) || ($this->filter == 0)) {
379			$this->filter = 0;
380		}
381		else {
382			$this->default = false;
383		}
384
385		///The user set a preset filter
386		if ($this->filter > 0) {
387			$this->loadPresetFilter();
388		}
389
390		$this->limit = $system->getRequest('limit', -1);
391	}
392
393	public function setFilters($filters) {
394		if (isset($filters['id_agent'])) {
395			$this->id_agent = $filters['id_agent'];
396		}
397
398		if (isset($filters['all_events'])) {
399			$this->all_events = $filters['all_events'];
400		}
401	}
402
403	private function loadPresetFilter() {
404		$filter = db_get_row('tevent_filter', 'id_filter', $this->filter);
405
406		$this->free_search = $filter['search'];
407		$this->hours_old = $filter['event_view_hr'];
408		$this->status = $filter['status'];
409		$this->type = $filter['event_type'];
410		$this->severity = $filter['severity'];
411	}
412
413	public function show() {
414		if (!$this->correct_acl) {
415			$this->show_fail_acl();
416		}
417		else {
418			$this->eventsGetFilters();
419			$this->show_events();
420		}
421	}
422
423	private function show_fail_acl() {
424		$error['type'] = 'onStart';
425		$error['title_text'] = __('You don\'t have access to this page');
426		$error['content_text'] = __('Access to this page is restricted to authorized users only, please contact system administrator if you need assistance. <br><br>Please know that all attempts to access this page are recorded in security logs of Pandora System Database');
427		if (class_exists("HomeEnterprise"))
428			$home = new HomeEnterprise();
429		else
430			$home = new Home();
431		$home->show($error);
432	}
433
434	public function get_event_dialog_error_options($options) {
435		$options['type'] = 'hidden';
436
437		$options['dialog_id'] = 'detail_event_dialog_error';
438		$options['title_text'] = __('ERROR: Event detail');
439		$options['content_text'] = '<span style="color: #ff0000;">' .
440			__('Error connecting to DB pandora.') . '</span>';
441
442		return $options;
443	}
444
445	public function get_event_dialog_options() {
446		$ui = Ui::getInstance();
447
448		$options['type'] = 'hidden';
449
450		$options['dialog_id'] = 'detail_event_dialog';
451
452		$options['title_close_button'] = true;
453		$options['title_text'] = __('Event detail');
454
455		//Content
456		ob_start();
457		?>
458		<table class="pandora_responsive alternate event_details">
459			<tbody>
460				<tr class="event_name">
461					<td class="cell_event_name" colspan="2"></td>
462				</tr>
463				<tr class="event_id">
464					<th><?php echo __('Event ID');?></th>
465					<td class="cell_event_id"></td>
466				</tr>
467				<tr class="event_timestamp">
468					<th><?php echo __('Timestamp');?></th>
469					<td class="cell_event_timestamp"></td>
470				</tr>
471				<tr class="event_owner">
472					<th><?php echo __('Owner');?></th>
473					<td class="cell_event_owner"></td>
474				</tr>
475				<tr class="event_type">
476					<th><?php echo __('Type');?></th>
477					<td class="cell_event_type"></td>
478				</tr>
479				<tr class="event_repeated">
480					<th><?php echo __('Repeated');?></th>
481					<td class="cell_event_repeated"></td>
482				</tr>
483				<tr class="event_severity">
484					<th><?php echo __('Severity');?></th>
485					<td class="cell_event_severity"></td>
486				</tr>
487				<tr class="event_status">
488					<th><?php echo __('Status');?></th>
489					<td class="cell_event_status"></td>
490				</tr>
491				<tr class="event_acknowledged_by">
492					<th><?php echo __('Acknowledged by');?></th>
493					<td class="cell_event_acknowledged_by"></td>
494				</tr>
495				<tr class="event_group">
496					<th><?php echo __('Group');?></th>
497					<td class="cell_event_group"></td>
498				</tr>
499				</tr>
500				<tr class="event_module_graph">
501					<th><?php echo __('Module Graph');?></th>
502					<td class="cell_module_graph"></td>
503				</tr>
504				<tr class="event_agent">
505					<th><?php echo __('Agent');?></th>
506					<td class="cell_agent"></td>
507				</tr>
508				<tr class="event_tags">
509					<th><?php echo __('Tags');?></th>
510					<td class="cell_event_tags"></td>
511				</tr>
512				<tr class="event_comments">
513					<th><?php echo __('Comments');?></th>
514					<td class="cell_event_comments"></td>
515				</tr>
516			</tbody>
517		</table>
518		<?php
519
520		$options['content_text'] = ob_get_clean();
521
522		$options_button = array(
523				'text' => __('Validate'),
524				'id' => 'validate_button',
525				'href' => 'javascript: validateEvent();');
526		$options['content_text'] .= $ui->createButton($options_button);
527		$options_hidden = array(
528			'id' => 'event_id',
529			'value' => 0,
530			'type' => 'hidden'
531			);
532		$options['content_text'] .= $ui->getInput($options_hidden);
533		$options['content_text'] .= '<div id="validate_button_loading" style="display: none; text-align: center;">
534			<img src="images/ajax-loader.gif" /></div>';
535		$options['content_text'] .= '<div id="validate_button_correct" style="display: none; text-align: center;">
536			<h3>' . __('Sucessful validate') . '</h3></div>';
537		$options['content_text'] .= '<div id="validate_button_fail" style="display: none; text-align: center;">
538			<h3 style="color: #ff0000;">' . __('Fail validate') . '</h3></div>';
539
540		$options['button_close'] = false;
541
542		return $options;
543	}
544
545	private function show_events() {
546		$ui = Ui::getInstance();
547
548		$ui->createPage();
549
550		$options = $this->get_event_dialog_options();
551
552		$ui->addDialog($options);
553
554		$options = $this->get_event_dialog_error_options($options);
555
556		$ui->addDialog($options);
557
558
559		$ui->createDefaultHeader(__("Events"),
560				$ui->createHeaderButton(
561					array('icon' => 'back',
562						'pos' => 'left',
563						'text' => __('Back'),
564						'href' => 'index.php?page=home')));
565		$ui->showFooter(false);
566		$ui->beginContent();
567			$ui->contentAddHtml("<a id='detail_event_dialog_hook' href='#detail_event_dialog' style='display:none;'>detail_event_hook</a>");
568			$ui->contentAddHtml("<a id='detail_event_dialog_error_hook' href='#detail_event_dialog_error' style='display:none;'>detail_event_dialog_error_hook</a>");
569
570			$filter_title = sprintf(__('Filter Events by %s'), $this->filterEventsGetString());
571			$ui->contentBeginCollapsible($filter_title);
572				$ui->beginForm("index.php?page=events");
573				/*
574					$options = array(
575						'name' => 'page',
576						'type' => 'hidden',
577						'value' => 'events'
578						);
579					$ui->formAddInput($options);*/
580
581					$items = db_get_all_rows_in_table('tevent_filter');
582					$items[] = array('id_filter' => 0, 'id_name' => __('None'));
583					$options = array(
584						'name' => 'filter',
585						'title' => __('Preset Filters'),
586						'label' => __('Preset Filters'),
587						'items' => $items,
588						'item_id' => 'id_filter',
589						'item_value' => 'id_name',
590						'selected' => $this->filter
591						);
592					$ui->formAddSelectBox($options);
593
594					$system = System::getInstance();
595					$groups = users_get_groups_for_select(
596						$system->getConfig('id_user'), "ER", true, true, false, 'id_grupo');
597					$options = array(
598						'name' => 'group',
599						'title' => __('Group'),
600						'label' => __('Group'),
601						'items' => $groups,
602						'selected' => $this->group
603						);
604					$ui->formAddSelectBox($options);
605
606					$options = array(
607						'name' => 'status',
608						'title' => __('Status'),
609						'label' => __('Status'),
610						'items' => events_get_all_status(),
611						'selected' => $this->status
612						);
613					$ui->formAddSelectBox($options);
614
615					$options = array(
616						'name' => 'type',
617						'title' => __('Type'),
618						'label' => __('Type'),
619						'items' => array_merge(array("all" => __('All')), get_event_types()),
620						'selected' => $this->type
621						);
622
623					$ui->formAddSelectBox($options);
624
625					$options = array(
626						'name' => 'severity',
627						'title' => __('Severity'),
628						'label' => __('Severity'),
629						'items' => array("-1" => __('All')) + get_priorities(),
630						'selected' => $this->severity
631						);
632					$ui->formAddSelectBox($options);
633
634					$options = array(
635						'name' => 'free_search',
636						'value' => $this->free_search,
637						'placeholder' => __('Free search')
638						);
639					$ui->formAddInputSearch($options);
640
641					$options = array(
642						'label' => __('Max. hours old'),
643						'name' => 'hours_old',
644						'value' => $this->hours_old,
645						'min' => 0,
646						'max' => 24 * 7,
647						'step' => 8
648						);
649					$ui->formAddSlider($options);
650
651					$options = array(
652						'icon' => 'refresh',
653						'icon_pos' => 'right',
654						'text' => __('Apply Filter')
655						);
656					$ui->formAddSubmitButton($options);
657				$html = $ui->getEndForm();
658				$ui->contentCollapsibleAddItem($html);
659			$ui->contentEndCollapsible();
660			$this->listEventsHtml();
661		$ui->endContent();
662		$ui->showPage();
663	}
664
665	private function getListEvents($page = 0) {
666		$system = System::getInstance();
667
668		//--------------Fill the SQL POST-------------------------------
669		$sql_post = '';
670
671		switch ($this->status) {
672			case 0:
673			case 1:
674			case 2:
675				$sql_post .= " AND estado = " . $this->status;
676				break;
677			case 3:
678				$sql_post .= " AND (estado = 0 OR estado = 2)";
679				break;
680		}
681
682		if ($this->free_search != "") {
683			$sql_post .= " AND evento LIKE '%" . io_safe_input($this->free_search) . "%'";
684		}
685
686		if ($this->severity != -1) {
687			switch ($this->severity) {
688				case EVENT_CRIT_WARNING_OR_CRITICAL:
689					$sql_post .= " AND (criticity = " . EVENT_CRIT_WARNING . " OR
690						criticity = " . EVENT_CRIT_CRITICAL . ")";
691					break;
692				case EVENT_CRIT_NOT_NORMAL:
693					$sql_post .= " AND criticity != " . EVENT_CRIT_NORMAL;
694					break;
695				default:
696					$sql_post .= " AND criticity = " . $this->severity;
697					break;
698			}
699		}
700
701		if ($this->hours_old > 0) {
702			$unixtime = get_system_time () - ($this->hours_old * SECONDS_1HOUR);
703			$sql_post .= " AND (utimestamp > " . $unixtime . ")";
704		}
705
706		if ($this->type != "") {
707			// If normal, warning, could be several (going_up_warning, going_down_warning... too complex
708			// for the user so for him is presented only "warning, critical and normal"
709			if ($this->type == "warning" || $this->type == "critical"
710				|| $this->type == "normal") {
711				$sql_post .= " AND event_type LIKE '%" . $this->type . "%' ";
712			}
713			elseif ($this->type == "not_normal") {
714				$sql_post .= " AND event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ";
715			}
716			elseif ($this->type != "all") {
717				$sql_post .= " AND event_type = '" . $this->type."'";
718			}
719
720		}
721
722		$system = System::getInstance();
723		$groups = users_get_groups($system->getConfig('id_user'), 'IR');
724
725		//Group selection
726		if ($this->group > 0 && in_array ($this->group, array_keys ($groups))) {
727			//If a group is selected and it's in the groups allowed
728			$sql_post .= " AND id_grupo = " . $this->group;
729		}
730		else {
731			if (is_user_admin ($system->getConfig('id_user'))) {
732				//Do nothing if you're admin, you get full access
733				$sql_post .= "";
734			}
735			else {
736				//Otherwise select all groups the user has rights to.
737				$sql_post .= " AND id_grupo IN (" .
738					implode (",", array_keys ($groups)) . ")";
739			}
740		}
741
742		if ($this->id_agent > 0) {
743			$sql_post .= " AND id_agente = " . $this->id_agent;
744		}
745
746		// Skip system messages if user is not PM
747		if (!check_acl($system->getConfig('id_user'), 0, "PM")) {
748			$sql_post .= " AND id_grupo != 0";
749		}
750		//--------------------------------------------------------------
751
752		if (isset($this->limit) && $this->limit != -1) {
753			$offset = 0;
754			$pagination = $this->limit;
755		}
756		else {
757			$offset = $page * $system->getPageSize();
758			$pagination = $system->getPageSize();
759		}
760
761		$events_db = events_get_events_grouped($sql_post,
762			$offset, $pagination, false, false);
763		if (empty($events_db)) {
764			$events_db = array();
765		}
766
767		$total_events = events_get_total_events_grouped($sql_post);
768
769		return array('events' => $events_db, 'total' => $total_events);
770	}
771
772	public function listEventsHtml($page = 0, $return = false, $id_table = 'list_events') {
773		$system = System::getInstance();
774		$ui = Ui::getInstance();
775
776		// Create an empty table to be filled from ajax
777		$table = new Table();
778		$table->id = $id_table;
779
780		$no_events = '<p id="empty_advice_events" class="empty_advice" style="display: none;">' . __('No events') . '</p>';
781
782		if (!$return) {
783			$ui->contentAddHtml($table->getHTML());
784
785			$ui->contentAddHtml('<div id="loading_rows">' .
786					html_print_image('images/spinner.gif', true) .
787					' ' . __('Loading...') .
788				'</div>' . $no_events);
789
790			$this->addJavascriptAddBottom();
791
792			$this->addJavascriptDialog();
793		}
794		else {
795			$this->addJavascriptAddBottom();
796
797			return array('table' => $table->getHTML() . $no_events);
798		}
799
800		$ui->contentAddLinkListener('list_events');
801	}
802
803	public function putEventsTableJS($id_agent) {
804		return "<script type=\"text/javascript\">
805					ajax_load_latest_agent_events(" . $id_agent . ", 10);
806				</script>";
807	}
808
809	public function addJavascriptDialog() {
810		$ui = Ui::getInstance();
811
812		$ui->contentAddHtml("
813			<script type=\"text/javascript\">
814				function openDetails(id_event) {
815					$.mobile.showPageLoadingMsg();
816
817					postvars = {};
818					postvars[\"action\"] = \"ajax\";
819					postvars[\"parameter1\"] = \"events\";
820					postvars[\"parameter2\"] = \"get_detail_event\";
821					postvars[\"id_event\"] = id_event;
822
823					$.ajax ({
824						type: \"POST\",
825						url: \"index.php\",
826						dataType: \"json\",
827						data: postvars,
828						success:
829							function (data) {
830								if (data.correct) {
831									event = data.event;
832
833									//Fill the dialog
834									$(\"#detail_event_dialog h1.dialog_title\")
835										.html(event[\"evento\"]);
836									$(\"#detail_event_dialog .cell_event_name\")
837										.html(event[\"evento\"]);
838									$(\"#detail_event_dialog .cell_event_id\")
839										.html(id_event);
840									$(\"#detail_event_dialog .cell_event_timestamp\")
841										.html(event[\"timestamp\"]);
842									$(\"#detail_event_dialog .cell_event_owner\")
843										.html(event[\"owner_user\"]);
844									$(\"#detail_event_dialog .cell_event_type\")
845										.html(event[\"event_type\"]);
846									$(\"#detail_event_dialog .cell_event_repeated\")
847										.html(event[\"event_repeated\"]);
848									$(\"#detail_event_dialog .cell_event_severity\")
849										.html(event[\"criticity\"]);
850									$(\"#detail_event_dialog .cell_event_status\")
851										.html(event[\"status\"]);
852									$(\"#detail_event_dialog .cell_event_acknowledged_by\")
853										.html(event[\"acknowledged_by\"]);
854									$(\"#detail_event_dialog .cell_event_group\")
855										.html(event[\"group\"]);
856									$(\"#detail_event_dialog .cell_event_tags\")
857										.html(event[\"tags\"]);
858									$(\"#detail_event_dialog .cell_event_comments\")
859
860.html(event[\"comments\"]);
861									$(\"#detail_event_dialog .cell_agent\")
862										.html(event[\"agent\"]);
863
864									//The link to module graph
865									$(\".cell_module_graph\").html(event[\"module_graph_link\"]);
866
867									$(\"#event_id\").val(id_event);
868
869									if (event[\"estado\"] != 1) {
870										$(\"#validate_button\").show();
871									}
872									else {
873										//The event is validated.
874										$(\"#validate_button\").hide();
875									}
876									$(\"#validate_button_loading\").hide();
877									$(\"#validate_button_fail\").hide();
878									$(\"#validate_button_correct\").hide();
879
880									$.mobile.hidePageLoadingMsg();
881
882									$(\"#detail_event_dialog_hook\").click();
883								}
884								else {
885									$.mobile.hidePageLoadingMsg();
886									$(\"#detail_event_dialog_error_hook\").click();
887								}
888							},
889						error:
890							function (jqXHR, textStatus, errorThrown) {
891								$.mobile.hidePageLoadingMsg();
892								$(\"#detail_event_dialog_error_hook\").click();
893							}
894						});
895				}
896
897
898				function validateEvent() {
899					id_event = $(\"#event_id\").val();
900
901					$(\"#validate_button\").hide();
902					$(\"#validate_button_loading\").show();
903
904					//Hide the button to close
905					$(\"#detail_event_dialog div.ui-header a.ui-btn-right\")
906						.hide();
907
908					postvars = {};
909					postvars[\"action\"] = \"ajax\";
910					postvars[\"parameter1\"] = \"events\";
911					postvars[\"parameter2\"] = \"validate_event\";
912					postvars[\"id_event\"] = id_event;
913
914					$.ajax ({
915						type: \"POST\",
916						url: \"index.php\",
917						dataType: \"json\",
918						data: postvars,
919						success:
920							function (data) {
921								$(\"#validate_button_loading\").hide();
922
923								if (data.correct) {
924									$(\"#validate_button_correct\").show();
925								}
926								else {
927									$(\"#validate_button_fail\").show();
928								}
929
930								$(\"#detail_event_dialog div.ui-header a.ui-btn-right\")
931									.show();
932							},
933						error:
934							function (jqXHR, textStatus, errorThrown) {
935								$(\"#validate_button_loading\").hide();
936								$(\"#validate_button_fail\").show();
937								$(\"#detail_event_dialog div.ui-header a.ui-btn-right\")
938									.show();
939							}
940						});
941				}
942			</script>");
943	}
944
945	private function addJavascriptAddBottom() {
946		$ui = Ui::getInstance();
947
948		$ui->contentAddHtml("<script type=\"text/javascript\">
949				var load_more_rows = 1;
950				var page = 0;
951				function add_rows(data, table_id) {
952					if (data.end) {
953						$(\"#loading_rows\").hide();
954					}
955					else {
956						var new_rows = \"\";
957						$.each(data.events, function(key, event) {
958							new_rows = \"<tr class='events \" + event[2] + \"'>\" +
959									\"<td class='cell_0'>\" +
960										event[0] +
961									\"</td>\" +
962									\"<td>\" + event[1] + \"</td>\" +
963								\"</tr>\" + new_rows;
964							});
965
966						$(\"table#\"+table_id+\" tbody\").append(new_rows);
967
968						load_more_rows = 1;
969						refresh_link_listener_list_events();
970					}
971				}
972
973				function ajax_load_rows() {
974					if (load_more_rows) {
975						load_more_rows = 0;
976
977						postvars = {};
978						postvars[\"action\"] = \"ajax\";
979						postvars[\"parameter1\"] = \"events\";
980						postvars[\"parameter2\"] = \"get_events\";
981						postvars[\"filter\"] = $(\"select[name='filter']\").val();
982						postvars[\"group\"] = $(\"select[name='group']\").val();
983						postvars[\"status\"] = $(\"select[name='status']\").val();
984						postvars[\"type\"] = $(\"select[name='type']\").val();
985						postvars[\"severity\"] = $(\"select[name='severity']\").val();
986						postvars[\"free_search\"] = $(\"input[name='free_search']\").val();
987						postvars[\"hours_old\"] = $(\"input[name='hours_old']\").val();
988						postvars[\"page\"] = page;
989						page++;
990
991						$.post(\"index.php\",
992							postvars,
993							function (data) {
994								add_rows(data, 'list_events');
995
996								if($('#list_events').offset() != undefined) {
997									//For large screens load the new events
998									//Check if the end of the event list tables is in the client limits
999									var table_end = $('#list_events').offset().top + $('#list_events').height();
1000									if (table_end < document.documentElement.clientHeight) {
1001										ajax_load_rows();
1002									}
1003								}
1004
1005								if (data.events.length == 0 && page == 1) {
1006									$('#empty_advice_events').show();
1007								}
1008							},
1009							\"json\");
1010					}
1011				}
1012
1013				function ajax_load_latest_agent_events(id_agent, limit) {
1014					postvars = {};
1015					postvars[\"action\"] = \"ajax\";
1016					postvars[\"parameter1\"] = \"events\";
1017					postvars[\"parameter2\"] = \"get_events\";
1018					postvars[\"agent_events\"] = \"1\";
1019					postvars[\"id_agent\"] = id_agent;
1020					postvars[\"limit\"] = limit;
1021
1022					$.post(\"index.php\",
1023						postvars,
1024						function (data) {
1025							add_rows(data, 'last_agent_events');
1026							if (data.events.length == 0) {
1027								$('#last_agent_events').css('visibility', 'hidden');
1028								$('#empty_advice_events').show();
1029							}
1030						},
1031						\"json\");
1032				}
1033
1034				$(document).ready(function() {
1035						ajax_load_rows();
1036
1037						$(window).bind(\"scroll\", function () {
1038							custom_scroll();
1039						});
1040
1041						$(window).on(\"touchmove\", function(event) {
1042							custom_scroll();
1043						});
1044				});
1045
1046				function custom_scroll() {
1047					if ($(this).scrollTop() + $(this).height()
1048							>= ($(document).height() - 100)) {
1049
1050							ajax_load_rows();
1051						}
1052				}
1053			</script>");
1054	}
1055
1056	private function filterEventsGetString() {
1057		global $system;
1058
1059		if ($this->default) {
1060			return __("(Default)");
1061		}
1062		else {
1063			if ($this->filter) {
1064				$filter = db_get_row('tevent_filter', 'id_filter', $this->filter);
1065
1066				return sprintf(__('Filter: %s'), $filter['id_name']);
1067			}
1068			else {
1069				$filters_to_serialize = array();
1070
1071				if($this->severity == -1) {
1072					$severity = __('All');
1073				}
1074				else {
1075					$severity = get_priorities($this->severity);
1076				}
1077
1078				if (!$this->default_filters['severity']) {
1079					$filters_to_serialize[] = sprintf(__("Severity: %s"),
1080						$severity);
1081				}
1082				if (!$this->default_filters['group']) {
1083					$groups = users_get_groups_for_select(
1084						$system->getConfig('id_user'), "ER", true, true, false, 'id_grupo');
1085
1086					$filters_to_serialize[] = sprintf(__("Group: %s"),
1087						$groups[$this->group]);
1088				}
1089
1090				if($this->type == 'all') {
1091					$type = __('All');
1092				}
1093				else {
1094					$type = get_event_types($this->type);
1095				}
1096
1097				if (!$this->default_filters['type']) {
1098					$filters_to_serialize[] = sprintf(__("Type: %s"),
1099						$type);
1100				}
1101				if (!$this->default_filters['status']) {
1102					$filters_to_serialize[] = sprintf(__("Status: %s"),
1103						events_get_status($this->status));
1104				}
1105				if (!$this->default_filters['free_search']) {
1106					$filters_to_serialize[] = sprintf(__("Free search: %s"),
1107						$this->free_search);
1108				}
1109				if (!$this->default_filters['hours_old']) {
1110					$filters_to_serialize[] = sprintf(__("Hours: %s"),
1111						$this->hours_old);
1112				}
1113
1114				$string = '(' . implode(' - ', $filters_to_serialize) . ')';
1115
1116				return $string;
1117			}
1118		}
1119	}
1120}
1121
1122?>
1123