From cfe16ee8c342564934bbba50c130bc0776450fd1 Mon Sep 17 00:00:00 2001
From: fbsanchez <fborja.sanchez@artica.es>
Date: Thu, 20 Jun 2019 11:46:01 +0200
Subject: [PATCH] minor fixes

---
 pandora_console/include/functions_events.php  | 141 +++++++-
 pandora_console/operation/events/events.php   |  39 ++-
 .../operation/events/export_csv.php           | 312 ++++++++++--------
 3 files changed, 331 insertions(+), 161 deletions(-)

diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php
index da2efa1bd1..a958a3a957 100644
--- a/pandora_console/include/functions_events.php
+++ b/pandora_console/include/functions_events.php
@@ -34,6 +34,143 @@ enterprise_include_once('meta/include/functions_agents_meta.php');
 enterprise_include_once('meta/include/functions_modules_meta.php');
 
 
+/**
+ * Translates a numeric value module_status into descriptive text.
+ *
+ * @param integer $status Module status.
+ *
+ * @return string Descriptive text.
+ */
+function events_translate_module_status($status)
+{
+    switch ($status) {
+        case AGENT_MODULE_STATUS_NORMAL:
+        return __('NORMAL');
+
+        case AGENT_MODULE_STATUS_CRITICAL_BAD:
+        return __('CRITICAL');
+
+        case AGENT_MODULE_STATUS_NO_DATA:
+        return __('NOT INIT');
+
+        case AGENT_MODULE_STATUS_CRITICAL_ALERT:
+        case AGENT_MODULE_STATUS_NORMAL_ALERT:
+        case AGENT_MODULE_STATUS_WARNING_ALERT:
+        return __('ALERT');
+
+        case AGENT_MODULE_STATUS_WARNING:
+        return __('WARNING');
+
+        default:
+        return __('UNKNOWN');
+    }
+}
+
+
+/**
+ * Translates a numeric value event_type into descriptive text.
+ *
+ * @param integer $event_type Event type.
+ *
+ * @return string Descriptive text.
+ */
+function events_translate_event_type($event_type)
+{
+    // Event type prepared.
+    switch ($event_type) {
+        case EVENTS_ALERT_FIRED:
+        case EVENTS_ALERT_RECOVERED:
+        case EVENTS_ALERT_CEASED:
+        case EVENTS_ALERT_MANUAL_VALIDATION:
+        return __('ALERT');
+
+        case EVENTS_RECON_HOST_DETECTED:
+        case EVENTS_SYSTEM:
+        case EVENTS_ERROR:
+        case EVENTS_NEW_AGENT:
+        case EVENTS_CONFIGURATION_CHANGE:
+        return __('SYSTEM');
+
+        case EVENTS_GOING_UP_WARNING:
+        case EVENTS_GOING_DOWN_WARNING:
+        return __('WARNING');
+
+        case EVENTS_GOING_DOWN_NORMAL:
+        case EVENTS_GOING_UP_NORMAL:
+        return __('NORMAL');
+
+        case EVENTS_GOING_DOWN_CRITICAL:
+        case EVENTS_GOING_UP_CRITICAL:
+        return __('CRITICAL');
+
+        case EVENTS_UNKNOWN:
+        case EVENTS_GOING_UNKNOWN:
+        default:
+        return __('UNKNOWN');
+    }
+}
+
+
+/**
+ * Translates a numeric value event_status into descriptive text.
+ *
+ * @param integer $status Event status.
+ *
+ * @return string Descriptive text.
+ */
+function events_translate_event_status($status)
+{
+    switch ($status) {
+        case EVENT_STATUS_NEW:
+        default:
+        return __('NEW');
+
+        case EVENT_STATUS_INPROCESS:
+        return __('IN PROCESS');
+
+        case EVENT_STATUS_VALIDATED:
+        return __('VALIDATED');
+    }
+}
+
+
+/**
+ * Translates a numeric value criticity into descriptive text.
+ *
+ * @param integer $criticity Event criticity.
+ *
+ * @return string Descriptive text.
+ */
+function events_translate_event_criticity($criticity)
+{
+    switch ($criticity) {
+        case EVENT_CRIT_CRITICAL:
+        return __('CRITICAL');
+
+        case EVENT_CRIT_MAINTENANCE:
+        return __('MAINTENANCE');
+
+        case EVENT_CRIT_INFORMATIONAL:
+        return __('INFORMATIONAL');
+
+        case EVENT_CRIT_MAJOR:
+        return __('MAJOR');
+
+        case EVENT_CRIT_MINOR:
+        return __('MINOR');
+
+        case EVENT_CRIT_NORMAL:
+        return __('NORMAL');
+
+        case EVENT_CRIT_WARNING:
+        return __('WARNING');
+
+        default:
+        return __('UNKNOWN');
+    }
+}
+
+
 /**
  * Return all header string for each event field.
  *
@@ -6465,10 +6602,6 @@ function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep=
  */
 function events_get_secondary_groups_left_join($table)
 {
-    if (users_is_admin()) {
-        return '';
-    }
-
     if ($table == 'tevento') {
         return 'LEFT JOIN tagent_secondary_group tasg ON te.id_agente = tasg.id_agent';
     }
diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php
index 400f3e9d6d..ec073082bf 100644
--- a/pandora_console/operation/events/events.php
+++ b/pandora_console/operation/events/events.php
@@ -1,7 +1,6 @@
 <?php
 /**
- * Extension to manage a list of gateways and the node address where they should
- * point to.
+ * Event list.
  *
  * @category   Events
  * @package    Pandora FMS
@@ -493,27 +492,27 @@ if ($pure) {
 
     // Fullscreen.
     $fullscreen['active'] = false;
-    $fullscreen['text'] = '<a class="events_link" href="'.$url.'&amp;pure=1">'.html_print_image('images/full_screen.png', true, ['title' => __('Full screen')]).'</a>';
+    $fullscreen['text'] = '<a class="events_link" href="'.$url.'&amp;pure=1&">'.html_print_image('images/full_screen.png', true, ['title' => __('Full screen')]).'</a>';
 
     // Event list.
     $list['active'] = false;
-    $list['text'] = '<a class="events_link" href="index.php?sec=eventos&sec2=operation/events/events&amp;pure='.$config['pure'].'">'.html_print_image('images/events_list.png', true, ['title' => __('Event list')]).'</a>';
+    $list['text'] = '<a class="events_link" href="index.php?sec=eventos&sec2=operation/events/events&amp;pure='.$config['pure'].'&">'.html_print_image('images/events_list.png', true, ['title' => __('Event list')]).'</a>';
 
     // History event list.
     $history_list['active'] = false;
-    $history_list['text'] = '<a class="events_link" href="index.php?sec=eventos&sec2=operation/events/events&amp;pure='.$config['pure'].'&amp;section=history&amp;history=1">'.html_print_image('images/books.png', true, ['title' => __('History event list')]).'</a>';
+    $history_list['text'] = '<a class="events_link" href="index.php?sec=eventos&sec2=operation/events/events&amp;pure='.$config['pure'].'&amp;section=history&amp;history=1&">'.html_print_image('images/books.png', true, ['title' => __('History event list')]).'</a>';
 
     // RSS.
     $rss['active'] = false;
-    $rss['text'] = '<a class="events_link" href="operation/events/events_rss.php?user='.$config['id_user'].'&hashup='.$hashup.'&'.$params.'">'.html_print_image('images/rss.png', true, ['title' => __('RSS Events')]).'</a>';
+    $rss['text'] = '<a class="events_link" href="operation/events/events_rss.php?user='.$config['id_user'].'&hashup='.$hashup.'&">'.html_print_image('images/rss.png', true, ['title' => __('RSS Events')]).'</a>';
 
     // Marquee.
     $marquee['active'] = false;
-    $marquee['text'] = '<a class="events_link" href="operation/events/events_marquee.php">'.html_print_image('images/heart.png', true, ['title' => __('Marquee display')]).'</a>';
+    $marquee['text'] = '<a class="events_link" href="operation/events/events_marquee.php?">'.html_print_image('images/heart.png', true, ['title' => __('Marquee display')]).'</a>';
 
     // CSV.
     $csv['active'] = false;
-    $csv['text'] = '<a class="events_link" href="operation/events/export_csv.php?fb64='.$filter_b64.'">'.html_print_image('images/csv_mc.png', true, ['title' => __('Export to CSV file')]).'</a>';
+    $csv['text'] = '<a class="events_link" href="operation/events/export_csv.php?'.$filter_b64.'">'.html_print_image('images/csv_mc.png', true, ['title' => __('Export to CSV file')]).'</a>';
 
     // Sound events.
     $sound_event['active'] = false;
@@ -1225,6 +1224,7 @@ try {
     $active_filters_div .= '</div>';
 
     $table_id = 'events';
+    $form_id = 'events_form';
 
     // Print datatable.
     ui_print_datatable(
@@ -1238,7 +1238,7 @@ try {
                 'history'    => (int) $history,
             ],
             'form'                => [
-                'id'            => 'events_form',
+                'id'            => $form_id,
                 'class'         => 'flex-row',
                 'html'          => $filter,
                 'inputs'        => [],
@@ -1528,7 +1528,7 @@ function process_datatables_item(item) {
 
         case "<?php echo EVENTS_GOING_UP_WARNING; ?>":
         case "<?php echo EVENTS_GOING_DOWN_WARNING; ?>":
-        $tex = "<?php echo __('WARNING'); ?>";
+            text = "<?php echo __('WARNING'); ?>";
             color = "<?php echo COL_WARNING; ?>";
         break;
 
@@ -1654,15 +1654,15 @@ function process_datatables_item(item) {
     /* Status */
     img = '<?php echo html_print_image('images/star.png', true, ['title' => __('Unknown'), 'class' => 'forced-title']); ?>';
     switch (item.estado) {
-        case "0":
+        case "<?php echo EVENT_STATUS_NEW; ?>":
             img = '<?php echo html_print_image('images/star.png', true, ['title' => __('New event'), 'class' => 'forced-title']); ?>';
         break;
 
-        case "1":
+        case "<?php echo EVENT_STATUS_VALIDATED; ?>":
             img = '<?php echo html_print_image('images/tick.png', true, [ 'title' => __('Event validated'), 'class' => 'forced-title']); ?>';
         break;
 
-        case "2":
+        case "<?php echo EVENT_STATUS_INPROCESS; ?>":
             img = '<?php echo html_print_image('images/hourglass.png', true, [ 'title' => __('Event in process'), 'class' => 'forced-title']); ?>';
         break;
     }
@@ -1968,16 +1968,21 @@ function reorder_tags_inputs() {
 }
 /* Tag management ends */
 $(document).ready( function() {
-
     /* Filter to a href */
     $('.events_link').on('click', function(e) {
         e.preventDefault();
 
-        console.log(e.currentTarget);
-
-        
+        inputs = $("#<?php echo $form_id; ?> :input");
+        values = {};
+        inputs.each(function() {
+            values[this.name] = $(this).val();
+        })
 
+        values['history'] = "<?php echo (int) $history; ?>";
 
+        var url = e.currentTarget.href;
+        url += 'fb64=' + btoa(JSON.stringify(values));
+        document.location = url;
 
     });
 
diff --git a/pandora_console/operation/events/export_csv.php b/pandora_console/operation/events/export_csv.php
index be0bb52b71..0c16a16f9d 100644
--- a/pandora_console/operation/events/export_csv.php
+++ b/pandora_console/operation/events/export_csv.php
@@ -1,18 +1,34 @@
 <?php
+/**
+ * Event CSV exporter.
+ *
+ * @category   Event CSV export
+ * @package    Pandora FMS
+ * @subpackage Community
+ * @version    1.0.0
+ * @license    See below
+ *
+ *    ______                 ___                    _______ _______ ________
+ *   |   __ \.-----.--.--.--|  |.-----.----.-----. |    ___|   |   |     __|
+ *  |    __/|  _  |     |  _  ||  _  |   _|  _  | |    ___|       |__     |
+ * |___|   |___._|__|__|_____||_____|__| |___._| |___|   |__|_|__|_______|
+ *
+ * ============================================================================
+ * Copyright (c) 2005-2019 Artica Soluciones Tecnologicas
+ * Please see http://pandorafms.org for full contribution list
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation for version 2.
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * ============================================================================
+ */
+
+// Load global vars.
+global $config;
 
-// Pandora FMS - http://pandorafms.com
-// ==================================================
-// Copyright (c) 2005-2009 Artica Soluciones Tecnologicas
-// Please see http://pandorafms.org for full contribution list
-// This program is free software; you can redistribute it and/or
-// modify it under the terms of the GNU General Public License
-// as published by the Free Software Foundation for version 2.
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-// Don't start a session before this import.
-// The session is configured and started inside the config process.
 require_once '../../include/config.php';
 require_once '../../include/auth/mysql.php';
 require_once '../../include/functions.php';
@@ -23,149 +39,165 @@ require_once '../../include/functions_groups.php';
 
 $config['id_user'] = $_SESSION['id_usuario'];
 
-if (! check_acl($config['id_user'], 0, 'ER') && ! check_acl($config['id_user'], 0, 'EW') && ! check_acl($config['id_user'], 0, 'EM')) {
+if (! check_acl($config['id_user'], 0, 'ER')
+    && ! check_acl($config['id_user'], 0, 'EW')
+    && ! check_acl($config['id_user'], 0, 'EM')
+) {
     exit;
 }
 
-hd($_REQUEST);
-
-$fb64 = get_parameter('fb64', '');
-
-
-try {
-    $filter = json_decode(base64_decode($fb64), true);
-} catch (Exception $e) {
-    echo $e;
-    exit;
-}
-
-hd($filter);
-
-die();
-global $config;
-
-// loading l10n tables, because of being invoked not through index.php.
+// Loading l10n tables, because of being invoked not through index.php.
 $l10n = null;
 if (file_exists($config['homedir'].'/include/languages/'.$user_language.'.mo')) {
-    $l10n = new gettext_reader(new CachedFileReader($config['homedir'].'/include/languages/'.$user_language.'.mo'));
+    $cfr = new CachedFileReader(
+        $config['homedir'].'/include/languages/'.$user_language.'.mo'
+    );
+    $l10n = new gettext_reader($cfr);
     $l10n->load_tables();
 }
 
-$offset = (int) get_parameter('offset');
-$id_group = (int) get_parameter('id_group');
-// group
-$event_type = (string) get_parameter('event_type', 'all');
-// 0 all
-$severity = (int) get_parameter('severity', -1);
-// -1 all
-$status = (int) get_parameter('status', -1);
-// -1 all, 0 only red, 1 only green
-$id_agent = (int) get_parameter('id_agent', -1);
+$column_names = [
+    'id_evento',
+    'evento',
+    'timestamp',
+    'estado',
+    'event_type',
+    'utimestamp',
+    'id_agente',
+    'agent_name',
+    'id_usuario',
+    'id_grupo',
+    'id_agentmodule',
+    'id_alert_am',
+    'criticity',
+    'user_comment',
+    'tags',
+    'source',
+    'id_extra',
+    'critical_instructions',
+    'warning_instructions',
+    'unknown_instructions',
+    'owner_user',
+    'ack_utimestamp',
+    'custom_data',
+    'data',
+    'module_status',
+];
 
-$id_event = (int) get_parameter('id_event', -1);
-$event_view_hr = (int) get_parameter('event_view_hr', $config['event_view_hr']);
-$id_user_ack = get_parameter('id_user_ack', 0);
-$search = io_safe_output(preg_replace('/&([A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', rawurldecode(get_parameter('search'))));
-$text_agent = (string) get_parameter('text_agent', __('All'));
-
-$tag_with_json = base64_decode(get_parameter('tag_with', ''));
-$tag_with_json_clean = io_safe_output($tag_with_json);
-$tag_with_base64 = base64_encode($tag_with_json_clean);
-$tag_with = json_decode($tag_with_json_clean, true);
-if (empty($tag_with)) {
-    $tag_with = [];
-}
-
-$tag_with = array_diff($tag_with, [0 => 0]);
-
-$tag_without_json = base64_decode(get_parameter('tag_without', ''));
-$tag_without_json_clean = io_safe_output($tag_without_json);
-$tag_without_base64 = base64_encode($tag_without_json_clean);
-$tag_without = json_decode($tag_without_json_clean, true);
-if (empty($tag_without)) {
-    $tag_without = [];
-}
-
-$tag_without = array_diff($tag_without, [0 => 0]);
-
-$filter_only_alert = (int) get_parameter('filter_only_alert', -1);
-
-//
-// Build the condition of the events query
-$sql_post = '';
-$meta = false;
-
-$id_user = $config['id_user'];
-
-require 'events.build_query.php';
-
-// Now $sql_post have all the where condition
-//
-switch ($config['dbtype']) {
-    case 'mysql':
-    case 'postgresql':
-    case 'oracle':
-        $sql = 'SELECT *
-			FROM tevento te
-			LEFT JOIN tagent_secondary_group tasg
-				ON te.id_grupo = tasg.id_group
-			WHERE 1=1 '.$sql_post.'
-			ORDER BY utimestamp DESC';
-    break;
-}
+$fields = [
+    'te.id_evento',
+    'te.evento',
+    'te.timestamp',
+    'te.estado',
+    'te.event_type',
+    'te.utimestamp',
+    'te.id_agente',
+    'ta.alias as agent_name',
+    'te.id_usuario',
+    'te.id_grupo',
+    'te.id_agentmodule',
+    'am.nombre as module_name',
+    'te.id_alert_am',
+    'te.criticity',
+    'te.user_comment',
+    'te.tags',
+    'te.source',
+    'te.id_extra',
+    'te.critical_instructions',
+    'te.warning_instructions',
+    'te.unknown_instructions',
+    'te.owner_user',
+    'te.ack_utimestamp',
+    'te.custom_data',
+    'te.data',
+    'te.module_status',
+    'tg.nombre as group_name',
+];
 
 $now = date('Y-m-d');
 
-// Show contentype header
+// Download header.
 header('Content-type: text/txt');
 header('Content-Disposition: attachment; filename="pandora_export_event'.$now.'.csv"');
 
-echo 'timestamp';
-echo $config['csv_divider'];
-echo 'agent';
-echo $config['csv_divider'];
-echo 'group';
-echo $config['csv_divider'];
-echo 'event';
-echo $config['csv_divider'];
-echo 'status';
-echo $config['csv_divider'];
-echo 'user';
-echo $config['csv_divider'];
-echo 'event_type';
-echo $config['csv_divider'];
-echo 'severity';
-echo $config['csv_divider'];
-echo 'id';
-echo chr(13);
-
-$new = true;
-while ($event = db_get_all_row_by_steps_sql($new, $result, $sql)) {
-    $new = false;
-    $alias = db_get_value('alias', 'tagente', 'id_agente', $event['id_agente']);
-    if ((!check_acl($config['id_user'], $event['id_grupo'], 'ER')
-        && !check_acl($config['id_user'], $event['id_grupo'], 'EW') && !check_acl($config['id_user'], $event['id_grupo'], 'EM') )
-        || (!check_acl($config['id_user'], 0, 'PM') && $event['event_type'] == 'system')
-    ) {
-        continue;
+try {
+    $fb64 = get_parameter('fb64', null);
+    $plain_filter = base64_decode($fb64);
+    $filter = json_decode($plain_filter, true);
+    if (json_last_error() != JSON_ERROR_NONE) {
+        throw new Exception('Invalid filter. ['.$plain_filter.']');
+    }
+
+    $names = events_get_column_names($column_names);
+
+    // Dump headers.
+    foreach ($names as $n) {
+        echo io_safe_output($n).$config['csv_divider'];
     }
 
-    echo date($config['date_format'], $event['utimestamp']);
-    echo $config['csv_divider'];
-    echo io_safe_output($alias);
-    echo $config['csv_divider'];
-    echo io_safe_output(groups_get_name($event['id_grupo']));
-    echo $config['csv_divider'];
-    echo io_safe_output($event['evento']);
-    echo $config['csv_divider'];
-    echo io_safe_output($event['estado']);
-    echo $config['csv_divider'];
-    echo io_safe_output($event['id_usuario']);
-    echo $config['csv_divider'];
-    echo io_safe_output($event['event_type']);
-    echo $config['csv_divider'];
-    echo $event['criticity'];
-    echo $config['csv_divider'];
-    echo $event['id_evento'];
     echo chr(13);
+
+    // Dump events.
+    $events_per_step = 1000;
+    $step = 0;
+    while (1) {
+        $events = events_get_all(
+            $fields,
+            $filter,
+            (($step++) * $events_per_step),
+            $events_per_step,
+            'desc',
+            'timestamp',
+            $filter['history']
+        );
+
+        if ($events === false) {
+            break;
+        }
+
+        foreach ($events as $row) {
+            foreach ($column_names as $val) {
+                $key = $val;
+                if ($val == 'id_grupo') {
+                    $key = 'group_name';
+                } else if ($val == 'id_agentmodule') {
+                    $key = 'module_name';
+                }
+
+                switch ($key) {
+                    case 'module_status':
+                        echo events_translate_module_status(
+                            $row[$key]
+                        );
+                    break;
+
+                    case 'event_type':
+                        echo events_translate_event_type(
+                            $row[$key]
+                        );
+                    break;
+
+                    case 'criticity':
+                        echo events_translate_event_criticity(
+                            $row[$key]
+                        );
+                    break;
+
+                    default:
+                        echo io_safe_output($row[$key]);
+                    break;
+                }
+
+                echo $config['csv_divider'];
+            }
+
+            echo chr(13);
+        }
+    }
+} catch (Exception $e) {
+    echo 'ERROR'.chr(13);
+    echo $e->getMessage();
+    exit;
 }
+
+exit;