static function cronCleanlogs()
 {
     global $DB;
     $pmLog = new PluginMonitoringLog();
     $pmConfig = new PluginMonitoringConfig();
     $id_restart = 0;
     $a_restarts = $pmLog->find("`action`='restart'", "`id` DESC", 1);
     if (count($a_restarts) > 0) {
         $a_restart = current($a_restarts);
         $id_restart = $a_restart['id'];
     }
     $id_reload = 0;
     $a_reloads = $pmLog->find("`action`='reload'", "`id` DESC", 1);
     if (count($a_reloads) > 0) {
         $a_reload = current($a_reloads);
         $id_reload = $a_reload['id'];
     }
     $pmConfig->getFromDB(1);
     $secs = $pmConfig->fields['logretention'] * DAY_TIMESTAMP;
     $query = "DELETE FROM `" . $pmLog->getTable() . "`\n         WHERE UNIX_TIMESTAMP(date_mod) < UNIX_TIMESTAMP()-{$secs}";
     if ($id_restart > 0 || $id_reload > 0) {
         // Keep last reload or restart command
         $id_restart = max($id_restart, $id_reload);
         $query .= " AND `id` < '" . $id_restart . "'";
     }
     $DB->query($query);
     // TODO: Delete serviceevents table content ???
     $query = "DELETE FROM `glpi_plugin_monitoring_serviceevents`\n         WHERE UNIX_TIMESTAMP(date) < UNIX_TIMESTAMP()-{$secs}";
     $DB->query($query);
     return true;
 }
Пример #2
0
 static function cronCleanlogs()
 {
     global $DB;
     $pmLog = new PluginMonitoringLog();
     $pmConfig = new PluginMonitoringConfig();
     $id_restart = 0;
     $a_restarts = $pmLog->find("`action`='restart'", "`id` DESC", 1);
     if (count($a_restarts) > 0) {
         $a_restart = current($a_restarts);
         $id_restart = $a_restart['id'];
     }
     $pmConfig->getFromDB(1);
     $secs = $pmConfig->fields['logretention'] * DAY_TIMESTAMP;
     $query = "DELETE FROM `" . $pmLog->getTable() . "`\n         WHERE UNIX_TIMESTAMP(date_mod) < UNIX_TIMESTAMP()-{$secs}";
     if ($id_restart > 0) {
         $query .= " AND `id` < '" . $id_restart . "'";
     }
     $DB->query($query);
     // Clean too events
     PluginMonitoringServiceevent::cronUpdaterrd();
     $pmUnavaibility = new PluginMonitoringUnavaibility();
     $pmUnavaibility->runUnavaibility();
     $query = "DELETE FROM `glpi_plugin_monitoring_serviceevents`\n         WHERE UNIX_TIMESTAMP(date) < UNIX_TIMESTAMP()-{$secs}";
     $DB->query($query);
     return true;
 }
Пример #3
0
  @since     2011

  ------------------------------------------------------------------------
*/
define('GLPI_ROOT', '../../..');
include GLPI_ROOT . "/inc/includes.php";
PluginMonitoringProfile::checkRight("config", "w");
commonHeader($LANG['plugin_monitoring']['title'][0], $_SERVER["PHP_SELF"], "plugins", "monitoring", "config");
$pmConfig = new PluginMonitoringConfig();
if (isset($_POST["update"])) {
    $pmConfig->update($_POST);
    glpi_header($_SERVER['HTTP_REFERER']);
} else {
    if (isset($_POST['timezones_add'])) {
        $input = array();
        $pmConfig->getFromDB($_POST['id']);
        $input['id'] = $_POST['id'];
        $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
        foreach ($_POST['timezones_to_add'] as $timezone) {
            $a_timezones[] = $timezone;
        }
        $input['timezones'] = exportArrayToDB($a_timezones);
        $pmConfig->update($input);
        glpi_header($_SERVER['HTTP_REFERER']);
    } else {
        if (isset($_POST['timezones_delete'])) {
            $input = array();
            $pmConfig->getFromDB($_POST['id']);
            $input['id'] = $_POST['id'];
            $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
            foreach ($_POST['timezones_to_delete'] as $timezone) {
Пример #4
0
 function displayGraphs($itemtype, $items_id)
 {
     global $CFG_GLPI;
     $pmComponent = new PluginMonitoringComponent();
     $pmConfig = new PluginMonitoringConfig();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $item = new $itemtype();
     $item->getFromDB($items_id);
     $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
     if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
         PluginMonitoringServicegraph::loadPreferences($pmComponent->fields['id']);
     }
     $css_width = '950';
     if (isset($_GET['mobile'])) {
         $css_width = '300';
     }
     echo "<table class='tab_cadre' width='" . $css_width . "'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     $title = Dropdown::getDropdownName(getTableForItemType('PluginMonitoringComponent'), $item->fields['plugin_monitoring_components_id']);
     $title .= ' ' . __('on', 'monitoring') . ' ';
     $pmComponentscatalog_Host->getFromDB($item->fields["plugin_monitoring_componentscatalogs_hosts_id"]);
     if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
         $itemtype2 = $pmComponentscatalog_Host->fields['itemtype'];
         $item2 = new $itemtype2();
         $item2->getFromDB($pmComponentscatalog_Host->fields['items_id']);
         $title .= str_replace("'", "\"", $item2->getLink() . " (" . $item2->getTypeName() . ")");
     }
     echo $title;
     echo "</th>";
     echo "<th width='200'>";
     if (!isset($_GET['mobile'])) {
         echo "<form method='post'>";
         $a_timezones = PluginMonitoringConfig::getTimezones();
         if (!isset($_SESSION['plugin_monitoring_timezone'])) {
             $_SESSION['plugin_monitoring_timezone'] = '0';
         }
         $a_timezones_allowed = array();
         $pmConfig->getFromDB(1);
         $a_temp = importArrayFromDB($pmConfig->fields['timezones']);
         foreach ($a_temp as $key) {
             $a_timezones_allowed[$key] = $a_timezones[$key];
         }
         if (count($a_timezones_allowed) == '0') {
             $a_timezones_allowed['0'] = $a_timezones['0'];
         }
         Dropdown::showFromArray('plugin_monitoring_timezone', $a_timezones_allowed, array('value' => $_SESSION['plugin_monitoring_timezone']));
         echo "&nbsp;<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>";
         Html::closeForm();
     }
     echo "</th>";
     echo "</tr>";
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if (!isset($_GET['mobile'])) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo "<div id='legendlink'><a onClick='Ext.get(\"options\").toggle();'>[ Options ]</a></div>";
         echo "</th>";
         echo "</tr>";
         // * Display perfname
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         echo "<div id='options' style='display:none'>";
         PluginMonitoringServicegraph::preferences($pmComponent->fields['id'], 0);
         echo "</div>";
         echo "</td>";
         echo "</tr>";
         // * Display date slider
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo __('Select date (only last 2, 12 and 24 hours)', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         $end = time();
         $oldvalue = current(getAllDatasFromTable('glpi_plugin_monitoring_serviceevents', "`plugin_monitoring_services_id`='" . $items_id . "'", false, 'date ASC LIMIT 1'));
         $date = new DateTime($oldvalue['date']);
         $start = $date->getTimestamp();
         $pmServicegraph = new PluginMonitoringServicegraph();
         echo "\n<script type=\"text/javascript\">\n\nExt.onReady(function(){\n\n    var tip = new Ext.slider.Tip({\n        getText: function(thumb){\n            return String.format('<b> ' + new Date(thumb.value * 1000).format('Y-m-d') + '</b>');\n        }\n    });\n\n    new Ext.Slider({\n        renderTo: 'custom-tip-slider',\n        width: 940,\n        increment: 86400,\n        minValue: " . $start . ",\n        maxValue: " . $end . ",\n        value: " . $end . ",\n        plugins: tip,\n        listeners: {\n            dragend: function(slider, thumb, value){\n               document.getElementById('custom_date').textContent = slider.getValue();\n               mgr" . $items_id . "2h.stopAutoRefresh();\n               mgr" . $items_id . "12h.stopAutoRefresh();\n               mgr" . $items_id . "1d.stopAutoRefresh();\n                  ";
         $a_graphlist = array('2h', '12h', '1d');
         foreach ($a_graphlist as $time) {
             $pmServicegraph->startAutoRefresh($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $pmComponent->fields['id']);
         }
         echo "\n            }\n        }\n    });\n\n});\n</script>";
         echo '<center><div id="custom-tip-slider"></div></center>';
         echo '<div id="custom_date" style="display:none"></div>';
         echo "</td>";
         echo "</tr>";
         // * Display time slider
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo __('Select time (only last 2, 12 and 24 hours)', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         $start = 0 + 86400 - 3600;
         $end = 86400 + 86400 - 3600 - 300;
         $current = mktime(date('H'), date('i'), 0, 1, 2, 1970);
         echo "\n<script type=\"text/javascript\">\n\nExt.onReady(function(){\n\n    var tiptime = new Ext.slider.Tip({\n        getText: function(thumb){\n            return String.format('<b> ' + new Date(thumb.value * 1000).format('H:i:s') + '</b>');\n        }\n    });\n\n    new Ext.Slider({\n        renderTo: 'custom-tip-slider-time',\n        width: 940,\n        increment: 300,\n        minValue: " . $start . ",\n        maxValue: " . $end . ",\n        value: " . $current . ",\n        plugins: tiptime,\n        listeners: {\n            dragend: function(slider, thumb, value){\n               document.getElementById('custom_time').textContent = slider.getValue();\n               mgr" . $items_id . "2h.stopAutoRefresh();\n               mgr" . $items_id . "12h.stopAutoRefresh();\n               mgr" . $items_id . "1d.stopAutoRefresh();\n                  ";
         $a_graphlist = array('2h', '12h', '1d');
         foreach ($a_graphlist as $time) {
             $pmServicegraph->startAutoRefresh($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $pmComponent->fields['id']);
         }
         echo "\n            }\n        }\n    });\n});\n</script>";
         echo '<center><div id="custom-tip-slider-time"></div></center>';
         echo '<div id="custom_time" style="display:none"></div>';
         echo "</td>";
         echo "</tr>";
     }
     $a_list = array();
     $a_list["2h"] = __("Last 2 hours", "monitoring");
     $a_list["12h"] = __("Last 12 hours", "monitoring");
     $a_list["1d"] = __("Last 24 hours", "monitoring");
     if (!isset($_GET['mobile'])) {
         $a_list["1w"] = __("Last 7 days (average)", "monitoring");
         $a_list["1m"] = __("Last month (average)", "monitoring");
         $a_list["0y6m"] = __("Last 6 months (average)", "monitoring");
         $a_list["1y"] = __("Last year (average)", "monitoring");
     }
     foreach ($a_list as $time => $name) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo $name;
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center' colspan='2'>";
         $pmServicegraph = new PluginMonitoringServicegraph();
         $part = '';
         $width = '950';
         if (isset($_GET['mobile'])) {
             $width = '294';
         }
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $part, $width);
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
 function displayGraphs($itemtype, $items_id)
 {
     global $CFG_GLPI;
     $pmComponent = new PluginMonitoringComponent();
     $pmConfig = new PluginMonitoringConfig();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $networkPort = new NetworkPort();
     $item = new $itemtype();
     $item->getFromDB($items_id);
     $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
     if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
         PluginMonitoringToolbox::loadPreferences($pmComponent->fields['id']);
     }
     $css_width = '950';
     if (isset($_GET['mobile'])) {
         $css_width = '300';
     }
     echo "<table class='tab_cadre' width='" . $css_width . "'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     $title = Dropdown::getDropdownName(getTableForItemType('PluginMonitoringComponent'), $item->fields['plugin_monitoring_components_id']);
     if (!is_null($item->fields['networkports_id']) && $item->fields['networkports_id'] > 0) {
         $networkPort->getFromDB($item->fields['networkports_id']);
         $title .= " [" . $networkPort->getLink() . "]";
     }
     $title .= ' ' . __('on', 'monitoring') . ' ';
     $pmComponentscatalog_Host->getFromDB($item->fields["plugin_monitoring_componentscatalogs_hosts_id"]);
     if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
         $itemtype2 = $pmComponentscatalog_Host->fields['itemtype'];
         $item2 = new $itemtype2();
         $item2->getFromDB($pmComponentscatalog_Host->fields['items_id']);
         $title .= str_replace("'", "\"", $item2->getLink() . " (" . $item2->getTypeName() . ")");
     }
     echo $title;
     echo "</th>";
     echo "<th width='200'>";
     if (!isset($_GET['mobile'])) {
         echo "<form method='post'>";
         $a_timezones = PluginMonitoringConfig::getTimezones();
         if (!isset($_SESSION['plugin_monitoring_timezone'])) {
             $_SESSION['plugin_monitoring_timezone'] = '0';
         }
         $a_timezones_allowed = array();
         $pmConfig->getFromDB(1);
         $a_temp = importArrayFromDB($pmConfig->fields['timezones']);
         foreach ($a_temp as $key) {
             $a_timezones_allowed[$key] = $a_timezones[$key];
         }
         if (count($a_timezones_allowed) == '0') {
             $a_timezones_allowed['0'] = $a_timezones['0'];
         }
         Dropdown::showFromArray('plugin_monitoring_timezone', $a_timezones_allowed, array('value' => $_SESSION['plugin_monitoring_timezone']));
         echo "&nbsp;<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>";
         Html::closeForm();
     }
     echo "</th>";
     echo "</tr>";
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if (!isset($_GET['mobile'])) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo "<div id='legendlink'><a onClick='\$(\"#options\").toggle();'>[ Options ]</a></div>";
         echo "</th>";
         echo "</tr>";
         // * Display perfname
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         echo "<div id='options' style='display:none'>";
         PluginMonitoringToolbox::preferences($pmComponent->fields['id'], 0);
         echo "</div>";
         echo "</td>";
         echo "</tr>";
         // * Display date slider
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo __('Select date', 'monitoring') . " - " . __('Select time', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         $start = time();
         $oldvalue = current(getAllDatasFromTable('glpi_plugin_monitoring_serviceevents', "`plugin_monitoring_services_id`='" . $items_id . "'", false, 'date ASC LIMIT 1'));
         $date = new DateTime($oldvalue['date']);
         if ($date->getTimestamp() < $start) {
             $start = $date->getTimestamp();
         }
         $nbdays = round((date('U') - $start) / 86400);
         echo "<script type=\"text/javascript\">\n            \$(function() {\n                \$( \"#custom_date\" ).datepicker({ minDate: -" . $nbdays . ", maxDate: \"+0D\", dateFormat:'mm/dd/yy' });\n                \$( \"#custom_time\" ).timepicker();\n\n            });\n         </script>";
         echo '<center><input type="text" id="custom_date" value="' . date('m/d/Y') . '"> ' . ' <input type="text" id="custom_time" value="' . date('H:i') . '"></center>';
         echo "</th>";
         echo "</tr>";
     }
     $a_list = array();
     $a_list["2h"] = __("Last 2 hours", "monitoring");
     $a_list["12h"] = __("Last 12 hours", "monitoring");
     $a_list["1d"] = __("Last 24 hours", "monitoring");
     $a_list["1w"] = __("Last 7 days (average)", "monitoring");
     //      $a_list["1m"]     = __("Last month (average)", "monitoring");
     //      $a_list["0y6m"]   = __("Last 6 months (average)", "monitoring");
     //      $a_list["1y"]     = __("Last year (average)", "monitoring");
     foreach ($a_list as $time => $name) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo $name;
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center' colspan='2' style='position: relative'>";
         $pmServicegraph = new PluginMonitoringServicegraph();
         $part = '';
         $width = '950';
         if (isset($_GET['mobile'])) {
             $width = '294';
         }
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $part, $width);
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
Пример #6
0
 function displayGraphs($itemtype, $items_id)
 {
     global $CFG_GLPI, $LANG;
     $pmComponent = new PluginMonitoringComponent();
     $pmConfig = new PluginMonitoringConfig();
     $item = new $itemtype();
     $item->getFromDB($items_id);
     $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     echo $item->getLink(1);
     echo "</th>";
     echo "<th width='200'>";
     echo "<form method='post'>";
     $a_timezones = PluginMonitoringConfig::getTimezones();
     if (!isset($_SESSION['plugin_monitoring_timezone'])) {
         $_SESSION['plugin_monitoring_timezone'] = '0';
     }
     $a_timezones_allowed = array();
     $pmConfig->getFromDB(1);
     $a_temp = importArrayFromDB($pmConfig->fields['timezones']);
     foreach ($a_temp as $key) {
         $a_timezones_allowed[$key] = $a_timezones[$key];
     }
     if (count($a_timezones_allowed) == '0') {
         $a_timezones_allowed['0'] = $a_timezones['0'];
     }
     Dropdown::showFromArray('plugin_monitoring_timezone', $a_timezones_allowed, array('value' => $_SESSION['plugin_monitoring_timezone']));
     echo "&nbsp;<input type='submit' name='update' value=\"" . $LANG['buttons'][7] . "\" class='submit'>";
     echo "</form>";
     echo "</th>";
     echo "</tr>";
     $a_list = array();
     $a_list[] = "2h";
     $a_list[] = "12h";
     $a_list[] = "1d";
     $a_list[] = "1w";
     $a_list[] = "1m";
     $a_list[] = "0y6m";
     $a_list[] = "1y";
     foreach ($a_list as $time) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo $time;
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center' colspan='2'>";
         $img = '';
         $timezone = '0';
         if (isset($_SESSION['plugin_monitoring_timezone'])) {
             $timezone = $_SESSION['plugin_monitoring_timezone'];
         }
         $timezone_file = str_replace("+", ".", $timezone);
         $pmServicegraph = new PluginMonitoringServicegraph();
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time);
         $img = "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/send.php?file=" . $itemtype . "-" . $items_id . "-" . $time . $timezone_file . ".png'/>";
         echo $img;
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
Пример #7
0
 static function getPHPPath()
 {
     $pmConfig = new PluginMonitoringConfig();
     $pmConfig->getFromDB("1");
     return $pmConfig->getField("phppath");
 }
 /**
  * Get host name for a service
  */
 function getHostName()
 {
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmConfig = new PluginMonitoringConfig();
     $pmConfig->getFromDB(1);
     $pmComponentscatalog_Host->getFromDB($this->fields['plugin_monitoring_componentscatalogs_hosts_id']);
     $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
     $item = new $itemtype();
     if ($item->getFromDB($pmComponentscatalog_Host->fields['items_id'])) {
         if ($pmConfig->fields['append_id_hostname'] == 1) {
             return $item->fields['name'] . "-" . $item->fields['id'];
         }
         return $item->fields['name'];
     }
     return '';
 }
 /**
  * Log when extra-debug is activated
  */
 static function logIfExtradebug($file, $message)
 {
     $config = new PluginMonitoringConfig();
     $config->getFromDB(1);
     if ($config->fields['extradebug']) {
         if (is_array($message)) {
             $message = print_r($message, TRUE);
         }
         Toolbox::logInFile($file, $message);
     }
 }
 function generateServicesCfg($file = 0, $tag = '')
 {
     global $DB;
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Starting generateServicesCfg services ({$tag}) ...\n");
     $pMonitoringCommand = new PluginMonitoringCommand();
     $pmEventhandler = new PluginMonitoringEventhandler();
     $pMonitoringCheck = new PluginMonitoringCheck();
     $pmComponent = new PluginMonitoringComponent();
     $pmEntity = new PluginMonitoringEntity();
     $pmContact_Item = new PluginMonitoringContact_Item();
     $networkPort = new NetworkPort();
     $pmService = new PluginMonitoringService();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $pmHostconfig = new PluginMonitoringHostconfig();
     $calendar = new Calendar();
     $user = new User();
     $profile_User = new Profile_User();
     $pmConfig = new PluginMonitoringConfig();
     $computerType = new ComputerType();
     $a_services = array();
     $i = 0;
     // Get computer type contener / VM
     $conteners = $computerType->find("`name`='BSDJail'");
     $pmConfig->getFromDB(1);
     // TODO: only contacts in allowed entities ...
     // Prepare individual contacts
     $a_contacts_entities = array();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n         AND `users_id`>0");
     foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
             $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
     }
     // Prepare groups contacts
     $group = new Group();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n         AND `groups_id`>0");
     foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
             $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
             $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $queryg = "SELECT * FROM `glpi_groups_users`\n            WHERE `groups_id`='" . $data['groups_id'] . "'";
         $resultg = $DB->query($queryg);
         while ($datag = $DB->fetch_array($resultg)) {
             if (isset($a_contacts_entities[$data['items_id']][$datag['users_id']])) {
                 $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
             }
             $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
     }
     $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
     // Toolbox::logInFile("pm-shinken", " Allowed entities:\n");
     $a_entities_list = array();
     foreach ($a_entities_allowed as $entity) {
         $a_entities_list = getSonsOf("glpi_entities", $entity);
     }
     $where = '';
     if (!isset($a_entities_allowed['-1'])) {
         $where = getEntitiesRestrictRequest("WHERE", "glpi_plugin_monitoring_services", '', $a_entities_list);
     }
     // --------------------------------------------------
     // "Normal" services ....
     $query = "SELECT * FROM `glpi_plugin_monitoring_services` {$where}";
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Services: {$query}\n");
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         // Toolbox::logInFile("pm-shinken", " - fetch service ".$data['id']."\n");
         // if (isset($a_entities_allowed['-1'])
         // OR isset($a_entities_allowed[$item->fields['entities_id']])) {
         $notadd = 0;
         $notadddescription = '';
         $a_component = current($pmComponent->find("`id`='" . $data['plugin_monitoring_components_id'] . "'", "", 1));
         if (empty($a_component)) {
             continue;
         }
         $a_hostname = array();
         $a_hostname_single = array();
         $a_hostname_type = array();
         $a_hostname_id = array();
         $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `id` = '" . $data['plugin_monitoring_componentscatalogs_hosts_id'] . "'\n               LIMIT 1";
         $resulth = $DB->query($queryh);
         $hostname = '';
         $plugin_monitoring_componentscatalogs_id = 0;
         $computerTypes_id = 0;
         $entities_id = 0;
         while ($datah = $DB->fetch_array($resulth)) {
             $itemtype = $datah['itemtype'];
             $item = new $itemtype();
             if ($item->getFromDB($datah['items_id'])) {
                 // if (isset($a_entities_allowed['-1'])
                 // OR isset($a_entities_allowed[$item->fields['entities_id']])) {
                 // Fix if hostname is not defined ...
                 if (!empty($item->fields['name'])) {
                     $h = self::shinkenFilter($item->fields['name']);
                     $a_hostname_single[] = $h;
                     if ($pmConfig->fields['append_id_hostname'] == 1) {
                         $h .= "-" . $datah['items_id'];
                     }
                     $a_hostname[] = $h;
                     $a_hostname_type[] = $datah['itemtype'];
                     $a_hostname_id[] = $datah['items_id'];
                     $hostname = $item->fields['name'];
                     $entities_id = $item->fields['entities_id'];
                     $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_id'];
                     if ($itemtype == 'Computer') {
                         $computerTypes_id = $item->fields['computertypes_id'];
                     }
                 }
                 // }
             }
         }
         if (count($a_hostname) > 0) {
             if (isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                 $a_services[$i]['use'] = $_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']];
             }
             $a_services[$i]['host_name'] = implode(",", array_unique($a_hostname));
             $a_services[$i]['_HOSTITEMSID'] = implode(",", array_unique($a_hostname_id));
             $a_services[$i]['_HOSTITEMTYPE'] = implode(",", array_unique($a_hostname_type));
             // Define display_name / service_description
             $a_services[$i]['service_description'] = !empty($a_component['description']) ? $a_component['description'] : self::shinkenFilter($a_component['name']);
             // In case have multiple networkt port, may have description different, else be dropped by shinken
             if ($data['networkports_id'] > 0) {
                 $networkPort->getFromDB($data['networkports_id']);
                 $a_services[$i]['service_description'] .= '-' . self::shinkenFilter($networkPort->fields['name']);
             }
             $a_services[$i]['display_name'] = $a_component['name'];
             // $a_services[$i]['_ENTITIESID'] = $item->fields['entities_id'];
             // $a_services[$i]['_ITEMSID'] = $data['id'];
             // $a_services[$i]['_ITEMTYPE'] = 'Service';
             PluginMonitoringToolbox::logIfExtradebug('pm-shinken', " - add service " . $a_services[$i]['service_description'] . " on " . $a_services[$i]['host_name'] . "\n");
             if (isset(self::$shinkenParameters['glpi']['entityId'])) {
                 $a_services[$i][self::$shinkenParameters['glpi']['entityId']] = $item->fields['entities_id'];
             }
             if (isset(self::$shinkenParameters['glpi']['itemType'])) {
                 $a_services[$i][self::$shinkenParameters['glpi']['itemType']] = 'Service';
             }
             if (isset(self::$shinkenParameters['glpi']['itemId'])) {
                 $a_services[$i][self::$shinkenParameters['glpi']['itemId']] = $data['id'];
             }
             // Manage freshness
             if ($a_component['freshness_count'] == 0) {
                 $a_services[$i]['check_freshness'] = '0';
                 $a_services[$i]['freshness_threshold'] = '3600';
             } else {
                 $multiple = 1;
                 if ($a_component['freshness_type'] == 'seconds') {
                     $multiple = 1;
                 } else {
                     if ($a_component['freshness_type'] == 'minutes') {
                         $multiple = 60;
                     } else {
                         if ($a_component['freshness_type'] == 'hours') {
                             $multiple = 3600;
                         } else {
                             if ($a_component['freshness_type'] == 'days') {
                                 $multiple = 86400;
                             }
                         }
                     }
                 }
                 $a_services[$i]['check_freshness'] = '1';
                 $a_services[$i]['freshness_threshold'] = (string) ($a_component['freshness_count'] * $multiple);
             }
             $pMonitoringCommand->getFromDB($a_component['plugin_monitoring_commands_id']);
             // Manage arguments
             $array = array();
             preg_match_all("/\\\$(ARG\\d+)\\\$/", $pMonitoringCommand->fields['command_line'], $array);
             sort($array[0]);
             $a_arguments = importArrayFromDB($a_component['arguments']);
             $a_argumentscustom = importArrayFromDB($data['arguments']);
             foreach ($a_argumentscustom as $key => $value) {
                 $a_arguments[$key] = $value;
             }
             foreach ($a_arguments as $key => $value) {
                 $a_arguments[$key] = str_replace('!', '\\!', html_entity_decode($value));
             }
             $args = '';
             foreach ($array[0] as $arg) {
                 if ($arg != '$PLUGINSDIR$' and $arg != '$NAGIOSPLUGINSDIR$' and $arg != '$HOSTADDRESS$' and $arg != '$MYSQLUSER$' and $arg != '$MYSQLPASSWORD$') {
                     $arg = str_replace('$', '', $arg);
                     if (!isset($a_arguments[$arg])) {
                         $args .= '!';
                     } else {
                         if (strstr($a_arguments[$arg], "[[HOSTNAME]]")) {
                             $a_arguments[$arg] = str_replace("[[HOSTNAME]]", $hostname, $a_arguments[$arg]);
                         } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTDESCR]]")) {
                             if (class_exists("PluginFusioninventoryNetworkPort")) {
                                 $pfNetworkPort = new PluginFusioninventoryNetworkPort();
                                 $pfNetworkPort->loadNetworkport($data['networkports_id']);
                                 $descr = $pfNetworkPort->getValue("ifdescr");
                                 $a_arguments[$arg] = str_replace("[[NETWORKPORTDESCR]]", $descr, $a_arguments[$arg]);
                             }
                         } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNUM]]")) {
                             $networkPort = new NetworkPort();
                             $networkPort->getFromDB($data['networkports_id']);
                             $logicalnum = $pfNetworkPort->fields['logical_number'];
                             $a_arguments[$arg] = str_replace("[[NETWORKPORTNUM]]", $logicalnum, $a_arguments[$arg]);
                         } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNAME]]")) {
                             if (isset($data['networkports_id']) && $data['networkports_id'] > 0) {
                                 $networkPort = new NetworkPort();
                                 $networkPort->getFromDB($data['networkports_id']);
                                 $portname = $pfNetworkPort->fields['name'];
                                 $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $portname, $a_arguments[$arg]);
                             } else {
                                 if ($a_services[$i]['_HOSTITEMTYPE'] == 'Computer') {
                                     // Get networkportname of networkcard defined
                                     $pmHostaddress = new PluginMonitoringHostaddress();
                                     $a_hostaddresses = $pmHostaddress->find("`itemtype`='Computer'" . " AND  `items_id`='" . $a_services[$i]['_HOSTITEMSID'] . "'", '', 1);
                                     if (count($a_hostaddresses) == 1) {
                                         $a_hostaddress = current($a_hostaddresses);
                                         if ($a_hostaddress['networkports_id'] > 0) {
                                             $networkPort = new NetworkPort();
                                             $networkPort->getFromDB($a_hostaddress['networkports_id']);
                                             $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $networkPort->fields['name'], $a_arguments[$arg]);
                                         }
                                     }
                                 }
                             }
                         } else {
                             if (strstr($a_arguments[$arg], "[")) {
                                 $a_arguments[$arg] = PluginMonitoringService::convertArgument($data['id'], $a_arguments[$arg]);
                             }
                         }
                         if ($a_arguments == '') {
                             $notadd = 1;
                             if ($notadddescription != '') {
                                 $notadddescription .= ", ";
                             }
                             $notadddescription .= "Argument " . $a_arguments[$arg] . " do not have value";
                         }
                         $args .= '!' . $a_arguments[$arg];
                         if ($a_arguments[$arg] == '' and $a_component['alias_command'] != '') {
                             $args .= $a_component['alias_command'];
                         }
                     }
                 }
             }
             // End manage arguments
             if ($a_component['remotesystem'] == 'nrpe') {
                 if ($a_component['alias_command'] != '') {
                     $alias_command = $a_component['alias_command'];
                     if (strstr($alias_command, '[[IP]]')) {
                         $split = explode('-', current($a_hostname));
                         $ip = PluginMonitoringHostaddress::getIp($a_hostname_id[0], $a_hostname_type[0], '');
                         $alias_command = str_replace("[[IP]]", $ip, $alias_command);
                     }
                     if (current($a_hostname_type) == 'Computer') {
                         if ($pmConfig->fields['nrpe_prefix_contener'] == 1) {
                             if (isset($conteners[$computerTypes_id])) {
                                 // get Host of contener/VM
                                 $where = "LOWER(`uuid`)" . ComputerVirtualMachine::getUUIDRestrictRequest($item->fields['uuid']);
                                 $hosts = getAllDatasFromTable('glpi_computervirtualmachines', $where);
                                 if (!empty($hosts)) {
                                     $host = current($hosts);
                                     //                                 $ip = PluginMonitoringHostaddress::getIp($host['computers_id'], 'Computer', '');
                                     $alias_command = current($a_hostname_single) . "_" . $alias_command;
                                 }
                             }
                         }
                     }
                     $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . "check_nrpe!" . $alias_command;
                 } else {
                     $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . "check_nrpe!" . $pMonitoringCommand->fields['command_name'];
                 }
             } else {
                 $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . $pMonitoringCommand->fields['command_name'] . $args;
             }
             // * Manage event handler
             if ($a_component['plugin_monitoring_eventhandlers_id'] > 0) {
                 if ($pmEventhandler->getFromDB($a_component['plugin_monitoring_eventhandlers_id'])) {
                     $a_services[$i]['event_handler'] = $pmEventhandler->fields['command_name'];
                 }
             }
             if (!empty(self::$shinkenParameters['shinken']['services']['process_perf_data'])) {
                 $a_services[$i]['process_perf_data'] = self::$shinkenParameters['shinken']['services']['process_perf_data'];
             }
             if (!empty(self::$shinkenParameters['shinken']['services']['notes'])) {
                 $a_services[$i]['notes'] = self::$shinkenParameters['shinken']['services']['notes'];
             }
             if (!empty(self::$shinkenParameters['shinken']['services']['notes_url'])) {
                 $a_services[$i]['notes_url'] = self::$shinkenParameters['shinken']['services']['notes_url'];
             }
             if (!empty(self::$shinkenParameters['shinken']['services']['action_url'])) {
                 $a_services[$i]['action_url'] = self::$shinkenParameters['shinken']['services']['action_url'];
             }
             if (!empty(self::$shinkenParameters['shinken']['services']['icon_image'])) {
                 $a_services[$i]['icon_image'] = self::$shinkenParameters['shinken']['services']['icon_image'];
             }
             if (!empty(self::$shinkenParameters['shinken']['services']['icon_image_alt'])) {
                 $a_services[$i]['icon_image_alt'] = self::$shinkenParameters['shinken']['services']['icon_image_alt'];
             }
             // * Contacts
             $a_contacts = array();
             $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n                  AND `items_id`='" . $plugin_monitoring_componentscatalogs_id . "'");
             foreach ($a_list_contact as $data_contact) {
                 if ($data_contact['users_id'] > 0) {
                     if (isset($a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                         if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                             $user->getFromDB($data_contact['users_id']);
                             $a_contacts[] = $user->fields['name'];
                         }
                     }
                 } else {
                     if ($data_contact['groups_id'] > 0) {
                         $queryg = "SELECT * FROM `glpi_groups_users`\n                        WHERE `groups_id`='" . $data_contact['groups_id'] . "'";
                         $resultg = $DB->query($queryg);
                         while ($datag = $DB->fetch_array($resultg)) {
                             if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$datag['users_id']])) {
                                 $user->getFromDB($datag['users_id']);
                                 $a_contacts[] = $user->fields['name'];
                             }
                         }
                     }
                 }
             }
             $a_contacts_unique = array_unique($a_contacts);
             $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
             // ** If shinken not use templates or template not defined :
             if (!isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                 $pMonitoringCheck->getFromDB($a_component['plugin_monitoring_checks_id']);
                 $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                 $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                 $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                 $timeperiodsuffix = '-' . $pmHostconfig->getValueAncestor('jetlag', $entities_id);
                 if ($timeperiodsuffix == '-0') {
                     $timeperiodsuffix = '';
                 }
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'] . $timeperiodsuffix;
                 }
                 $a_services[$i]['notification_interval'] = '30';
                 $a_services[$i]['notification_period'] = "24x7";
                 $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                 $a_services[$i]['process_perf_data'] = '1';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['passive_checks_enabled'] = '1';
                 $a_services[$i]['parallelize_check'] = '1';
                 $a_services[$i]['obsess_over_service'] = '1';
                 $a_services[$i]['check_freshness'] = '1';
                 $a_services[$i]['freshness_threshold'] = '3600';
                 $a_services[$i]['notifications_enabled'] = '1';
                 if (isset($a_services[$i]['event_handler'])) {
                     $a_services[$i]['event_handler_enabled'] = '1';
                 } else {
                     $a_services[$i]['event_handler_enabled'] = '0';
                     // $a_services[$i]['event_handler_enabled'] = '';
                 }
                 $a_services[$i]['flap_detection_enabled'] = '1';
                 $a_services[$i]['failure_prediction_enabled'] = '1';
                 $a_services[$i]['retain_status_information'] = '1';
                 $a_services[$i]['retain_nonstatus_information'] = '1';
                 $a_services[$i]['is_volatile'] = '0';
                 // $a_services[$i]['_httpstink'] = 'NO';
             } else {
                 // Notification options
                 $a_services[$i]['notification_interval'] = '30';
                 $pmComponentscatalog->getFromDB($plugin_monitoring_componentscatalogs_id);
                 if ($pmComponentscatalog->fields['notification_interval'] != '30') {
                     $a_services[$i]['notification_interval'] = $pmComponentscatalog->fields['notification_interval'];
                 }
                 $a_services[$i]['notification_period'] = '24x7';
                 $a_services[$i]['check_period'] = '24x7';
                 $timeperiodsuffix = '-' . $pmHostconfig->getValueAncestor('jetlag', $entities_id);
                 if ($timeperiodsuffix == '-0') {
                     $timeperiodsuffix = '';
                 }
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'] . $timeperiodsuffix;
                 }
             }
             // WebUI user interface ...
             if (isset(self::$shinkenParameters['webui']['serviceIcons']['name'])) {
                 $a_services[$i][self::$shinkenParameters['webui']['serviceIcons']['name']] = self::$shinkenParameters['webui']['serviceIcons']['value'];
             }
             if ($notadd == '1') {
                 unset($a_services[$i]);
                 $input = array();
                 $input['id'] = $data['id'];
                 $input['event'] = $notadddescription;
                 $input['state'] = "CRITICAL";
                 $input['state_type'] = "HARD";
                 $pmService->update($input);
             } else {
                 $i++;
             }
         }
         // }
     }
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateServicesCfg services\n");
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Starting generateServicesCfg business rules ...\n");
     // --------------------------------------------------
     // Business rules services ...
     $pmService = new PluginMonitoringService();
     $pmServicescatalog = new PluginMonitoringServicescatalog();
     $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pmBusinessrule = new PluginMonitoringBusinessrule();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
     // Prepare individual contacts
     $a_contacts_entities = array();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'\n         AND `users_id`>0");
     foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
             $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
     }
     // Prepare groups contacts
     $group = new Group();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'\n         AND `groups_id`>0");
     foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
             $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
             $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $queryg = "SELECT * FROM `glpi_groups_users`\n            WHERE `groups_id`='" . $data['groups_id'] . "'";
         $resultg = $DB->query($queryg);
         while ($datag = $DB->fetch_array($resultg)) {
             if (isset($a_contacts_entities[$data['items_id']][$datag['users_id']])) {
                 $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
             }
             $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
     }
     // Services catalogs
     $a_listBA = $pmServicescatalog->find("`is_generic`='0'");
     foreach ($a_listBA as $dataBA) {
         if (isset($a_entities_allowed['-1']) or isset($a_entities_allowed[$dataBA['entities_id']])) {
             $a_grouplist = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $dataBA['id'] . "'");
             $a_group = array();
             foreach ($a_grouplist as $gdata) {
                 $pmBusinessrule_component->replayDynamicServices($gdata['id']);
                 $a_listBR = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $gdata['id'] . "'");
                 foreach ($a_listBR as $dataBR) {
                     if ($pmService->getFromDB($dataBR['plugin_monitoring_services_id'])) {
                         if ($pmService->getHostName() != '') {
                             $hostname = self::shinkenFilter($pmService->getHostName());
                             if ($gdata['operator'] == 'and' or $gdata['operator'] == 'or' or strstr($gdata['operator'], ' of:')) {
                                 $operator = '|';
                                 if ($gdata['operator'] == 'and') {
                                     $operator = '&';
                                 }
                                 if (!isset($a_group[$gdata['id']])) {
                                     $a_group[$gdata['id']] = '';
                                     if (strstr($gdata['operator'], ' of:')) {
                                         $a_group[$gdata['id']] = $gdata['operator'];
                                     }
                                     $a_group[$gdata['id']] .= $hostname . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 } else {
                                     $a_group[$gdata['id']] .= $operator . $hostname . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 }
                             } else {
                                 $a_group[$gdata['id']] = $gdata['operator'] . " " . $hostname . "," . self::shinkenFilter($item->getName());
                             }
                         }
                     }
                     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "   - SC group : " . $a_group[$gdata['id']] . "\n");
                 }
             }
             if (count($a_group) > 0) {
                 $pMonitoringCheck->getFromDB($dataBA['plugin_monitoring_checks_id']);
                 $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                 $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                 $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                 if ($calendar->getFromDB($dataBA['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                 }
                 $a_services[$i]['host_name'] = self::$shinkenParameters['shinken']['fake_hosts']['name_prefix'] . self::$shinkenParameters['shinken']['fake_hosts']['bp_host'];
                 $a_services[$i]['business_impact'] = $dataBA['business_priority'];
                 $a_services[$i]['service_description'] = self::shinkenFilter($dataBA['name']);
                 $a_services[$i]['_ENTITIESID'] = $dataBA['id'];
                 $a_services[$i]['_ITEMSID'] = $dataBA['id'];
                 $a_services[$i]['_ITEMTYPE'] = 'ServiceCatalog';
                 $command = "bp_rule!";
                 foreach ($a_group as $key => $value) {
                     if (!strstr($value, "&") and !strstr($value, "|")) {
                         $a_group[$key] = trim($value);
                     } else {
                         $a_group[$key] = "(" . trim($value) . ")";
                     }
                 }
                 $a_services[$i]['check_command'] = $command . implode("&", $a_group);
                 if ($dataBA['notification_interval'] != '30') {
                     $a_services[$i]['notification_interval'] = $dataBA['notification_interval'];
                 } else {
                     $a_services[$i]['notification_interval'] = '30';
                 }
                 $a_services[$i]['notification_period'] = "24x7";
                 $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['process_perf_data'] = '1';
                 $a_services[$i]['active_checks_enabled'] = '1';
                 $a_services[$i]['passive_checks_enabled'] = '1';
                 $a_services[$i]['parallelize_check'] = '1';
                 $a_services[$i]['obsess_over_service'] = '1';
                 $a_services[$i]['check_freshness'] = '1';
                 $a_services[$i]['freshness_threshold'] = '3600';
                 $a_services[$i]['notifications_enabled'] = '1';
                 $a_services[$i]['event_handler_enabled'] = '0';
                 //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
                 $a_services[$i]['flap_detection_enabled'] = '1';
                 $a_services[$i]['failure_prediction_enabled'] = '1';
                 $a_services[$i]['retain_status_information'] = '1';
                 $a_services[$i]['retain_nonstatus_information'] = '1';
                 $a_services[$i]['is_volatile'] = '0';
                 // $a_services[$i]['_httpstink'] = 'NO';
                 // * Contacts
                 $a_contacts = array();
                 $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'\n                  AND `items_id`='" . $dataBA['id'] . "'");
                 foreach ($a_list_contact as $data_contact) {
                     if ($data_contact['users_id'] > 0) {
                         if (isset($a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                             if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                                 $user->getFromDB($data_contact['users_id']);
                                 $a_contacts[] = $user->fields['name'];
                             }
                         }
                     } else {
                         if ($data_contact['groups_id'] > 0) {
                             $queryg = "SELECT * FROM `glpi_groups_users`\n                        WHERE `groups_id`='" . $data_contact['groups_id'] . "'";
                             $resultg = $DB->query($queryg);
                             while ($datag = $DB->fetch_array($resultg)) {
                                 if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                                     $user->getFromDB($datag['users_id']);
                                     $a_contacts[] = $user->fields['name'];
                                 }
                             }
                         }
                     }
                 }
                 $a_contacts_unique = array_unique($a_contacts);
                 $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
                 $i++;
             }
         }
     }
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateServicesCfg business rules\n");
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Starting generateServicesCfg business rules templates ...\n");
     // Services catalogs templates
     // TODO : correctly test and improve it !
     $a_listBA = $pmServicescatalog->find("`is_generic`='1'");
     foreach ($a_listBA as $dataBA) {
         PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "   - SC : " . $dataBA['id'] . "\n");
         if (isset($a_entities_allowed['-1']) or isset($a_entities_allowed[$dataBA['entities_id']])) {
             $pmServicescatalog->getFromDB($dataBA['id']);
             $a_entitiesServices = $pmServicescatalog->getGenericServicesEntities();
             foreach ($a_entitiesServices as $idEntity => $a_entityServices) {
                 // New entity ... so new business rule !
                 PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "   - SC templated services for an entity : " . $idEntity . "\n");
                 $pmDerivatedSC = new PluginMonitoringServicescatalog();
                 $a_derivatedSC = $pmDerivatedSC->find("`entities_id`='{$idEntity}' AND `name` LIKE '" . $dataBA['name'] . "%'");
                 foreach ($a_derivatedSC as $a_derivated) {
                     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "   - a_derivated : " . $a_derivated['name'] . "\n");
                     $a_derivatedSC = $a_derivated;
                 }
                 $a_group = array();
                 foreach ($a_entityServices as $services) {
                     if ($pmService->getFromDB($services['serviceId'])) {
                         // Toolbox::logInFile("pm-shinken", "   - SC templated service entity : ".$services['entityId'].", service :  ".$pmService->getName(true)." on ".$pmService->getHostName()."\n");
                         if ($pmService->getHostName() != '') {
                             $hostname = self::shinkenFilter($pmService->getHostName());
                             $serviceFakeId = $services['entityId'];
                             $pmBusinessrulegroup->getFromDB($services['BRgroupId']);
                             $BRoperator = $pmBusinessrulegroup->getField('operator');
                             if ($BRoperator == 'and' or $BRoperator == 'or' or strstr($BRoperator, ' of:')) {
                                 $operator = '|';
                                 if ($BRoperator == 'and') {
                                     $operator = '&';
                                 }
                                 if (!isset($a_group[$serviceFakeId])) {
                                     $a_group[$serviceFakeId] = '';
                                     if (strstr($BRoperator, ' of:')) {
                                         $a_group[$serviceFakeId] = $BRoperator;
                                     }
                                     $a_group[$serviceFakeId] .= $hostname . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 } else {
                                     $a_group[$serviceFakeId] .= $operator . $hostname . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 }
                             } else {
                                 $a_group[$serviceFakeId] = $BRoperator . " " . $hostname . "," . self::shinkenFilter($pmService->getHostName());
                             }
                             // Toolbox::logInFile("pm-shinken", "   - SCT group : ".$a_group[$serviceFakeId]."\n");
                         }
                     }
                 }
                 if (count($a_group) > 0) {
                     $pMonitoringCheck->getFromDB($a_derivatedSC['plugin_monitoring_checks_id']);
                     $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                     $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                     $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                     if ($calendar->getFromDB($a_derivatedSC['calendars_id'])) {
                         $a_services[$i]['check_period'] = $calendar->fields['name'];
                     }
                     $a_services[$i]['host_name'] = self::shinkenFilter($a_derivatedSC['name']);
                     $a_services[$i]['host_name'] = self::$shinkenParameters['shinken']['fake_hosts']['name_prefix'] . self::$shinkenParameters['shinken']['fake_hosts']['bp_host'];
                     $a_services[$i]['business_impact'] = $a_derivatedSC['business_priority'];
                     $a_services[$i]['service_description'] = self::shinkenFilter($a_derivatedSC['name']);
                     $a_services[$i]['_ENTITIESID'] = $a_derivatedSC['entities_id'];
                     $a_services[$i]['_ITEMSID'] = $a_derivatedSC['id'];
                     $a_services[$i]['_ITEMTYPE'] = 'ServiceCatalog';
                     $command = "bp_rule!";
                     foreach ($a_group as $key => $value) {
                         if (!strstr($value, "&") and !strstr($value, "|")) {
                             $a_group[$key] = trim($value);
                         } else {
                             $a_group[$key] = "(" . trim($value) . ")";
                         }
                     }
                     $a_services[$i]['check_command'] = $command . implode("&", $a_group);
                     if ($a_derivatedSC['notification_interval'] != '30') {
                         $a_services[$i]['notification_interval'] = $a_derivatedSC['notification_interval'];
                     } else {
                         $a_services[$i]['notification_interval'] = '30';
                     }
                     $a_services[$i]['notification_period'] = "24x7";
                     $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                     $a_services[$i]['active_checks_enabled'] = '1';
                     $a_services[$i]['process_perf_data'] = '1';
                     $a_services[$i]['active_checks_enabled'] = '1';
                     $a_services[$i]['passive_checks_enabled'] = '1';
                     $a_services[$i]['parallelize_check'] = '1';
                     $a_services[$i]['obsess_over_service'] = '1';
                     $a_services[$i]['check_freshness'] = '1';
                     $a_services[$i]['freshness_threshold'] = '3600';
                     $a_services[$i]['notifications_enabled'] = '1';
                     $a_services[$i]['event_handler_enabled'] = '0';
                     //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
                     $a_services[$i]['flap_detection_enabled'] = '1';
                     $a_services[$i]['failure_prediction_enabled'] = '1';
                     $a_services[$i]['retain_status_information'] = '1';
                     $a_services[$i]['retain_nonstatus_information'] = '1';
                     $a_services[$i]['is_volatile'] = '0';
                     // $a_services[$i]['_httpstink'] = 'NO';
                     // * Contacts
                     $a_contacts = array();
                     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'\n                     AND `items_id`='" . $dataBA['id'] . "'");
                     foreach ($a_list_contact as $data_contact) {
                         if ($data_contact['users_id'] > 0) {
                             if (isset($a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                                 if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                                     $user->getFromDB($data_contact['users_id']);
                                     $a_contacts[] = $user->fields['name'];
                                 }
                             }
                         } else {
                             if ($data_contact['groups_id'] > 0) {
                                 $queryg = "SELECT * FROM `glpi_groups_users`\n                           WHERE `groups_id`='" . $data_contact['groups_id'] . "'";
                                 $resultg = $DB->query($queryg);
                                 while ($datag = $DB->fetch_array($resultg)) {
                                     if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                                         $user->getFromDB($datag['users_id']);
                                         $a_contacts[] = $user->fields['name'];
                                     }
                                 }
                             }
                         }
                     }
                     $a_contacts_unique = array_unique($a_contacts);
                     $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
                     $i++;
                 }
             }
         }
     }
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateServicesCfg business rules templates\n");
     if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on " . date("Y-m-d H:i:s") . "\n\n";
         foreach ($a_services as $data) {
             $config .= $this->writeFile("service", $data);
         }
         return array('services.cfg', $config);
     } else {
         return $a_services;
     }
 }
 function parseToRrdtool($plugin_monitoring_services_id)
 {
     global $DB;
     $pmRrdtool = new PluginMonitoringRrdtool();
     $pmCommand = new PluginMonitoringCommand();
     $pmService = new PluginMonitoringService();
     $pmComponent = new PluginMonitoringComponent();
     if ($pmService->getFromDB($plugin_monitoring_services_id)) {
         $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
         if (!isset($pmComponent->fields['plugin_monitoring_commands_id'])) {
             return;
         }
         if (is_null($pmComponent->fields['graph_template'])) {
             return;
         }
         $pmCommand->getFromDB($pmComponent->fields['plugin_monitoring_commands_id']);
         $pmUnavaibility = new PluginMonitoringUnavaibility();
         $pmUnavaibility->runUnavaibility($plugin_monitoring_services_id);
         $query = "SELECT * FROM `" . $this->getTable() . "`\n            WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n            ORDER BY `date`";
         $result = $DB->query($query);
         $i = 0;
         $nb_rows = $DB->numrows($result);
         $rrdtool_value = '';
         $last_date = '';
         while ($edata = $DB->fetch_array($result)) {
             $i++;
             if ($edata['unavailability'] == '0') {
                 if ($last_date != '') {
                     $pmRrdtool->addData($pmComponent->fields['graph_template'], $plugin_monitoring_services_id, 0, '', $rrdtool_value, 1);
                 }
                 break;
             }
             $perf_data = $edata['perf_data'];
             if ($edata['perf_data'] == '') {
                 $perf_data = $edata['output'];
             }
             if ($edata['unavailability'] != '2' and $i < $nb_rows) {
                 $rrdtool_value = $pmRrdtool->addData($pmComponent->fields['graph_template'], $plugin_monitoring_services_id, $this->convert_datetime_timestamp($edata['date']), $perf_data, $rrdtool_value, 0);
             }
             $last_date = $edata['date'];
             if ($i == $nb_rows) {
                 if ($edata['unavailability'] != '2') {
                     $input = array();
                     $input['id'] = $edata['id'];
                     $input['unavailability'] = 2;
                     $this->update($input);
                     $pmRrdtool->addData($pmComponent->fields['graph_template'], $plugin_monitoring_services_id, $this->convert_datetime_timestamp($edata['date']), $perf_data, $rrdtool_value, 1);
                     $queryd = "DELETE FROM `" . $this->getTable() . "`\n                     WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                        AND `date`<'" . $edata['date'] . "'";
                     $DB->query($queryd);
                 }
             }
         }
         $a_list = array();
         $a_list[] = "2h";
         $a_list[] = "12h";
         $a_list[] = "1d";
         $a_list[] = "1w";
         $a_list[] = "1m";
         $a_list[] = "0y6m";
         $a_list[] = "1y";
         $pmConfig = new PluginMonitoringConfig();
         $pmConfig->getFromDB(1);
         $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
         foreach ($a_list as $time) {
             foreach ($a_timezones as $timezone) {
                 $pmRrdtool->displayGLPIGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $plugin_monitoring_services_id, $timezone, $time);
             }
         }
     } else {
         $query = "DELETE FROM `" . $this->getTable() . "`\n            WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'";
         $DB->query($query);
     }
 }