function sendAcknowledge($services_id)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $pmComponent = new PluginMonitoringComponent();
     $pmTag = new PluginMonitoringTag();
     $pmService->getFromDB($services_id);
     $hostname = '';
     $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts` \n         WHERE `id` = '" . $pmService->fields['plugin_monitoring_componentscatalogs_hosts_id'] . "'\n         LIMIT 1";
     $resulth = $DB->query($queryh);
     while ($datah = $DB->fetch_array($resulth)) {
         $itemtype = $datah['itemtype'];
         $item = new $itemtype();
         if ($item->getFromDB($datah['items_id'])) {
             $hostname = $itemtype . "-" . $datah['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
         }
     }
     $a_component = current($pmComponent->find("`id`='" . $pmService->fields['plugin_monitoring_components_id'] . "'", "", 1));
     $service_description = preg_replace("/[^A-Za-z0-9]/", "", $a_component['name']) . "-" . $pmService->fields['id'];
     $tag = PluginMonitoringEntity::getTagByEntities($pmService->fields['entities_id']);
     $ip = $pmTag->getIP($tag);
     $auth = $pmTag->getAuth($tag);
     $url = 'http://' . $ip . ':7760/';
     $action = 'acknowledge';
     $a_fields = array('host_name' => urlencode($hostname), 'service_description' => urlencode($service_description), 'author' => urlencode($_SESSION['glpiname']), 'comment' => urlencode(''));
     $this->sendCommand($url, $action, $a_fields, '', $auth);
 }
along with GLPI; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file: David DURIEUX
// Purpose of file:
// ----------------------------------------------------------------------
// Direct access to file
if (strpos($_SERVER['PHP_SELF'], "updatePerfname.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
if (!defined('GLPI_ROOT')) {
    die("Can not acces directly to this file");
}
Session::checkLoginUser();
$pmComponent = new PluginMonitoringComponent();
$sPerfname = explode(',', $_GET['perfname']);
$dbPerfname = array();
$_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']] = array();
foreach ($sPerfname as $value) {
    $dbPerfname[$value] = 1;
    $_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']][$value] = "checked";
}
if ($_GET['db']) {
    $input = array('id' => $_GET['components_id'], 'perfname' => serialize($dbPerfname));
    $pmComponent->update($input);
}
Html::ajaxFooter();
   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();

      $a_services = array();
      $i=0;

      // TODO: only contacts in allowed entities ...
      // Prepare individual contacts
      $a_contacts_entities = array();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
         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'
         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`
            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_type = array();
            $a_hostname_id = array();
            $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`
               WHERE `id` = '".$data['plugin_monitoring_componentscatalogs_hosts_id']."'
               LIMIT 1";
            $resulth = $DB->query($queryh);
            $hostname = '';
            $plugin_monitoring_componentscatalogs_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'])) {
                        $a_hostname[] = preg_replace("/[^A-Za-z0-9\-_]/","",$item->fields['name']);
                        $a_hostname_type[] = $datah['itemtype'];
                        $a_hostname_id[] = $datah['items_id'];
                        $hostname = $item->fields['name'];
                        $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_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'] : preg_replace("/[^A-Za-z0-9\-_]/","",$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'] .= '-'.preg_replace("/[^A-Za-z0-9\-_]/", "", $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($split[1], $split[0], '');
                        $alias_command = str_replace("[[IP]]", $ip, $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'
                  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`
                        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'];
                  if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
                  $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';
                  if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
               }

               // 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'
         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'
         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`
            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 = preg_replace("/[^A-Za-z0-9\-_]/","",$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.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           } else {
                              $a_group[$gdata['id']] .= $operator.$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           }
                        } else {
                           $a_group[$gdata['id']] = $gdata['operator']." ".$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$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'] = preg_replace("/[^A-Za-z0-9\-_]/","",$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'
                  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`
                        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 = preg_replace("/[^A-Za-z0-9\-_]/","",$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.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           } else {
                              $a_group[$serviceFakeId] .= $operator.$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           }
                        } else {
                           $a_group[$serviceFakeId] = $BRoperator." ".$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$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'] = preg_replace("/[^A-Za-z0-9\-_]/","",$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'] = preg_replace("/[^A-Za-z0-9\-_]/","",$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'
                     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`
                           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;
      }
   }
 /**
  *
  * @param $items_id integer ID
  * @param $options array
  *
  *@return bool true if form is ok
  *
  **/
 function showForm($items_id, $itemtype, $options = array())
 {
     global $DB, $CFG_GLPI;
     $pmComponent = new PluginMonitoringComponent();
     $pmRealm = new PluginMonitoringRealm();
     $entities_id = 0;
     if ($itemtype == "Entity") {
         $entities_id = $items_id;
     } else {
         $item = new $itemtype();
         $item->getFromDB($items_id);
         $entities_id = $item->fields['entities_id'];
     }
     $query = "SELECT * FROM `" . $this->getTable() . "`\n         WHERE `items_id`='" . $items_id . "'\n            AND `itemtype`='" . $itemtype . "'\n         LIMIT 1";
     $result = $DB->query($query);
     if ($DB->numrows($result) == '0') {
         $this->getEmpty();
         if ($entities_id != '0' or $itemtype != 'Entity') {
             $this->fields['plugin_monitoring_components_id'] = -1;
             $this->fields['plugin_monitoring_realms_id'] = -1;
             $this->fields['jetlag'] = 100;
         }
     } else {
         $data = $DB->fetch_assoc($result);
         $this->getFromDB($data['id']);
     }
     echo "<form name='form' method='post'\n         action='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/hostconfig.form.php'>";
     echo "<table class='tab_cadre_fixe'";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='4'>";
     echo __('Hosts configuration', 'monitoring');
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo __('Component', 'monitoring') . "&nbsp;:";
     echo "</td>";
     echo "<td>";
     $toadd = array();
     if ($entities_id != '0' or $itemtype != 'Entity') {
         $toadd["-1"] = __('Inheritance of the parent entity');
     }
     Dropdown::show('PluginMonitoringComponent', array('name' => 'plugin_monitoring_components_id', 'value' => $this->fields['plugin_monitoring_components_id'], 'toadd' => $toadd, 'display_emptychoice' => FALSE));
     echo "</td>";
     echo "<td>" . __('Reaml', 'monitoring') . "&nbsp;:</td>";
     echo "<td>";
     $toadd = array();
     if ($entities_id != '0' or $itemtype != 'Entity') {
         $toadd["-1"] = __('Inheritance of the parent entity');
     }
     Dropdown::show('PluginMonitoringRealm', array('name' => 'plugin_monitoring_realms_id', 'value' => $this->fields['plugin_monitoring_realms_id'], 'toadd' => $toadd, 'display_emptychoice' => FALSE));
     echo "</td>";
     echo "</tr>";
     // Inheritance
     if ($this->fields['plugin_monitoring_components_id'] == '-1') {
         echo "<tr class='tab_bg_1'>";
         if ($this->fields['plugin_monitoring_components_id'] == '-1') {
             echo "<td colspan='2' class='green center'>";
             echo __('Inheritance of the parent entity') . "&nbsp;:&nbsp;";
             $pmComponent->getFromDB($this->getValueAncestor("plugin_monitoring_components_id", $entities_id));
             echo $pmComponent->fields['name'];
             echo "</td>";
         } else {
             echo "<td colspan='2'>";
             echo "</td>";
         }
         if ($this->fields['plugin_monitoring_realms_id'] == '-1') {
             echo "<td colspan='2' class='green center'>";
             echo __('Inheritance of the parent entity') . "&nbsp;:&nbsp;";
             $pmRealm->getFromDB($this->getValueAncestor("plugin_monitoring_realms_id", $entities_id));
             echo $pmRealm->fields['name'];
             echo "</td>";
         } else {
             echo "<td colspan='2'>";
             echo "</td>";
         }
         echo "</tr>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo __('Jet lag', 'monitoring') . "&nbsp;:";
     echo "</td>";
     echo "<td>";
     $elements = array('-11' => '-11', '-10' => '-10', '-9' => '-9', '-8' => '-8', '-7' => '-7', '-6' => '-6', '-5' => '-5', '-4' => '-4', '-3' => '-3', '-2' => '-2', '-1' => '-1', '0' => '0', '1' => '+1', '2' => '+2', '3' => '+3', '4' => '+4', '5' => '+5', '6' => '+6', '7' => '+7', '8' => '+8', '9' => '+9', '10' => '+10', '11' => '+11', '12' => '+12', '13' => '+13', '14' => '+14');
     if ($entities_id != '0' or $itemtype != 'Entity') {
         $elements["100"] = __('Inheritance of the parent entity');
     }
     Dropdown::showFromArray('jetlag', $elements, array('value' => $this->fields['jetlag']));
     echo "</td>";
     echo "<td colspan='2'></td>";
     echo "</tr>";
     // Inheritance
     if ($this->fields['jetlag'] == '100') {
         echo "<tr class='tab_bg_1'>";
         if ($this->fields['jetlag'] == '100') {
             echo "<td colspan='2' class='green center'>";
             echo __('Inheritance of the parent entity') . "&nbsp;:&nbsp;";
             echo $elements[$this->getValueAncestor("jetlag", $entities_id)];
             echo "</td>";
         } else {
             echo "<td colspan='2'>";
             echo "</td>";
         }
         echo "<td colspan='2'>";
         echo "</td>";
         echo "</tr>";
     }
     /*
           if ($itemtype == 'Entity'
                   AND $items_id == '0') {
              echo "<tr class='tab_bg_1'>";
              echo "<td>";
              echo __('Shinken Server', 'monitoring')."&nbsp;:";
              echo "</td>";
              echo "<td>";
              Dropdown::show("Computer", array(
                  'name'  => 'computers_id',
                  'value' => $this->fields['computers_id']
                 ));
              echo "</td>";
              echo "<td colspan='2'></td>";
              echo "</tr>";
           }
     */
     if ($this->canCreate()) {
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='4' align='center'>";
         if (isset($this->fields['id']) and $this->fields['id'] != '') {
             echo "<input type='hidden' name='id' value='" . $this->fields['id'] . "'/>";
         }
         echo "<input type='hidden' name='itemtype' value='" . $itemtype . "'/>";
         echo "<input type='hidden' name='items_id' value='" . $items_id . "'/>";
         echo "<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>";
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
     Html::closeForm();
     return true;
 }
Beispiel #5
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 displayItem($data, $config)
 {
     global $CFG_GLPI;
     $itemtype = $data['itemtype'];
     $itemtype2 = '';
     if ($itemtype == 'host' || $itemtype == 'service') {
         $itemtype2 = $itemtype;
         $itemtype = 'PluginMonitoringDisplayview';
     }
     $item = new $itemtype();
     $content = '';
     $title = $item->getTypeName();
     $event = '';
     $width = '';
     if ($itemtype == "PluginMonitoringService") {
         $content = $item->showWidget($data['items_id'], $data['extra_infos']);
         if (!isset($item->fields['plugin_monitoring_components_id'])) {
             return false;
         }
         $title .= " : <a href=\"" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['items_id'] . "\">" . Dropdown::getDropdownName(getTableForItemType('PluginMonitoringComponent'), $item->fields['plugin_monitoring_components_id']);
         $title .= '</a> ' . __('on', 'monitoring') . ' ';
         $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
         $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() . " / " . $data['extra_infos'] . ")");
         }
         $width = "width: 475,";
     } else {
         if ($itemtype == "PluginMonitoringWeathermap") {
             $content = $item->showWidget($data['items_id'], $data['extra_infos']);
             $content = '<div id="weathermap-' . $data['items_id'] . '">' . $content . "</div>";
             $event = ", " . $item->widgetEvent($data['items_id']);
             $title .= " : " . Dropdown::getDropdownName(getTableForItemType('PluginMonitoringWeathermap'), $data['items_id']);
             $item->getFromDB($data['items_id']);
             $width = "width:" . $item->fields['width'] * $data['extra_infos'] / 100 . ",";
         } else {
             if ($itemtype2 != '') {
                 $content = $item->showWidget2($data['id']);
             } else {
                 $content = $item->showWidget($data['items_id']);
             }
             if ($data['itemtype'] == 'PluginMonitoringServicescatalog') {
                 $width = "width: 202,";
             } else {
                 $width = "width: 180,";
             }
         }
     }
     if ($config == 0 && $itemtype != "PluginMonitoringService") {
         $title = '';
     }
     echo "<script>\n         var left = 0;\n         var topd = 0;\n         var obj = document.getElementById('panel');\n         if (obj.offsetParent) {\n           do {\n             left += obj.offsetLeft;\n             topd += obj.offsetTop;\n           } while (obj = obj.offsetParent);\n         }\n\n        var item" . $data['id'] . " = new Ext.Panel({\n             closable: true,           \n             title: '" . $title . "',\n             x: " . $data['x'] . ",\n             y: " . $data['y'] . ",\n             html       : '" . $content . "',\n             baseCls : 'x-panel',\n             layout : 'fit',\n             bodyStyle: 'background:transparent',\n             ";
     if ($config == 0 && $itemtype != "PluginMonitoringService") {
         echo "border: false,";
     }
     echo "renderTo: Ext.getBody(),\n             floating: false,\n             frame: false,\n             " . $width . "\n             autoHeight  : true,\n             layout: 'fit',\n             draggable: {\n                 //Config option of Ext.Panel.DD class.\n                 //It's a floating Panel, so do not show a placeholder proxy in the original position.\n                 insertProxy: false,\n\n                 //Called for each mousemove event while dragging the DD object.\n                 onDrag : function(e){\n                     //Record the x,y position of the drag proxy so that we can\n                     //position the Panel at end of drag.\n                     var el = this.proxy.getEl();\n                     this.x = el.getLeft(true) - left - 5;\n                     this.y = el.getTop(true) - topd - 5;\n\n\n                     //Keep the Shadow aligned if there is one.\n                     var s = this.panel.getEl().shadow;\n                     if (s) {\n                         s.realign(this.x, this.y, pel.getWidth(), pel.getHeight());\n                     }\n                 },\n\n                 //Called on the mouseup event.\n                 endDrag : function(e){\n                     this.panel.setPosition(this.x, this.y);\n";
     if ($config == '1') {
         echo "      Ext.get('updatecoordonates').load({\n                        url: '" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/ajax/displayview_itemcoordinates.php',\n                        scripts: true,\n                        params:'id=" . $data['id'] . "&x=' + (this.x)  + '&y=' + (this.y)\n                     });\n";
         echo "      if (this.x < 1) {\n                        this.panel.destroy();\n                     }\n                     if (this.y < 0) {\n                        this.panel.destroy();\n                     }\n            \n            ";
     }
     echo "      }\n             }\n             " . $event . "\n         });\n     </script>";
     //.show()
     if ($itemtype == "PluginMonitoringService") {
         $pmComponent = new PluginMonitoringComponent();
         $item = new $itemtype();
         $item->getFromDB($data['items_id']);
         $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
         $pmServicegraph = new PluginMonitoringServicegraph();
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $data['items_id'], "0", $data['extra_infos'], "js");
     } else {
         if ($itemtype == "PluginMonitoringComponentscatalog") {
             $pmComponentscatalog = new PluginMonitoringComponentscatalog();
             $pmComponentscatalog->ajaxLoad($data['items_id']);
         } else {
             if ($itemtype == "PluginMonitoringServicescatalog") {
                 $pmServicescatalog = new PluginMonitoringServicescatalog();
                 $pmServicescatalog->ajaxLoad($data['items_id']);
             } else {
                 if ($itemtype2 != '') {
                     $pmDisplayview = new PluginMonitoringDisplayview();
                     $pmDisplayview->ajaxLoad2($data['id']);
                 } else {
                     if ($itemtype == "PluginMonitoringDisplayview") {
                         $pmDisplayview = new PluginMonitoringDisplayview();
                         $pmDisplayview->ajaxLoad($data['items_id']);
                     }
                 }
             }
         }
     }
     if ($itemtype == "PluginMonitoringWeathermap") {
         //         echo "<script type='text/javascript'>
         //            function updateimagew".$data['items_id']."() {
         //               var demain=new Date();
         //               document.getElementById('weathermap-".$data['items_id']."').innerHTML = demain.getTime() + '".$content."';
         //            }
         //            setInterval(updateimagew".$data['items_id'].", 50000);
         //         </script>";
         //      }
         echo "<script type='text/javascript'>\n         var mgr = new Ext.UpdateManager('weathermap-" . $data['items_id'] . "');\n         mgr.startAutoRefresh(50, \"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/widgetWeathermap.php\", \"id=" . $data['items_id'] . "&extra_infos=" . $data['extra_infos'] . "\", \"\", true);\n         </script>";
     }
     return true;
 }
 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>";
 }
 function getSpecificData($perfdatas_id, $items_id, $which = 'last', $state = "AND `state` = 'OK'")
 {
     global $DB;
     // ** Get in table serviceevents
     $mydatat = array();
     $a_labels = array();
     $a_ref = array();
     $pmService = new PluginMonitoringService();
     $pmService->getFromDB($items_id);
     $_SESSION['plugin_monitoring_checkinterval'] = PluginMonitoringComponent::getTimeBetween2Checks($pmService->fields['plugin_monitoring_components_id']);
     $enddate = date('U');
     $counters = array();
     switch ($which) {
         case 'first':
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n               WHERE `plugin_monitoring_services_id`='" . $items_id . "'\n                  AND `perf_data` != ''\n                  " . $state . "\n               ORDER BY `date` ASC\n               LIMIT 1";
             break;
         case 'last':
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n               WHERE `plugin_monitoring_services_id`='" . $items_id . "'\n                  AND `perf_data` != ''\n                  " . $state . "\n               ORDER BY `date` DESC\n               LIMIT 1";
             break;
         default:
             return $counters;
             break;
     }
     $resultevent = $DB->query($query);
     $dataevent = $DB->fetch_assoc($resultevent);
     $result = $DB->query($query);
     $ret = $this->getData($result, $perfdatas_id, $dataevent['date'], $dataevent['date']);
     /*
           if (is_array($ret)) {
              foreach ($ret[0] as $name=>$data) {
                 $counters[$name] = $data[0];
              }
           }
     */
     if (is_array($ret) && is_array($ret[0]) && is_array($ret[4])) {
         foreach ($ret[4] as $name => $data) {
             // Toolbox::logInFile("pm", "$name -> $data = ".$ret[0][$data][0]."\n");
             $counter = array();
             $counter['id'] = preg_replace("/[^A-Za-z0-9\\-_]/", "", $name);
             $counter['name'] = $data;
             $counter['value'] = $ret[0][$data][0];
             $counters[] = $counter;
         }
     }
     return $counters;
 }
 function showComponents($componentscatalogs_id)
 {
     global $DB, $CFG_GLPI;
     $this->addComponent($componentscatalogs_id);
     $rand = mt_rand();
     $pmComponent = new PluginMonitoringComponent();
     $pmCommand = new PluginMonitoringCommand();
     $pmCheck = new PluginMonitoringCheck();
     $calendar = new Calendar();
     echo "<form method='post' name='componentscatalog_component_form{$rand}' id='componentscatalog_component_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/front/componentscatalog_component.form.php\">";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th>";
     echo __('Associated components', 'monitoring');
     echo "</th>";
     echo "</tr>";
     echo "</table>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th width='10'>&nbsp;</th>";
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Command name', 'monitoring') . "</th>";
     echo "<th>" . __('Check definition', 'monitoring') . "</th>";
     echo "<th>" . __('Check period', 'monitoring') . "</th>";
     echo "<th>" . __('Remote check', 'monitoring') . "</th>";
     echo "</tr>";
     $used = array();
     $query = "SELECT * FROM `" . $this->getTable() . "`\n         WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $used[] = $data['plugin_monitoring_components_id'];
         $pmComponent->getFromDB($data['plugin_monitoring_components_id']);
         echo "<tr>";
         echo "<td>";
         echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>";
         echo "</td>";
         echo "<td class='center'>";
         echo $pmComponent->getLink(1);
         echo "</td>";
         echo "<td class='center'>";
         $pmCommand->getFromDB($pmComponent->fields['plugin_monitoring_commands_id']);
         echo $pmCommand->getLink();
         echo "</td>";
         echo "<td class='center'>";
         $pmCheck->getFromDB($pmComponent->fields['plugin_monitoring_checks_id']);
         echo $pmCheck->getLink();
         echo "</td>";
         echo "<td class='center'>";
         $calendar->getFromDB($pmComponent->fields['calendars_id']);
         echo $calendar->getLink();
         echo "</td>";
         echo "<td class='center'>";
         if ($pmComponent->fields['remotesystem'] == '') {
             echo "-";
         } else {
             echo $pmComponent->fields['remotesystem'];
         }
         echo "</td>";
         echo "</tr>";
     }
     Html::openArrowMassives("componentscatalog_host_form{$rand}", true);
     Html::closeArrowMassives(array('deleteitem' => _sx('button', 'Delete permanently')));
     Html::closeForm();
     echo "</table>";
 }
 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>";
 }
 function showForm($items_id, $servicescatalogs_id, $options = array())
 {
     global $CFG_GLPI;
     if ($items_id != '') {
         $this->getFromDB($items_id);
     } else {
         $this->getEmpty();
     }
     $this->showFormHeader($options);
     $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
     $pmBusinessrule_component->replayDynamicServices($items_id);
     $pmSC = new PluginMonitoringServicescatalog();
     $pmSC->getFromDB($servicescatalogs_id);
     $rand = mt_rand();
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo "<input type='hidden' name='plugin_monitoring_servicescatalogs_id' value='" . $servicescatalogs_id . "'/>";
     echo __('Name') . "&nbsp;:";
     echo "</td>";
     echo "<td>";
     echo "<input type='text' name='name' value='" . $this->fields["name"] . "' size='30'/>";
     echo "</td>";
     if ($items_id != '') {
         if (Session::haveRight("plugin_monitoring_servicescatalog", CREATE)) {
             echo "<th colspan='2' width='60%'>";
             echo __('Resources', 'monitoring');
             echo "&nbsp;";
             echo "<img onClick=\"Ext.get('ressources" . $rand . "').setDisplayed('block')\"\n                       title=\"" . __('add') . "\" alt=\"" . __('add') . "\"\n                       class='pointer'  src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png'>";
             echo "</th>";
         }
     }
     echo "</tr>";
     echo "<tr>";
     echo "<td valign='top'>";
     echo __('Logical operator') . "&nbsp;:";
     echo "</td>";
     echo "<td valign='top'>";
     $first_operator = array();
     $first_operator['and'] = "and";
     $first_operator['or'] = "or";
     $first_operator['2 of:'] = __('2 of', 'monitoring');
     $first_operator['3 of:'] = __('3 of', 'monitoring');
     $first_operator['4 of:'] = __('4 of', 'monitoring');
     $first_operator['5 of:'] = __('5 of', 'monitoring');
     $first_operator['6 of:'] = __('6 of', 'monitoring');
     $first_operator['7 of:'] = __('7 of', 'monitoring');
     $first_operator['8 of:'] = __('8 of', 'monitoring');
     $first_operator['9 of:'] = __('9 of', 'monitoring');
     $first_operator['10 of:'] = __('10 of', 'monitoring');
     Dropdown::showFromArray('operator', $first_operator, array("value" => $this->fields['operator']));
     echo "</td>";
     if ($items_id != '') {
         echo "<td colspan='2'>";
         if (Session::haveRight("plugin_monitoring_servicescatalog", CREATE)) {
             // ** Dropdown to display
             echo "<div style='display:none' id='ressources" . $rand . "' >";
             // Static (a service for an host)
             echo "<table>";
             echo "<tr class='tab_bg_1'>";
             echo "<td>";
             echo "<form name='form' method='post' action='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/businessrule.form.php'>";
             echo "<input type='hidden' name='plugin_monitoring_businessrulegroups_id' value='" . $items_id . "' />";
             echo "<input type='hidden' name='is_generic' value='" . $pmSC->getField('is_generic') . "' />";
             PluginMonitoringBusinessrule::dropdownService(0, array('name' => 'type'));
             echo "<input type='submit' name='add' value=\"" . __('Add') . "\" class='submit'>";
             Html::closeForm();
             echo "</td>";
             echo "</tr>";
             echo "</table>";
             echo "<hr>";
             // Dynamique (all service of component of component catalog)
             echo "<table>";
             echo "<tr class='tab_bg_1'>";
             echo "<td><strong>";
             echo __('Components catalog', 'monitoring');
             echo ' + ';
             echo __('Component', 'monitoring');
             echo " (" . __('Dynamic', 'monitoring') . ")";
             echo " :</strong></td>";
             echo "</tr>";
             echo "<tr class='tab_bg_1'>";
             echo "<td>";
             echo "<form name='form' method='post' action='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/businessrule_component.form.php'>";
             echo "<input type='hidden' name='plugin_monitoring_businessrulegroups_id' value='" . $items_id . "' />";
             $options = array('toupdate' => array('value_fieldname' => 'plugin_monitoring_componentscalalog_id', 'to_update' => "componentdropdown" . $rand, 'url' => $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/dropdownComponent.php", 'moreparams' => array()));
             Dropdown::show('PluginMonitoringComponentscatalog', $options);
             echo '<div id="componentdropdown' . $rand . '"></div>';
             //PluginMonitoringBusinessrule::dropdownService(0, array('name' => 'type'));
             echo "<input type='submit' name='add' value=\"" . __('Add') . "\" class='submit'>";
             Html::closeForm();
             echo "</td>";
             echo "</tr>";
             echo "</table>";
             echo "<hr>";
             echo "</div>";
         }
         $pmBusinessrule = new PluginMonitoringBusinessrule();
         $pmService = new PluginMonitoringService();
         $a_services = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $items_id . "'" . " AND `is_dynamic`='0'");
         if (count($a_services) > 0) {
             echo "<strong>" . __('Static hosts', 'monitoring') . " :</strong>";
             echo "<table width='100%'>";
             foreach ($a_services as $gdata) {
                 if ($pmService->getFromDB($gdata['plugin_monitoring_services_id'])) {
                     $shortstate = $pmService->getShortState();
                     echo "<tr class='tab_bg_1'>";
                     echo "<td>";
                     echo "<img src='" . $pmService->getShortState(array('image' => '32')) . "'/>";
                     echo "</td>";
                     echo "<td>";
                     echo $pmService->getLink();
                     echo "</td>";
                     echo "<td>";
                     echo "<input type='submit' name='deletebusinessrules-" . $gdata['id'] . "' value=\"" . _sx('button', 'Delete permanently') . "\" class='submit'>";
                     echo "</td>";
                     echo "</tr>";
                 } else {
                     // resource deleted
                     echo "<tr class='tab_bg_1'>";
                     echo "<td colspan='2' bgcolor='#ff0000'>";
                     echo __('Resource deleted', 'monitoring');
                     echo "</td>";
                     echo "<td>";
                     echo "<input type='submit' name='deletebusinessrules-" . $gdata['id'] . "' value=\"" . __('Clean') . "\" class='submit'>";
                     echo "</td>";
                     echo "</tr>";
                 }
             }
             echo "</table>";
             echo "<hr/>";
         }
         $a_br_components = $pmBusinessrule_component->find("`plugin_monitoring_businessrulegroups_id`='" . $items_id . "'");
         $pmComponentscatalog_Component = new PluginMonitoringComponentscatalog_Component();
         $pmComponentscatalog = new PluginMonitoringComponentscatalog();
         $pmComponent = new PluginMonitoringComponent();
         if (count($a_br_components) > 0) {
             echo "<strong>" . __('Dynamic hosts', 'monitoring') . " :</strong>";
             echo "<table width='100%'>";
             foreach ($a_br_components as $a_br_component) {
                 echo "<tr class='tab_bg_1'>";
                 echo "<td>";
                 $pmComponentscatalog_Component->getFromDB($a_br_component['plugin_monitoring_componentscatalogs_components_id']);
                 $pmComponentscatalog->getFromDB($pmComponentscatalog_Component->fields['plugin_monitoring_componentscalalog_id']);
                 echo $pmComponentscatalog->getLink();
                 echo ' > ';
                 $pmComponent->getFromDB($pmComponentscatalog_Component->fields['plugin_monitoring_components_id']);
                 echo $pmComponent->getLink();
                 echo "</td>";
                 echo "<td>";
                 echo "<input type='submit' name='deletebrcomponents-" . $a_br_component['id'] . "' value=\"" . _sx('button', 'Delete permanently') . "\" class='submit'>";
                 echo "</td>";
                 echo "</tr>";
             }
             echo "</table>";
         }
         if (!($pmSC->fields['is_generic'] && $pmSC->fields['is_recursive'])) {
             echo "<table width='100%'>";
             $a_services = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $items_id . "'" . " AND `is_dynamic`='1'");
             foreach ($a_services as $gdata) {
                 $pmService->getFromDB($gdata["plugin_monitoring_services_id"]);
                 $shortstate = $pmService->getShortState();
                 echo "<tr class='tab_bg_1'>";
                 echo "<td width='130'>&nbsp;";
                 echo "</td>";
                 echo "<td>";
                 echo "<img src='" . $pmService->getShortState(array('image' => '32')) . "'/>";
                 echo "</td>";
                 echo "<td>";
                 $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
                 $pmComponentscatalog_Host->getFromDB($pmService->fields['plugin_monitoring_componentscatalogs_hosts_id']);
                 echo $pmService->getLink();
                 echo "</td>";
                 echo "</tr>";
             }
             echo "</table>";
         } else {
             echo "<strong>" . __('Dynamic hosts list will be defined during Shinken configuration build.', 'monitoring') . "</strong>";
         }
     }
     echo "</td>";
     echo "</tr>";
     $this->showFormButtons($options);
     return true;
 }
 function generateSyntheseReport($array)
 {
     global $DB;
     $end_date = $array[$array['reporttype'] . 'date_end'];
     $end_date_timestamp = strtotime($end_date);
     $number = $array[$array['reporttype'] . 'number'];
     $period = $array[$array['reporttype'] . 'period'];
     $componentscatalogs_id = $array['componentscatalogs_id'];
     $pmComponent = new PluginMonitoringComponent();
     $pmUnavaibility = new PluginMonitoringUnavaibility();
     $pmServiceevent = new PluginMonitoringServiceevent();
     PluginMonitoringReport::beginCapture();
     $a_groups = array("avaibility");
     foreach ($array['perfname'] as $perfname) {
         $a_groups[] = $perfname;
     }
     $a_groups = array_unique($a_groups);
     foreach ($a_groups as $groupname) {
         foreach ($array['components_id'] as $components_id) {
             $pmComponent->getFromDB($components_id);
             echo "<table class='tab_cadre_fixe'>";
             echo '<tr class="tab_bg_1">';
             echo '<th colspan="' . (3 + $number * 2) . '">';
             echo $pmComponent->getName() . " / ";
             if ($groupname == 'avaibility') {
                 echo __('Avaibility', 'monitoring');
             } else {
                 echo $groupname;
             }
             echo '</th>';
             echo '</tr>';
             echo '<tr class="tab_bg_1">';
             echo '<th>';
             echo __('Name');
             echo '</th>';
             echo '<th>';
             echo __('Entity');
             echo '</th>';
             echo '<th>';
             echo __('Itemtype');
             echo '</th>';
             for ($i = $number; $i >= 1; $i--) {
                 echo '<th colspan="2">';
                 echo Html::convDate(date('Y-m-d', strtotime("-" . $i . " " . $period, $end_date_timestamp)));
                 echo "<br/>";
                 echo Html::convDate(date('Y-m-d', strtotime("-" . ($i - 1) . " " . $period, $end_date_timestamp)));
                 echo '</th>';
             }
             echo '</tr>';
             $query = "SELECT `glpi_plugin_monitoring_componentscatalogs_hosts`.*, \n                  `glpi_plugin_monitoring_services`.`id` as sid FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               LEFT JOIN `glpi_plugin_monitoring_services`\n                  ON `glpi_plugin_monitoring_componentscatalogs_hosts`.`id`=`plugin_monitoring_componentscatalogs_hosts_id`\n               WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'\n                  AND `plugin_monitoring_components_id`='" . $components_id . "'";
             $result = $DB->query($query);
             $rownb = true;
             while ($data = $DB->fetch_array($result)) {
                 $itemtype = $data['itemtype'];
                 $item = new $itemtype();
                 $item->getFromDB($data['items_id']);
                 if ($groupname == 'avaibility') {
                     $a_times = $pmUnavaibility->parseEvents($data['id'], '', date('Y-m-d', strtotime("-" . ($number + 1) . " " . $period, $end_date_timestamp)), date('Y-m-d', strtotime("-" . $number . " " . $period, $end_date_timestamp)));
                     $previous_value = round(($a_times[1] - $a_times[0]) / $a_times[1] * 100, 3);
                 } else {
                     $previous_value = 0;
                 }
                 echo '<tr class="tab_bg_1' . (($rownb = !$rownb) ? '_2' : '') . '">';
                 echo '<td>';
                 echo $item->getName();
                 echo '</td>';
                 echo '<td>';
                 echo Dropdown::getDropdownName("glpi_entities", $item->fields['entities_id']);
                 echo '</td>';
                 echo '<td>';
                 echo $item->getTypeName();
                 echo '</td>';
                 for ($i = $number; $i >= 1; $i--) {
                     echo '<td>';
                     $startdatet = date('Y-m-d', strtotime("-" . $i . " " . $period, $end_date_timestamp));
                     $enddatet = date('Y-m-d', strtotime("-" . ($i - 1) . " " . $period, $end_date_timestamp));
                     if ($groupname == 'avaibility') {
                         $a_times = $pmUnavaibility->parseEvents($data['id'], '', $startdatet, $enddatet);
                         $value = round(($a_times[1] - $a_times[0]) / $a_times[1] * 100, 3);
                         echo $value . "%";
                     } else {
                         $queryevents = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                        WHERE `plugin_monitoring_services_id`='" . $data['sid'] . "'\n                           AND `date` >= '" . $startdatet . "'\n                           AND `date` <= '" . $enddatet . "'\n                        ORDER BY `date`";
                         $resultevents = $DB->query($queryevents);
                         $ret = $pmServiceevent->getData($resultevents, $pmComponent->fields['graph_template']);
                         $value = round(array_sum($ret[0][$groupname]) / count($ret[0][$groupname]), 3);
                         echo $value;
                     }
                     echo '</td>';
                     echo '<td>';
                     if ($previous_value < $value) {
                         echo '<img src="../pics/arrow-up-right.png" width="16" />';
                     } else {
                         if ($previous_value == $value) {
                             echo '<img src="../pics/arrow-right.png" width="16" />';
                         } else {
                             if ($previous_value > $value) {
                                 echo '<img src="../pics/arrow-down-right.png" width="16" />';
                             }
                         }
                     }
                     $previous_value = $value;
                     echo '</td>';
                 }
                 echo "</tr>";
             }
             echo "</table>";
         }
         echo "<br/><br/>";
     }
     $content = PluginMonitoringReport::endCapture();
     PluginMonitoringReport::generatePDF($content, 'L');
 }
  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author
  @comment
  @copyright Copyright (c) 2011-2014 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
Session::checkLoginUser();
$docDir = GLPI_PLUGIN_DOC_DIR . '/monitoring';
if (isset($_GET['file'])) {
    $filename = $_GET['file'];
    $file = $docDir . '/' . $filename;
    if (preg_match("/PluginMonitoringService-([0-9]+)-2h([0-9]+).png/", $filename)) {
        include GLPI_ROOT . "/inc/includes.php";
        $match = array();
        preg_match("/PluginMonitoringService-([0-9]+)-2h([0-9]+).png/", $filename, $match);
        $pmServicegraph = new PluginMonitoringServicegraph();
        $pmService = new PluginMonitoringService();
        $pmComponent = new PluginMonitoringComponent();
        $pmService->getFromDB($match[1]);
        $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
        $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $match[1], $match[2], '2h');
    }
    Toolbox::sendFile($file, $filename);
}
}
if (isset($_GET['components_id']) && !isset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']])) {
    PluginMonitoringToolbox::loadPreferences($_GET['components_id']);
}
if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']])) {
    echo json_encode(array());
    //   echo __('No data ...', 'monitoring');
    exit;
}
if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']][''])) {
    unset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']]['']);
}
$a_ret = $pmServicegraph->generateData($_GET['rrdtool_template'], $_GET['itemtype'], $_GET['items_id'], $_GET['timezone'], $_GET['time'], $enddate, $_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']]);
$mydatat = $a_ret[0];
$a_labels = $a_ret[1];
$pmComponent = new PluginMonitoringComponent();
$pmCommand = new PluginMonitoringCommand();
$pmComponent->getFromDB($_GET['components_id']);
$pmCommand->getFromDB($pmComponent->fields['plugin_monitoring_commands_id']);
$a_data = array();
$a_values = array();
$lab = '';
$num = 1;
$a_names = array();
$formaty = ".0f";
$max = 0;
foreach ($mydatat as $name => $data) {
    if (!isset($a_names[$name])) {
        $a_names[$name] = $num;
        $num++;
    }
 static function getTimeBetween2Checks($components_id)
 {
     $pmComponent = new PluginMonitoringComponent();
     $pmCheck = new PluginMonitoringCheck();
     $pmComponent->getFromDB($components_id);
     $pmCheck->getFromDB($pmComponent->fields['plugin_monitoring_checks_id']);
     $timeMinutes = $pmCheck->fields['check_interval'];
     $timeSeconds = $timeMinutes * 60;
     return $timeSeconds;
 }
   function showWidget($id, $time) {
      global $DB, $CFG_GLPI;

      $pmComponent = new PluginMonitoringComponent();

      if ($this->getFromDB($id)) {
         $pmComponent->getFromDB($this->fields['plugin_monitoring_components_id']);

         $pmServicegraph = new PluginMonitoringServicegraph();
         ob_start();
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'],
                                       "PluginMonitoringService",
                                       $id,
                                       "0",
                                       $time,
                                       "div",
                                       "475");
         $chart = ob_get_contents();
         ob_end_clean();
         return $chart;
      }
   }
  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
Session::checkCentralAccess();
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "display");
if (isset($_POST['sessionupdate'])) {
    $_SESSION['glpi_plugin_monitoring']['_refresh'] = $_POST['_refresh'];
    Html::back();
    exit;
}
if (isset($_POST["plugin_monitoring_timezone"])) {
    $_SESSION['plugin_monitoring_timezone'] = $_POST["plugin_monitoring_timezone"];
    Html::back();
}
if (isset($_POST['updateperfdata'])) {
    $pmComponent = new PluginMonitoringComponent();
    if (isset($_POST["perfnameinvert"])) {
        $itemtype = $_GET['itemtype'];
        $items_id = $_GET['items_id'];
        $item = new $itemtype();
        $item->getFromDB($items_id);
        $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
        $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$pmComponent->fields['id']] = array();
        $_POST['perfnameinvert'] = explode("####", $_POST['perfnameinvert']);
        foreach ($_POST["perfnameinvert"] as $perfname) {
            $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$pmComponent->fields['id']][$perfname] = "checked";
        }
    }
    if (isset($_POST["perfnamecolor"])) {
        $itemtype = $_GET['itemtype'];
        $items_id = $_GET['items_id'];
Beispiel #18
0
  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2013 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
PluginMonitoringProfile::checkRight("component", "w");
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "components");
$pMonitoringComponent = new PluginMonitoringComponent();
if (isset($_POST["copy"])) {
    $pMonitoringComponent->showForm(0, array(), $_POST);
    Html::footer();
    exit;
} else {
    if (isset($_POST["add"])) {
        if (isset($_POST['arg'])) {
            $_POST['arguments'] = exportArrayToDB($_POST['arg']);
        }
        if (empty($_POST['name']) or empty($_POST['plugin_monitoring_checks_id']) or empty($_POST['plugin_monitoring_commands_id']) or empty($_POST['calendars_id'])) {
            $_SESSION['plugin_monitoring_components'] = $_POST;
            Session::addMessageAfterRedirect("<font class='red'>" . __('Fields with asterisk are required', 'monitoring') . "</font>");
            Html::back();
        }
        if ($_POST['graph_template'] != '') {
 function showDefineDataOfGauge($components_id, $a_path = array(), $deletebutton = FALSE)
 {
     if (!isset($this->fields) || !isset($this->fields['aggregate_items']) || $this->fields['aggregate_items'] == '') {
         $this->getEmpty();
     }
     $pmComponent = new PluginMonitoringComponent();
     $pmComponent->getFromDB($components_id);
     $perfdetail = getAllDatasFromTable('glpi_plugin_monitoring_perfdatadetails', "`plugin_monitoring_perfdatas_id`='" . $pmComponent->fields['graph_template'] . "'");
     $elements = array();
     foreach ($perfdetail as $perfdata) {
         for ($i = 1; $i <= 15; $i++) {
             if ($perfdata['dsname' . $i] != '') {
                 $elements[$perfdata['id'] . "/" . $i] = $perfdata['dsname' . $i];
             }
         }
     }
     echo "<table>";
     echo "<tr>";
     echo "<td>";
     echo __('Value', 'monitoring');
     echo " : </td>";
     echo "<td>";
     $value = '';
     if ($this->fields['aggregate_items'] != '') {
         $aggregate_items = importArrayFromDB($this->fields['aggregate_items']);
         $value = $aggregate_items[$a_path['a']]["id" . $a_path['b']][$a_path['c']]["id" . $a_path['d']][$a_path['num']]['perfdatadetails_id'] . '/' . $aggregate_items[$a_path['a']]["id" . $a_path['b']][$a_path['c']]["id" . $a_path['d']][$a_path['num']]['perfdatadetails_dsname'];
     }
     Dropdown::showFromArray('item', $elements, array('value' => $value));
     echo "</td>";
     if ($deletebutton) {
         echo "<td rowspan='4'>";
         echo "<form name='form2' method='post' action=''>";
         echo "<input type='hidden' name='id' value='" . $a_path['id'] . "' />";
         echo "<input type='hidden' name='delete_item' value='" . $a_path['a'] . "|id" . $a_path['b'] . "|" . $a_path['c'] . "|id" . $a_path['d'] . "|" . $a_path['num'] . "' />";
         echo "<input type='submit' class='submit' name='delete' value='" . _sx('button', 'Delete permanently') . "' />";
         Html::closeForm();
         echo "</td>";
     }
     echo "</tr>";
     echo "<tr>";
     echo "<td>";
     echo __('Warning', 'monitoring');
     echo " : </td>";
     echo "<td>";
     $used = '';
     $other = '75';
     if (is_numeric($this->fields['aggregate_warn'])) {
         $used = $this->fields['aggregate_warn'];
         $other = $used;
     } else {
         if ($this->fields['aggregate_warn'] == '') {
             $used = '';
         } else {
             $used = $this->fields['aggregate_warn'][$a_path['a']][$a_path['b']][$a_path['c']][$a_path['d']][$a_path['num']];
         }
     }
     Dropdown::showFromArray('warn', $elements, array('other' => $other, 'used' => $used));
     echo "</td>";
     echo "</tr>";
     echo "<tr>";
     echo "<td>";
     echo __('Critical', 'monitoring');
     echo " : </td>";
     echo "<td>";
     $used = '';
     $other = '90';
     if (is_numeric($this->fields['aggregate_crit'])) {
         $used = $this->fields['aggregate_crit'];
         $other = $used;
     } else {
         if ($this->fields['aggregate_crit'] == '') {
             $used = '';
         } else {
             $used = $this->fields['aggregate_crit'][$a_path['a']][$a_path['b']][$a_path['c']][$a_path['d']][$a_path['num']];
         }
     }
     Dropdown::showFromArray('crit', $elements, array('other' => $other, 'used' => $used));
     echo "</td>";
     echo "</tr>";
     echo "<tr>";
     echo "<td>";
     echo __('Limit (max)', 'monitoring');
     echo " : </td>";
     echo "<td>";
     $used = '';
     $other = '100';
     if (is_numeric($this->fields['aggregate_limit'])) {
         $used = $this->fields['aggregate_limit'];
         $other = $used;
     } else {
         if ($this->fields['aggregate_limit'] == '') {
             $used = '';
         } else {
             $used = $this->fields['aggregate_limit'][$a_path['a']][$a_path['b']][$a_path['c']][$a_path['d']][$a_path['num']];
         }
     }
     Dropdown::showFromArray('limit', $elements, array('other' => $other, 'used' => $used));
     echo "</td>";
     echo "</tr>";
     echo "</table>";
 }
Beispiel #20
0
 function generateAllGraphs($weathermaps_id)
 {
     global $DB;
     $pmServicegraph = new PluginMonitoringServicegraph();
     $pmComponent = new PluginMonitoringComponent();
     $cache = array();
     $query = "SELECT * FROM `glpi_plugin_monitoring_weathermaplinks`\n         LEFT JOIN `glpi_plugin_monitoring_weathermapnodes` \n            ON `glpi_plugin_monitoring_weathermapnodes`.`id`=`plugin_monitoring_weathermapnodes_id_1`\n         LEFT JOIN `glpi_plugin_monitoring_services` \n            ON `glpi_plugin_monitoring_services`.`id`=`plugin_monitoring_services_id`\n         WHERE `plugin_monitoring_weathermaps_id`='" . $weathermaps_id . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $graph_template = '';
         if (isset($cache[$data['plugin_monitoring_components_id']])) {
             $graph_template = $cache[$data['plugin_monitoring_components_id']];
         } else {
             $pmComponent->getFromDB($data['plugin_monitoring_components_id']);
             $cache[$data['plugin_monitoring_components_id']] = $pmComponent->fields['graph_template'];
             $graph_template = $pmComponent->fields['graph_template'];
         }
         $pmServicegraph->displayGraph($graph_template, "PluginMonitoringService", $data['plugin_monitoring_services_id'], 0, '2h');
     }
 }
Beispiel #21
0
   function slideSlider($id) {
      global $CFG_GLPI, $DB;

      echo "<script type='text/javascript'>
         function fittext(itemid) {
            document.getElementById(itemid).style.fontSize = '50px';
            var fontsize = 50;
            while(document.getElementById(itemid).offsetWidth > 120) {
               fontsize--;
               if (fontsize > 20) {
                  fontsize--;
               }
               document.getElementById(itemid).style.fontSize = fontsize + 'px';
            }
            while(document.getElementById(itemid).offsetHeight > 67) {
               fontsize--;
               document.getElementById(itemid).style.fontSize = fontsize + 'px';
            }
            if (fontsize > 30) {
               document.getElementById(itemid).style.fontSize = '30px';
            }
            if (fontsize < 7) {
               document.getElementById(itemid).style.fontSize = '7px';
            }
         }
      </script>";
      PluginMonitoringToolbox::loadLib();

      $this->getFromDB($id);
      echo '<div id="custom_date" style="display:none"></div>';
      echo '<div id="custom_time" style="display:none"></div>';

      echo '<script src="'.$CFG_GLPI["root_doc"].'/plugins/monitoring/lib/slider.js-14/js/jssor.slider.mini.js"></script>
<script>
    jQuery(document).ready(function ($) {
        //Define an array of slideshow transition code
        var _SlideshowTransitions = [
        {$Duration:0001,$Opacity:2}
        ];
        var options = {
            $AutoPlay: true,
            $AutoPlayInterval: '.$this->fields['duration'].'000,
            $SlideshowOptions: {
                    $Class: $JssorSlideshowRunner$,
                    $Transitions: _SlideshowTransitions,
                    $TransitionsOrder: 1,
                    $ShowLink: true
        }
        };
        var jssor_slider1 = new $JssorSlider$(\'slider1_container\', options);
    });
</script>';
      echo "<table class='tab_cadre'>";

      echo "<tr>";
      echo "<td>";

      $query = "SELECT * FROM `glpi_plugin_monitoring_sliders_items`
              WHERE `plugin_monitoring_sliders_id`='".$id."'";

      $result = $DB->query($query);
      $maxWidth = 0;
      $maxHeight = 0;
      $is_minemap = 0;
      while ($data=$DB->fetch_array($result)) {
         if ($data['itemtype'] == 'PluginMonitoringServicescatalog'
                 || $data['itemtype'] == 'PluginMonitoringComponentscatalog'
                 || $data['itemtype'] == 'PluginMonitoringCustomitem_Gauge'
                 || $data['itemtype'] == 'PluginMonitoringCustomitem_Counter') {
            if ($maxWidth < 180) {
               $maxWidth = 180;
            }
            if ($maxHeight < 180) {
               $maxHeight = 180;
            }
            if ($data['is_minemap'] == 1) {
               $is_minemap = 1;
            }
         } else if ($data['itemtype'] == 'PluginMonitoringService') {
            if ($maxWidth < 475) {
               $maxWidth = 475;
            }
            if ($maxHeight < 330) {
               $maxHeight = 330;
            }
         } else if ($data['itemtype'] == "PluginMapsMap") {
            if ($maxWidth < 950) {
               $maxWidth = 950;
            }
            if ($maxHeight < 800) {
               $maxHeight = 800;
            }
         } else {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            if ($maxWidth < $item->fields['width']) {
               $maxWidth = $item->fields['width'];
            }
            if (isset($item->fields['height'])) {
               if ($maxHeight < $item->fields['width']) {
                  $maxHeight = $item->fields['height'];
               }
            }
         }
      }
      if ($is_minemap) {
         $maxHeight = '1500';
      }

      $pm = new PluginMonitoringComponentscatalog();
      echo '<div id="slider1_container" style="position: relative;
top: 0px; left: 0px; width: '.$maxWidth.'px; height: '.$maxHeight.'px;">
    <!-- Slides Container -->
    <div u="slides" style="cursor: move; position: absolute; overflow: hidden;
    left: 0px; top: 0px; width: '.$maxWidth.'px; height: '.$maxHeight.'px;">';

      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         if ($itemtype == "PluginMonitoringService") {
            echo '<div>';
            echo $item->showWidget($data['items_id'], $data['extra_infos']);
            echo '</div>';
         } else if ($itemtype == "PluginMonitoringWeathermap") {
            echo '<div>';
            echo '<div id="weathermap-'.$data['items_id'].'"></div>';
            echo '</div>';
         } else if ($itemtype == 'PluginMonitoringDisplayview') {
            echo '<div>';
            $pmDisplayview_item = new PluginMonitoringDisplayview_item();
            echo $pmDisplayview_item->view($data['items_id']);
            echo '</div>';
         } else if ($itemtype == "PluginMapsMap") {
            echo '<div>';
            echo '<div id="pluginmap"></div>';
            echo '</div>';
         } else {
            echo '<div>';
            echo $item->showWidget($data['items_id']);
            echo '</div>';
         }

      }
echo '    </div>
</div>';
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         // Ajax
         if ($itemtype == "PluginMonitoringService") {
            $pmComponent = new PluginMonitoringComponent();
            $item = new $itemtype();

            $item->getFromDB($data['items_id']);
            $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
            $pmServicegraph = new PluginMonitoringServicegraph();
            $pmServicegraph->displayGraph($pmComponent->fields['graph_template'],
                                          "PluginMonitoringService",
                                          $data['items_id'],
                                          "0",
                                          $data['extra_infos'],
                                          "js");
         } else if($itemtype == "PluginMonitoringComponentscatalog") {
            $pmComponentscatalog = new PluginMonitoringComponentscatalog();
            $pmComponentscatalog->ajaxLoad($data['items_id'], $data['is_minemap']);
         } else if($itemtype == "PluginMonitoringServicescatalog") {
            $pmServicescatalog = new PluginMonitoringServicescatalog();
            $pmServicescatalog->ajaxLoad($data['items_id']);
         } else if($itemtype == "PluginMonitoringDisplayview") {

         } else if($itemtype == "PluginMonitoringCustomitem_Gauge") {
            $pmCustomitem_Gauge = new PluginMonitoringCustomitem_Gauge();
            $pmCustomitem_Gauge->ajaxLoad($data['items_id']);
         } else if($itemtype == "PluginMonitoringCustomitem_Counter") {
            $pmCustomitem_Counter = new PluginMonitoringCustomitem_Counter();
            $pmCustomitem_Counter->ajaxLoad($data['items_id']);
         }
         if ($itemtype == "PluginMonitoringWeathermap") {
            $sess_id = session_id();
            PluginMonitoringSecurity::updateSession();

            echo "<script type='text/javascript'>
            var mgr = new Ext.UpdateManager('weathermap-".$data['items_id']."');
            mgr.startAutoRefresh(50, \"".$CFG_GLPI["root_doc"].
                    "/plugins/monitoring/ajax/widgetWeathermap.php\","
                    . " \"id=".$data['items_id']."&extra_infos=".
                    $data['extra_infos']."&sess_id=".$sess_id.
                    "&glpiID=".$_SESSION['glpiID'].
                    "&plugin_monitoring_securekey=".$_SESSION['plugin_monitoring_securekey'].
                    "\", \"\", true);
            </script>";
         }
         if ($itemtype == "PluginMapsMap") {
            $sess_id = session_id();
            PluginMonitoringSecurity::updateSession();

            echo "<script type='text/javascript'>
            var mgr = new Ext.UpdateManager('pluginmap');
            mgr.startAutoRefresh(50, \"".$CFG_GLPI["root_doc"].
                    "/plugins/monitoring/ajax/widgetPluginmap.php\","
                    . " \"extra_infos=".
                    $data['extra_infos']."&sess_id=".$sess_id.
                    "&glpiID=".$_SESSION['glpiID'].
                    "&plugin_monitoring_securekey=".$_SESSION['plugin_monitoring_securekey'].
                    "\", \"\", true);
            </script>";
         }
      }
      echo "</td>";
      echo "</tr>";
      echo "</table>";
   }
 function showComponents($componentscatalogs_id)
 {
     global $DB, $LANG, $CFG_GLPI;
     $this->addComponent($componentscatalogs_id);
     $rand = mt_rand();
     $pmComponent = new PluginMonitoringComponent();
     $pmCommand = new PluginMonitoringCommand();
     $pmCheck = new PluginMonitoringCheck();
     $calendar = new Calendar();
     echo "<form method='post' name='componentscatalog_component_form{$rand}' id='componentscatalog_component_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/front/componentscatalog_component.form.php\">";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th>";
     echo $LANG['plugin_monitoring']['component'][2];
     echo "</th>";
     echo "</tr>";
     echo "</table>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th width='10'>&nbsp;</th>";
     echo "<th>" . $LANG['common'][16] . "</th>";
     echo "<th>" . $LANG['plugin_monitoring']['command'][2] . "</th>";
     echo "<th>" . $LANG['plugin_monitoring']['check'][0] . "</th>";
     echo "<th>" . $LANG['plugin_monitoring']['host'][9] . "</th>";
     echo "<th>" . $LANG['plugin_monitoring']['service'][8] . "</th>";
     echo "</tr>";
     $used = array();
     $query = "SELECT * FROM `" . $this->getTable() . "`\n         WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $used[] = $data['plugin_monitoring_components_id'];
         $pmComponent->getFromDB($data['plugin_monitoring_components_id']);
         echo "<tr>";
         echo "<td>";
         echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>";
         echo "</td>";
         echo "<td class='center'>";
         echo $pmComponent->getLink(1);
         echo "</td>";
         echo "<td class='center'>";
         $pmCommand->getFromDB($pmComponent->fields['plugin_monitoring_commands_id']);
         echo $pmCommand->getLink();
         echo "</td>";
         echo "<td class='center'>";
         $pmCheck->getFromDB($pmComponent->fields['plugin_monitoring_checks_id']);
         echo $pmCheck->getLink();
         echo "</td>";
         echo "<td class='center'>";
         $calendar->getFromDB($pmComponent->fields['calendars_id']);
         echo $calendar->getLink();
         echo "</td>";
         echo "<td class='center'>";
         if ($pmComponent->fields['remotesystem'] == '') {
             echo "-";
         } else {
             echo $pmComponent->fields['remotesystem'];
         }
         echo "</td>";
         echo "</tr>";
     }
     openArrowMassive("componentscatalog_host_form{$rand}", true);
     closeArrowMassive('deleteitem', $LANG['buttons'][6]);
     echo "</table>";
 }
   function drawMap($weathermaps_id, $widthw=100, $config=0) {
      global $DB, $CFG_GLPI;

      $this->getFromDB($weathermaps_id);

      PluginMonitoringSecurity::updateSession();

      if (countElementsInTable('glpi_plugin_monitoring_weathermapnodes', "`plugin_monitoring_weathermaps_id`='".$weathermaps_id."'") == 0) {
         return;
      }

      $rand = mt_rand();
      echo '<svg id="cloud'.$rand.'" width="'.$this->fields['width'].'" '
              . 'height="'.$this->fields['height'].'">
  <defs>
    <marker id="arrowhead'.$rand.'" orient="auto" markerWidth="2" markerHeight="4"
            refX="0.3" refY="0.8">
      <path d="M0,0 V1.6 L0.8,0.8 Z" fill="#d0d0d0" />
    </marker>
    <marker id="arrowheadred'.$rand.'" orient="auto" markerWidth="2" markerHeight="4"
            refX="0.3" refY="0.8">
      <path d="M0,0 V1.6 L0.8,0.8 Z" fill="red" />
    </marker>
    <marker id="arrowheadblack'.$rand.'" orient="auto" markerWidth="2" markerHeight="4"
            refX="0.3" refY="0.8">
      <path d="M0,0 V1.6 L0.8,0.8 Z" fill="black" />
    </marker>
  </defs>
        </svg>';

      echo '<script>
      var width = '.$this->fields['width'].';
      var height = '.$this->fields['height'].';

      var color = d3.scale.category10();

      var force'.$rand.' = d3.layout.force()
          .charge(-180)
          .linkDistance(20)
          .size([width, height]);

      var svg'.$rand.' = d3.select("#cloud'.$rand.'");

      var drag_node = d3.behavior.drag()
        .on("drag", dragmove)';
      if ($config) {
         echo '
        .on("dragend", dragendconfig)';
      }

              echo ';


      function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        tick'.$rand.'(); // this is the key to make it work together with updating both px,py,x,y on d !
     }

     function dragendconfig(d, i) {
        $.ajax({type: "POST",url: "'.$CFG_GLPI['root_doc'].'/plugins/monitoring/ajax/updateWeathermap.php",data: {id: d.id, x: d.x, y: d.y},success: function(msg) {}});
     }
              ';


      $a_data = array();
      $a_mapping = array();
      $i = 0;
      $query = "SELECT * FROM `".getTableForItemType("PluginMonitoringWeathermapnode")."`
         WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
         ORDER BY `name`";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $name = $data['name'];
         $url = '';
         if ($name == '') {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            $name = $item->getName();
            $url = $item->getLinkURL();
         }
         $a_mapping[$data['id']] = $i;
         $i++;
         $a_textx = array(
             'middle' => 0,
             'start'  => '12',
             'end'    => '-12');
         $texty = 0;
         if ($data['position'] == 'middle') {
            $texty = -13;
         }
         $a_data['nodes'][] = array(
             'name'  => $name,
             'id'    => (int)$data['id'],
             'x'     => ($widthw * $data['x']) / 100,
             'y'     => ($widthw * $data['y']) / 100,
             'fixed' => TRUE,
             "group" => 3,
             "url"   => $url,
             "textposition" => $data['position'],
             "textx" => $a_textx[$data['position']],
             "texty" => $texty,
             "nodeusage" => 'grey'
         );
      }
      $nodes_upusage = array();

      $pmWeathermapnode = new PluginMonitoringWeathermapnode();
      $pmWeathermaplink = new PluginMonitoringWeathermaplink();
      $pmService = new PluginMonitoringService();
      $pmComponent = new PluginMonitoringComponent();
      $a_data['links'] = array();
      $query = "SELECT `glpi_plugin_monitoring_weathermaplinks`.*
            FROM `glpi_plugin_monitoring_weathermaplinks`
         LEFT JOIN `glpi_plugin_monitoring_weathermapnodes`
            ON `plugin_monitoring_weathermapnodes_id_1` = `glpi_plugin_monitoring_weathermapnodes`.`id`
         WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $pmWeathermapnode->getFromDB($data['plugin_monitoring_weathermapnodes_id_2']);

         if (!$pmService->getFromDB($data['plugin_monitoring_services_id'])) {
            $pmWeathermapnode = new PluginMonitoringWeathermapnode();
            $pmWeathermapnode->getFromDB($data['plugin_monitoring_weathermapnodes_id_1']);
            $querytt = "SELECT glpi_plugin_monitoring_services.id FROM `glpi_plugin_monitoring_services`
               LEFT JOIN glpi_plugin_monitoring_componentscatalogs_hosts
                  ON plugin_monitoring_componentscatalogs_hosts_id=glpi_plugin_monitoring_componentscatalogs_hosts.id
               WHERE  networkports_id>0
                  AND itemtype='".$pmWeathermapnode->fields['itemtype']."'
                  AND items_id='".$pmWeathermapnode->fields['items_id']."'";
            $resulttt = $DB->query($querytt);
            $s_id = 0;
            if ($DB->numrows($resulttt) == 1) {
               $datatt = $DB->fetch_assoc($resulttt);
               $input = array(
                   'id'                            => $data['id'],
                   'plugin_monitoring_services_id' => $datatt['id']
               );
               $pmWeathermaplink->update($input);
               $pmWeathermaplink->getFromDB($data['id']);
               $data = $pmWeathermaplink->fields;
            }
         }

         $queryevent = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
            WHERE `plugin_monitoring_services_id`='".$data['plugin_monitoring_services_id']."'
               ORDER BY `date` DESC
               LIMIT 1";
         $resultevent = $DB->query($queryevent);
         $in = '';
         $out = '';
         $service_exist = 0;
         while ($dataevent=$DB->fetch_array($resultevent)) {
            if ($pmService->getFromDB($data['plugin_monitoring_services_id'])) {
               $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);

               $matches1 = array();
               preg_match("/".$pmComponent->fields['weathermap_regex_in']."/m", $dataevent['perf_data'], $matches1);
               if (isset($matches1[1])) {
                  $in = $matches1[1];
               }
               $matches1 = array();
               preg_match("/".$pmComponent->fields['weathermap_regex_out']."/m", $dataevent['perf_data'], $matches1);
               if (isset($matches1[1])) {
                  $out = $matches1[1];
               }
               $service_exist = 1;
            } else {
               $pmService->getEmpty();
               $pmComponent->getEmpty();
            }
         }
         if ($service_exist) {
            list($downusage, $downcolor) = $this->getWBandwidth($in, $data['bandwidth_in']);
            list($upusage, $upcolor) = $this->getWBandwidth($out, $data['bandwidth_out']);
         } else {
            $upusage = 100;
            $downusage = 100;
            $upcolor = 'black';
            $downcolor = 'black';
         }
         $a_data['links'][] = array(
             'source'    => $a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']],
             'target'    => $a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']],
             'up'        => $upcolor,
             'down'      => $downcolor,
             'upusage'   => $upusage,
             'downusage' => $downusage,
             'info'      => '',
             'value'     => 1,
             'services_id' => $data['plugin_monitoring_services_id'],
             'components_id' => $pmService->fields['plugin_monitoring_components_id'],
             'rrdtool_template' => $pmComponent->fields['graph_template']
         );
         if (!isset($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']]])) {
            $nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']]] = array();
         }
         if (!isset($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']]])) {
            $nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']]] = array();
         }
         array_push($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_1']]], $upusage);
         array_push($nodes_upusage[$a_mapping[$data['plugin_monitoring_weathermapnodes_id_2']]], $downusage);
      }

      foreach ($nodes_upusage as $nodes_num=>$datausage) {
         $moyusage = array_sum($datausage)/count($datausage);
         list($usage, $color) = $this->getWBandwidth(array_sum($datausage)/count($datausage), 100);
         if ($moyusage == 0) {
            $color = 'grey';
         }
         $a_data['nodes'][$nodes_num]['nodeusage'] = $color;
      }

      echo 'var jsonstr'.$rand.' = \''.json_encode($a_data).'\';';
      echo 'var json'.$rand.' = JSON.parse(jsonstr'.$rand.');
      force'.$rand.'
        .nodes(json'.$rand.'.nodes)
        .links(json'.$rand.'.links)
        .start();

     ';

      $this->d3jsLink('up', 'usage', $rand);
      $this->d3jsLink('up', 'notusage', $rand);
      $this->d3jsLink('down', 'usage', $rand);
      $this->d3jsLink('down', 'notusage', $rand);

      echo '    var nodes'.$rand.' = svg'.$rand.'.selectAll(".node")
        .data(force'.$rand.'.nodes())
      .enter().append("g")
        .attr("class", "node")
        .call(drag_node)
      .append("a")
        .attr("xlink:href", function (d) { return d.url; })
        .attr("target", "_blank");

//      .on("dragend", function(d){$.ajax({url: "toto",success: function(data) {}})});
//d3.select(this).style("fill", "white");}


    nodes'.$rand.'.append("circle")
       .attr("r", 5)
       .attr("class", function(d) { return "circle" + d.nodeusage; });


    nodes'.$rand.'.append("text")
       .attr("text-anchor", function(d) { return d.textposition; })
       .attr("x", function(d) { return d.textx; })
       .attr("y", function(d) { return d.texty; })
       .attr("dy", ".35em")
       .attr("class", "linklabel")
      .text(function(d) { return d.name; });

   var textdown'.$rand.' = svg'.$rand.'.selectAll("line.link")
       .data(force'.$rand.'.links())
    .enter().append("text")
       .attr("dy", ".25em")
       .attr("text-anchor", "middle")
       .style("pointer-events", "none")
       .attr("class", function(d) { return "linklabel" + d.down;})
       .text(function(d) { return d.downusage + "%";})

   var textup'.$rand.' = svg'.$rand.'.selectAll("line.link")
       .data(force'.$rand.'.links())
    .enter().append("text")
       .attr("dy", ".25em")
       .attr("text-anchor", "middle")
       .style("pointer-events", "none")
       .attr("class", function(d) { return "linklabel" + d.up;})
       .text(function(d) { return d.upusage + "%";})

    force'.$rand.'.on("tick", tick'.$rand.');

    function tick'.$rand.'() {
        linksupusage'.$rand.'.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * ((d.upusage * 97) / 100)); })
            .attr("y2", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * ((d.upusage * 97) / 100)); });

        linksupnotusage'.$rand.'.attr("x1", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * ((d.upusage * 97) / 100)); })
            .attr("y1", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * ((d.upusage * 97) / 100)); })
            .attr("x2", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * 97); })
            .attr("y2", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * 97); });

        linksdownusage'.$rand.'.attr("x1", function(d) { return d.target.x; })
            .attr("y1", function(d) { return d.target.y; })
            .attr("x2", function(d) { return d.source.x + Math.round(((d.target.x - d.source.x) / 200) * (200 - ((d.downusage * 97) / 100))); })
            .attr("y2", function(d) { return d.source.y + Math.round(((d.target.y - d.source.y) / 200) * (200 - ((d.downusage * 97) / 100))); });

        linksdownnotusage'.$rand.'.attr("x1", function(d) { return d.source.x + Math.round(((d.target.x - d.source.x) / 200) * (200 - ((d.downusage * 97) / 100))); })
            .attr("y1", function(d) { return d.source.y + Math.round(((d.target.y - d.source.y) / 200) * (200 - ((d.downusage * 97) / 100))); })
            .attr("x2", function(d) { return d.source.x + Math.round(((d.target.x - d.source.x) / 200) * 103); })
            .attr("y2", function(d) { return d.source.y + Math.round(((d.target.y - d.source.y) / 200) * 103); });

        nodes'.$rand.'
            .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
';

         echo '
   textdown'.$rand.'.attr("x", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * 130); })
      .attr("y", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * 130); });


   textup'.$rand.'.attr("x", function(d) { return d.source.x + (((d.target.x - d.source.x) / 200) * 70); })
      .attr("y", function(d) { return d.source.y + (((d.target.y - d.source.y) / 200) * 70); });

     };
';

echo '        </script>';


   }
 static function loadPreferences($components_id)
 {
     $pmComponent = new PluginMonitoringComponent();
     $pmComponent->getFromDB($components_id);
     $_SESSION['glpi_plugin_monitoring']['perfname'][$components_id] = array();
     $a_perfname = importArrayFromDB($pmComponent->fields['perfname']);
     foreach ($a_perfname as $perfname => $active) {
         $_SESSION['glpi_plugin_monitoring']['perfname'][$components_id][$perfname] = 'checked';
     }
     $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$components_id] = array();
     $a_perfnameinvert = importArrayFromDB($pmComponent->fields['perfnameinvert']);
     foreach ($a_perfnameinvert as $perfname => $active) {
         $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$components_id][$perfname] = 'checked';
     }
     $_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$components_id] = array();
     $a_perfnamecolor = importArrayFromDB($pmComponent->fields['perfnamecolor']);
     foreach ($a_perfnamecolor as $perfname => $color) {
         $_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$components_id][$perfname] = $color;
     }
 }
   function generateData($rrdtool_template, $itemtype, $items_id, $timezone, $time, $enddate='', $todisplay=array()) {
      global $DB;

      if ($enddate == '') {
         $enddate = date('U');
      }

      // Manage timezones
      $converttimezone = '0';
      if (strstr($timezone, '-')) {
         $timezone_temp = str_replace("-", "", $timezone);
         $converttimezone = ($timezone_temp * 3600);
         $timezone = str_replace("-", "+", $timezone);
      } else if (strstr($timezone, '+')) {
         $timezone_temp = str_replace("+", "", $timezone);
         $converttimezone = ($timezone_temp * 3600);
         $timezone = str_replace("+", "-", $timezone);
      }

      // ** Get in table serviceevents
      $mydatat = array();
      $a_labels = array();
      $a_ref = array();
      $pmServiceevent = new PluginMonitoringServiceevent();
      $pmService = new PluginMonitoringService();
      $pmService->getFromDB($items_id);

      $_SESSION['plugin_monitoring_checkinterval'] = PluginMonitoringComponent::getTimeBetween2Checks($pmService->fields['plugin_monitoring_components_id']);

      $dateformat = "%Y-%m-%d %Hh";

      $begin = '';
      switch ($time) {

         case '2h':
            $begin = date('Y-m-d H:i:s', $enddate - (2 * 3600));
            $timecomplete = 0;
            $dateformat = "(%d)%H:%M";
            if (date('m', $enddate) != date('m', $enddate - (2 * 3600))) {
               $timecomplete = 2;
               $dateformat = "%m-%d %H:%M";
            }

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = array();
            if (isset($this->jsongraph_a_ref[$rrdtool_template])) {
               $ret = $pmServiceevent->getData(
                       $result,
                       $rrdtool_template,
                       $begin,
                       date('Y-m-d H:i:s', $enddate),
                       array($this->jsongraph_a_ref[$rrdtool_template],
                             $this->jsongraph_a_convert[$rrdtool_template]),
                       $timecomplete,
                       $todisplay);
            } else {
               $ret = $pmServiceevent->getData(
                       $result,
                       $rrdtool_template,
                       $begin,
                       date('Y-m-d H:i:s', $enddate),
                       array(),
                       $timecomplete,
                       $todisplay);
            }
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];
               if (!isset($this->jsongraph_a_ref[$rrdtool_template])) {
                  $this->jsongraph_a_ref[$rrdtool_template] = $ret[2];
                  $this->jsongraph_a_convert[$rrdtool_template] = $ret[3];
               }
            }
            break;

         case '12h':
            $begin = date('Y-m-d H:i:s', $enddate - (12 * 3600));
            $timecomplete = 0;
            $dateformat = "(%d)%H:%M";
            if (date('m', $enddate) != date('m', $enddate - (12 * 3600))) {
               $timecomplete = 2;
               $dateformat = "%m-%d %H:%M";
            }

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = $pmServiceevent->getData(
                    $result,
                    $rrdtool_template,
                    $begin,
                    date('Y-m-d H:i:s', $enddate),
                    array(),
                    $timecomplete,
                    $todisplay);
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];
            }
            break;

         case '1d':
            $begin = date('Y-m-d H:i:s', $enddate - (24 * 3600));
            $timecomplete = 0;
            $dateformat = "(%d)%H:%M";
            if (date('m', $enddate) != date('m', $enddate - (24 * 3600))) {
               $timecomplete = 2;
               $dateformat = "%m-%d %H:%M";
            }

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = $pmServiceevent->getData(
                    $result,
                    $rrdtool_template,
                    $begin,
                    date('Y-m-d H:i:s', $enddate),
                    array(),
                    $timecomplete,
                    $todisplay);
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];
            }
            break;

         case '1w':
            $begin = date('Y-m-d H:i:s', $enddate - (7 * 24 * 3600));
            $dateformat = "%Y-%m-%d %H:%M";

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = $pmServiceevent->getData(
                    $result,
                    $rrdtool_template,
                    $begin,
                    date('Y-m-d H:i:s', $enddate),
                    array(),
                    TRUE,
                    $todisplay);
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];

               $nb_val = count($a_labels);
               // May have 22 points in the graph
               $nb_val_period = $nb_val / 75;
               $mydatatNew = array();
               foreach ($mydatat as $name=>$data) {
                  $nb = 1;
                  $val = 0;
                  foreach ($data as $value) {
                     $val += $value;
                     $nb++;
                     if ($nb > $nb_val_period) {
                        $mydatatNew[$name][] = round($val / ($nb - 1), 2);
                        $nb = 1;
                        $val = 0;
                     }
                  }
                  if ($nb > 1
                          && $nb <= $nb_val_period) {

                        $mydatatNew[$name][] = round($val / ($nb - 1), 2);
                  }
               }
               $mydatat = $mydatatNew;
               $a_labelsNew = array();
               $nb = 1;
               $val = 0;
               foreach ($a_labels as $value) {
                  if ($nb == 1) {
                     $a_labelsNew[] = $value;
                  }
                  $nb++;
                  if ($nb > $nb_val_period) {
                     $nb = 1;
                  }
               }
               $a_labels = $a_labelsNew;
            }
            break;

         case '1m':
            $begin = date('Y-m-d H:i:s', $enddate - (30 * 24 * 3600));
            $dateformat = "%Y-%m-%d %H:%M";

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = $pmServiceevent->getData(
                    $result,
                    $rrdtool_template,
                    $begin,
                    date('Y-m-d H:i:s', $enddate),
                    array(),
                    TRUE,
                    $todisplay);
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];

               $nb_val = count($a_labels);
               // May have 22 points in the graph
               $nb_val_period = $nb_val / 75;
               $mydatatNew = array();
               foreach ($mydatat as $name=>$data) {
                  $nb = 1;
                  $val = 0;
                  foreach ($data as $value) {
                     $val += $value;
                     $nb++;
                     if ($nb > $nb_val_period) {
                        $mydatatNew[$name][] = ceil($val / ($nb - 1));
                        $nb = 1;
                        $val = 0;
                     }
                  }
                  if ($nb > 1
                          && $nb <= $nb_val_period) {

                        $mydatatNew[$name][] = ceil($val / ($nb - 1));
                  }
               }
               $mydatat = $mydatatNew;

               $a_labelsNew = array();
               $nb = 1;
               $val = 0;
               foreach ($a_labels as $value) {
                  if ($nb == 1) {
                     $a_labelsNew[] = $value;
                  }
                  $nb++;
                  if ($nb > $nb_val_period) {
                     $nb = 1;
                  }
               }
               $a_labels = $a_labelsNew;
            }
            break;

         case '0y6m':
            $begin = date('Y-m-d H:i:s', date('U') - ((364 / 2) * 24 * 3600));
            $dateformat = "%Y-%m-%d %H:%M";

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = $pmServiceevent->getData(
                    $result,
                    $rrdtool_template,
                    $begin,
                    date('Y-m-d H:i:s', $enddate),
                    array(),
                    TRUE,
                    $todisplay);
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];

               $nb_val = count($a_labels);
               // May have 22 points in the graph
               $nb_val_period = $nb_val / 75;
               $mydatatNew = array();
               foreach ($mydatat as $name=>$data) {
                  $nb = 1;
                  $val = 0;
                  foreach ($data as $value) {
                     $val += $value;
                     $nb++;
                     if ($nb > $nb_val_period) {
                        $mydatatNew[$name][] = ceil($val / ($nb - 1));
                        $nb = 1;
                        $val = 0;
                     }
                  }
                  if ($nb > 1
                          && $nb <= $nb_val_period) {

                        $mydatatNew[$name][] = ceil($val / ($nb - 1));
                  }
               }
               $mydatat = $mydatatNew;

               $a_labelsNew = array();
               $nb = 1;
               $val = 0;
               foreach ($a_labels as $value) {
                  if ($nb == 1) {
                     $a_labelsNew[] = $value;
                  }
                  $nb++;
                  if ($nb > $nb_val_period) {
                     $nb = 1;
                  }
               }
               $a_labels = $a_labelsNew;
            }
            break;

         case '1y':
            $begin = date('Y-m-d H:i:s', date('U') - (365 * 24 * 3600));
            $dateformat = "%Y-%m-%d %H:%M";

            $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
               WHERE `plugin_monitoring_services_id`='".$items_id."'
                  AND `date` > '".$begin."'
                  AND `date` <= '".date('Y-m-d H:i:s', $enddate)."'
               ORDER BY `date`";
            $result = $DB->query($query);
            $ret = $pmServiceevent->getData(
                    $result,
                    $rrdtool_template,
                    $begin,
                    date('Y-m-d H:i:s', $enddate),
                    array(),
                    TRUE,
                    $todisplay);
            if (is_array($ret)) {
               $mydatat  = $ret[0];
               $a_labels = $ret[1];
               $a_ref    = $ret[2];

               $nb_val = count($a_labels);
               // May have 22 points in the graph
               $nb_val_period = $nb_val / 75;
               $mydatatNew = array();
               foreach ($mydatat as $name=>$data) {
                  $nb = 1;
                  $val = 0;
                  foreach ($data as $value) {
                     $val += $value;
                     $nb++;
                     if ($nb > $nb_val_period) {
                        $mydatatNew[$name][] = ceil($val / ($nb - 1));
                        $nb = 1;
                        $val = 0;
                     }
                  }
                  if ($nb > 1
                          && $nb <= $nb_val_period) {

                        $mydatatNew[$name][] = ceil($val / ($nb - 1));
                  }
               }
               $mydatat = $mydatatNew;

               $a_labelsNew = array();
               $nb = 1;
               $val = 0;
               foreach ($a_labels as $value) {
                  if ($nb == 1) {
                     $a_labelsNew[] = $value;
                  }
                  $nb++;
                  if ($nb > $nb_val_period) {
                     $nb = 1;
                  }
               }
               $a_labels = $a_labelsNew;
            }
            break;
      }
      return array($mydatat, $a_labels, $dateformat);
   }
 static function getAdditionalMenuOptions()
 {
     global $CFG_GLPI;
     $main_menu = '<img src="' . $CFG_GLPI["root_doc"] . '/plugins/monitoring/pics/main_menu.png" alt="' . __('Main menu', 'monitoring') . '" title="' . __('Main menu', 'monitoring') . '"\\>';
     return array('componentscatalog' => array('title' => PluginMonitoringComponentscatalog::getTypeName(), 'page' => PluginMonitoringComponentscatalog::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/componentscatalog.php', 'add' => '/plugins/monitoring/front/componentscatalog.form.php')), 'command' => array('title' => PluginMonitoringCommand::getTypeName(), 'page' => PluginMonitoringCommand::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/command.php', 'add' => '/plugins/monitoring/front/command.form.php')), 'check' => array('title' => PluginMonitoringCheck::getTypeName(), 'page' => PluginMonitoringCheck::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/check.php', 'add' => '/plugins/monitoring/front/check.form.php')), 'eventhandler' => array('title' => PluginMonitoringEventhandler::getTypeName(), 'page' => PluginMonitoringEventhandler::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/eventhandler.php', 'add' => '/plugins/monitoring/front/eventhandler.form.php')), 'perfdata' => array('title' => PluginMonitoringPerfdata::getTypeName(), 'page' => PluginMonitoringPerfdata::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/perfdata.php', 'add' => '/plugins/monitoring/front/perfdata.form.php')), 'component' => array('title' => PluginMonitoringComponent::getTypeName(), 'page' => PluginMonitoringComponent::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/component.php', 'add' => '/plugins/monitoring/front/component.form.php')), 'contacttemplate' => array('title' => PluginMonitoringContacttemplate::getTypeName(), 'page' => PluginMonitoringContacttemplate::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/contacttemplate.php', 'add' => '/plugins/monitoring/front/contacttemplate.form.php')), 'notificationcommand' => array('title' => PluginMonitoringNotificationcommand::getTypeName(), 'page' => PluginMonitoringNotificationcommand::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/notificationcommand.php', 'add' => '/plugins/monitoring/front/notificationcommand.form.php')), 'realm' => array('title' => PluginMonitoringRealm::getTypeName(), 'page' => PluginMonitoringRealm::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/realm.php', 'add' => '/plugins/monitoring/front/realm.form.php')), 'tag' => array('title' => PluginMonitoringTag::getTypeName(), 'page' => PluginMonitoringTag::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/tag.php')), 'servicescatalog' => array('title' => PluginMonitoringServicescatalog::getTypeName(), 'page' => PluginMonitoringServicescatalog::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/servicescatalog.php', 'add' => '/plugins/monitoring/front/servicescatalog.form.php')), 'weathermap' => array('title' => PluginMonitoringWeathermap::getTypeName(), 'page' => PluginMonitoringWeathermap::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/weathermap.php', 'add' => '/plugins/monitoring/front/weathermap.form.php')), 'displayview' => array('title' => PluginMonitoringDisplayview::getTypeName(), 'page' => PluginMonitoringDisplayview::getSearchURL(false), 'links' => array('search' => '/plugins/monitoring/front/displayview.php', 'add' => '/plugins/monitoring/front/displayview.form.php')), 'slider' => array('title' => PluginMonitoringSlider::getTypeName(), 'page' => PluginMonitoringSlider::getSearchURL(false), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'search' => '/plugins/monitoring/front/slider.php', 'add' => '/plugins/monitoring/front/slider.form.php')), 'downtime' => array('title' => PluginMonitoringDowntime::getTypeName(), 'page' => PluginMonitoringDowntime::getSearchURL(false), 'links' => array('search' => '/plugins/monitoring/front/downtime.php')), 'acknowledge' => array('title' => PluginMonitoringAcknowledge::getTypeName(), 'page' => PluginMonitoringAcknowledge::getSearchURL(false), 'links' => array('search' => '/plugins/monitoring/front/acknowledge.php')), 'menu' => array('title' => PluginMonitoringMenu::getTypeName(), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'config' => '/plugins/monitoring/front/config.form.php')), 'dashboard' => array('title' => PluginMonitoringDisplay::getTypeName(), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php', 'config' => '/plugins/monitoring/front/config.form.php')), 'config' => array('title' => PluginMonitoringConfig::getTypeName(), 'links' => array($main_menu => '/plugins/monitoring/front/menu.php')));
 }
   function generateSyntheseReport($array, $pdf=TRUE) {
      global $DB;

      if (count($array) == 0) {
         return;
      }
      $end_date = $array['synthesedate_end'];
      $end_date_timestamp = strtotime($end_date);
      $number   = $array['synthesenumber'];
      $period   = $array['syntheseperiod'];

      $componentscatalogs_id = $array['componentscatalogs_id'];

      $pmComponent    = new PluginMonitoringComponent();
      $pmUnavailability = new PluginMonitoringUnavailability();
      $pmServiceevent = new PluginMonitoringServiceevent();

      if ($pdf) {
         PluginMonitoringReport::beginCapture();
      }
      echo "<table class='tab_cadrehov'>";
      foreach ($array['components_id'] as $components_id) {
         $pmComponent->getFromDB($components_id);
         array_unshift($array['perfname'][$components_id], 'avaibility');
         array_unshift($array['perfname_val'][$components_id], 1);
         echo '<tr class="tab_bg_1" height="90">';
         echo '<th colspan="'.(3 + ($number * 2)).'">';
         echo $pmComponent->getName();
         echo '</th>';
         echo '</tr>';

         foreach ($array['perfname'][$components_id] as $num=>$groupname) {
            echo '<tr class="tab_bg_1">';
            echo '<th colspan="'.(3 + ($number * 2)).'">';
            if ($groupname == 'avaibility') {
               echo __('Avaibility', 'monitoring');
            } else {
               echo $groupname;
            }
            echo '</th>';
            echo '</tr>';

            echo '<tr class="tab_bg_1">';
            echo '<th rowspan="2">';
            echo __('Name');
            echo '</th>';
            echo '<th rowspan="2">';
            echo __('Entity');
            echo '</th>';
            echo '<th rowspan="2">';
            echo __('Itemtype');
            echo '</th>';
            $a_year = array();
            for ($i = $number; $i >= 1;$i--) {
               $year = date('Y', strtotime("-".$i." ".$period, $end_date_timestamp));
               if (!isset($a_year[$year])) {
                  $a_year[$year] = 2;
               } else {
                  $a_year[$year] += 2;
               }
            }
            foreach ($a_year as $year=>$colspan) {
               echo '<th colspan="'.$colspan.'">';
               echo $year;
               echo '</th>';
            }
            echo '</tr>';

            echo '<tr class="tab_bg_1">';
            for ($i = $number; $i >= 1;$i--) {
               echo '<th colspan="2">';
               echo Html::convDate(date('m-d', strtotime("-".$i." ".$period, $end_date_timestamp)));
               echo "<br/>";
               echo Html::convDate(date('m-d', strtotime("-".($i-1)." ".$period, $end_date_timestamp)));
               echo '</th>';
            }
            echo '</tr>';

            $query = "SELECT `glpi_plugin_monitoring_componentscatalogs_hosts`.*,
                  `glpi_plugin_monitoring_services`.`id` as sid FROM `glpi_plugin_monitoring_componentscatalogs_hosts`
               LEFT JOIN `glpi_plugin_monitoring_services`
                  ON `glpi_plugin_monitoring_componentscatalogs_hosts`.`id`=`plugin_monitoring_componentscatalogs_hosts_id`
               WHERE `plugin_monitoring_componentscalalog_id`='".$componentscatalogs_id."'
                  AND `plugin_monitoring_components_id`='".$components_id."'";
            $result = $DB->query($query);
            $rownb = true;
            while ($data=$DB->fetch_array($result)) {
               $itemtype = $data['itemtype'];
               $item = new $itemtype();
               $item->getFromDB($data['items_id']);

               if ($groupname == 'avaibility') {
                  $a_times = $pmUnavailability->parseEvents($data['id'], '',
                                                          date('Y-m-d', strtotime("-".($number + 1)." ".$period, $end_date_timestamp)),
                                                          date('Y-m-d', strtotime("-".$number." ".$period, $end_date_timestamp)));
                  $previous_value = round(((($a_times[1] - $a_times[0]) / $a_times[1]) * 100), 3);
               } else {
                  $previous_value = 0;
               }
               echo '<tr class="tab_bg'.(($rownb = !$rownb)?'_4':'_1').'">';
               echo '<td>';
               echo $item->getLink();
               echo '</td>';
               echo '<td>';
               echo Dropdown::getDropdownName("glpi_entities", $item->fields['entities_id']);
               echo '</td>';
               echo '<td>';
               echo $item->getTypeName();
               echo '</td>';
               for ($i = $number; $i >= 1;$i--) {
                  $startdatet = date('Y-m-d', strtotime("-".$i." ".$period, $end_date_timestamp));
                  $enddatet   = date('Y-m-d', strtotime("-".($i-1)." ".$period, $end_date_timestamp));
                  if ($groupname == 'avaibility') {
                     $a_times = $pmUnavailability->parseEvents($data['id'], '', $startdatet, $enddatet);
                     $value = round(((($a_times[1] - $a_times[0]) / $a_times[1]) * 100), 2);
                  } else {
                     $queryevents = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`
                        WHERE `plugin_monitoring_services_id`='".$data['sid']."'
                           AND `date` >= '".$startdatet."'
                           AND `date` <= '".$enddatet."'
                        ORDER BY `date`";
                     $resultevents = $DB->query($queryevents);
                     $_SESSION['plugin_monitoring_checkinterval'] = PluginMonitoringComponent::getTimeBetween2Checks($pmComponent->fields['id']);
                     $ret = $pmServiceevent->getData($resultevents, $pmComponent->fields['graph_template'], $startdatet, $enddatet);
                     if (!isset($ret[0][$groupname])) {
                        $value = 0;
                     } else {
                        $value = round(array_sum($ret[0][$groupname]) / count($ret[0][$groupname]), 2);
                     }
                  }

                  $bgcolor = '';
                  if ($array['perfname_val'][$components_id][$num] == 1) {
                     if ($previous_value < $value) {
                        $bgcolor = 'style="background-color:#d1ffc3"';
                     } else if ($previous_value > $value) {
                        $bgcolor = 'style="background-color:#ffd1d3"';
                     }
                  } else {
                     if ($previous_value < $value) {
                        $bgcolor = 'style="background-color:#ffd1d3"';
                     } else if ($previous_value > $value) {
                        $bgcolor = 'style="background-color:#d1ffc3"';
                     }
                  }

                  echo '<td '.$bgcolor.'>';
                  if ($groupname == 'avaibility') {
                     echo $value."%";
                  } else {
                     if ($value > 3000000000) {
                        echo round($value/1000000000, 2).'T';
                     } else if ($value > 3000000) {
                        echo round($value/1000000, 2).'M';
                     } else if ($value > 3000) {
                        echo round($value/1000, 2).'K';
                     } else {
                        echo $value;
                     }
                  }
                  echo '</td>';
                  echo '<td '.$bgcolor.'>';
                  if ($array['perfname_val'][$components_id][$num] == 1) {
                     if ($previous_value < $value) {
                        echo '<img src="../pics/arrow-up-right.png" width="16" />';
                     } else if ($previous_value == $value) {
                        echo '<img src="../pics/arrow-right.png" width="16" />';
                     } else if ($previous_value > $value) {
                        echo '<img src="../pics/arrow-down-right.png" width="16" />';
                     }
                  } else {
                     if ($previous_value < $value) {
                        echo '<img src="../pics/arrow-up-right_inv.png" width="16" />';
                     } else if ($previous_value == $value) {
                        echo '<img src="../pics/arrow-right.png" width="16" />';
                     } else if ($previous_value > $value) {
                        echo '<img src="../pics/arrow-down-right_inv.png" width="16" />';
                     }
                  }
                  $previous_value = $value;
                  echo '</td>';
               }
               echo "</tr>";

            }
         }
         echo '<tr class="tab_bg_1" height="50">';
         echo '<td colspan="'.(3 + ($number * 2)).'">';
         echo '</td>';
         echo '</tr>';
      }
      echo "</table>";
      if ($pdf) {
         $content = PluginMonitoringReport::endCapture();
         PluginMonitoringReport::generatePDF($content, 'L');
      }
   }
 function showWidget($id, $time)
 {
     global $LANG, $DB, $CFG_GLPI;
     $pmRrdtool = new PluginMonitoringRrdtool();
     $pmComponent = new PluginMonitoringComponent();
     $this->getFromDB($id);
     $pmComponent->getFromDB($this->fields['plugin_monitoring_components_id']);
     $pmRrdtool->displayGLPIGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $id, "0", $time);
     return '<img src="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/front/send.php?file=PluginMonitoringService-' . $id . '-' . $time . '0.png"/>';
 }
Beispiel #29
0
 public function testPHPlogs()
 {
     global $CFG_GLPI, $PLUGIN_HOOKS;
     $_SESSION['glpi_use_mode'] = 2;
     $_SESSION["glpiID"] = 2;
     $_SESSION["glpiactiveentities_string"] = 0;
     $PLUGIN_HOOKS = plugin_init_monitoring();
     plugin::load("monitoring");
     $CFG_GLPI['root_doc'] = "http://127.0.0.1/fusion0.80/";
     loadLanguage("en_GB");
     $pmComponent = new PluginMonitoringComponent();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $pmComponentscatalog_Component = new PluginMonitoringComponentscatalog_Component();
     $pmComponentscatalog_rule = new PluginMonitoringComponentscatalog_rule();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmService = new PluginMonitoringService();
     $computer = new Computer();
     // Add components
     $input = array();
     $input['name'] = 'Host alive';
     $input['plugin_monitoring_commands_id '] = '21';
     $input['plugin_monitoring_checks_id'] = '1';
     $input['calendars_id'] = '1';
     $components_id = $pmComponent->add($input);
     // Add components catalog
     $input = array();
     $input['name'] = 'linux servers';
     $catalogs_id = $pmComponentscatalog->add($input);
     $input = array();
     $input['plugin_monitoring_componentscalalog_id'] = $catalogs_id;
     $input['plugin_monitoring_components_id'] = $components_id;
     $pmComponentscatalog_Component->add($input);
     // Add Computer
     $input = array();
     $input['name'] = 'pc1';
     $input['entities_id'] = 0;
     $pc1 = $computer->add($input);
     // Check computer pc1 not added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '0', '[f1] Computer in component cataglog and may not be');
     $input = array();
     $input['plugin_monitoring_componentscalalog_id'] = $catalogs_id;
     $input['name'] = 'all have name';
     $input['itemtype'] = 'Computer';
     $input['condition'] = '{"field":["1"],"searchtype":["contains"],"contains":["pc"],"itemtype":"Computer","start":"0"}';
     $rules_id = $pmComponentscatalog_rule->add($input);
     // Check computer pc1 not added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '1', '[f2] Computer may be in component catalog');
     // Check service of this computer created
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '1', '[s2] One service may be created');
     // Add Computer
     $input = array();
     $input['name'] = 'pc2';
     $input['entities_id'] = 0;
     $pc2 = $computer->add($input);
     // Check computer pc1 not added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '2', '[f3] 2 computers may be in component catalog');
     // Check service of this computer created
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '2', '[s3] 2 services may be created');
     // Remove pc2
     $computer->delete(array('id' => $pc2), 1);
     // Check computer pc1 added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '1', '[f4] Computer may be unique in component catalog');
     // Check service of this computer created
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '1', '[s4] One service may be created');
     // Modify rule
     $input['id'] = $rules_id;
     $input['condition'] = '{"field":["1"],"searchtype":["contains"],"contains":["tc"],"itemtype":"Computer","start":"0"}';
     $pmComponentscatalog_rule->update($input);
     // Check no computer in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '0', '[f5] Computer may be deleted on rule update');
     // Check service
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '0', '[s5] No service may be created');
     // Modify rule
     $input['id'] = $rules_id;
     $input['condition'] = '{"field":["1"],"searchtype":["contains"],"contains":["pc"],"itemtype":"Computer","start":"0"}';
     $pmComponentscatalog_rule->update($input);
     // Check computer pc1 added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '1', '[f6] Computer may be unique in component catalog');
     // Delete rule
     $pmComponentscatalog_rule->delete(array('id' => $rules_id), 1);
     // Check not have computer in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '0', '[f7] must have no computer in component catalog');
     // Check service
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '0', '[s7] No service may be created');
 }
 function generateServicesCfg($file = 0, $tag = '')
 {
     global $DB;
     $pMonitoringCommand = new PluginMonitoringCommand();
     $pMonitoringCheck = new PluginMonitoringCheck();
     $pmComponent = new PluginMonitoringComponent();
     $pmEntity = new PluginMonitoringEntity();
     $pmContact_Item = new PluginMonitoringContact_Item();
     $pmService = new PluginMonitoringService();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $calendar = new Calendar();
     $user = new User();
     $pmLog = new PluginMonitoringLog();
     $profile_User = new Profile_User();
     if (isset($_SERVER['HTTP_USER_AGENT']) and strstr($_SERVER['HTTP_USER_AGENT'], 'xmlrpclib.py')) {
         if (!isset($_SESSION['glpi_currenttime'])) {
             $_SESSION['glpi_currenttime'] = date("Y-m-d H:i:s");
         }
         $input = array();
         $input['user_name'] = "Shinken";
         $input['action'] = "restart";
         $input['date_mod'] = date("Y-m-d H:i:s");
         $pmLog->add($input);
     }
     $hostnamebp = '';
     $a_services = array();
     $i = 0;
     // * Prepare 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;
     }
     $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
     $query = "SELECT * FROM `glpi_plugin_monitoring_services`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $notadd = 0;
         $notadddescription = '';
         $a_component = current($pmComponent->find("`id`='" . $data['plugin_monitoring_components_id'] . "'", "", 1));
         $a_hostname = 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;
         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']])) {
                     $a_hostname[] = $itemtype . "-" . $datah['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
                     $hostname = $item->fields['name'];
                     $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_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));
             $hostnamebp = $a_services[$i]['host_name'];
             // For business rules
             $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9]/", "", $a_component['name']) . "-" . $data['id'];
             $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;
             }
             $args = '';
             foreach ($array[0] as $arg) {
                 if ($arg != '$PLUGINSDIR$' 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("PluginFusinvsnmpNetworkPort")) {
                                 $pfNetworkPort = new PluginFusinvsnmpNetworkPort();
                                 $pfNetworkPort->loadNetworkport($data['networkports_id']);
                                 $descr = '';
                                 $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]]")) {
                             $networkPort = new NetworkPort();
                             $networkPort->getFromDB($data['networkports_id']);
                             $portname = $pfNetworkPort->fields['name'];
                             $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $portname, $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] . " 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'] != '') {
                     $a_services[$i]['check_command'] = "check_nrpe!" . $a_component['alias_command'];
                 } else {
                     $a_services[$i]['check_command'] = "check_nrpe!" . $pMonitoringCommand->fields['command_name'];
                 }
             } else {
                 $a_services[$i]['check_command'] = $pMonitoringCommand->fields['command_name'] . $args;
             }
             // * 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 (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']])) {
                         //                  $pmContact->getFromDB($data_contact['plugin_monitoring_contacts_id']);
                         $user->getFromDB($data_contact['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'];
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                 }
                 $a_services[$i]['notification_interval'] = '30';
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['notification_period'] = $calendar->fields['name'];
                 } else {
                     $a_services[$i]['notification_period'] = "24x7";
                 }
                 $a_services[$i]['notification_options'] = 'w,c,r';
                 $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'] = '1';
                 $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';
             }
             $pmComponentscatalog->getFromDB($plugin_monitoring_componentscatalogs_id);
             if ($pmComponentscatalog->fields['notification_interval'] != '30') {
                 $a_services[$i]['notification_interval'] = $pmComponentscatalog->fields['notification_interval'];
             }
             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++;
             }
         }
     }
     //      // Business rules....
     $pmService = new PluginMonitoringService();
     $pmServicescatalog = new PluginMonitoringServicescatalog();
     $pMonitoringBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pmBusinessrule = new PluginMonitoringBusinessrule();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $a_listBA = $pmServicescatalog->find();
     foreach ($a_listBA as $dataBA) {
         if (isset($a_entities_allowed['-1']) or isset($a_entities_allowed[$dataBA['entities_id']])) {
             $a_grouplist = $pMonitoringBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $dataBA['id'] . "'");
             $a_group = array();
             foreach ($a_grouplist as $gdata) {
                 $a_listBR = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $gdata['id'] . "'");
                 foreach ($a_listBR as $dataBR) {
                     if ($pmService->getFromDB($dataBR['plugin_monitoring_services_id'])) {
                         $pmComponentscatalog_Host->getFromDB($pmService->fields['plugin_monitoring_componentscatalogs_hosts_id']);
                         $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
                         $item = new $itemtype();
                         if ($item->getFromDB($pmComponentscatalog_Host->fields['items_id'])) {
                             $hostname = $itemtype . "-" . $pmComponentscatalog_Host->fields['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
                             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 . "," . preg_replace("/[^A-Za-z0-9]/", "", $pmService->fields['name']) . "-" . $pmService->fields['id'];
                                 } else {
                                     $a_group[$gdata['id']] .= $operator . $hostname . "," . preg_replace("/[^A-Za-z0-9]/", "", $pmService->fields['name']) . "-" . $pmService->fields['id'];
                                 }
                             } else {
                                 $a_group[$gdata['id']] = $gdata['operator'] . " " . $hostname . "," . preg_replace("/[^A-Za-z0-9]/", "", $item->getName()) . "-" . $item->fields['id'];
                             }
                         }
                     }
                 }
             }
             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'] = $hostnamebp;
                 $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9]/", "", $dataBA['name']) . "-" . $dataBA['id'] . "-businessrules";
                 $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);
                 $a_services[$i]['notification_interval'] = '30';
                 if ($calendar->getFromDB($dataBA['calendars_id'])) {
                     $a_services[$i]['notification_period'] = $calendar->fields['name'];
                 } else {
                     $a_services[$i]['notification_period'] = "24x7";
                 }
                 $a_services[$i]['notification_options'] = 'w,c,r';
                 $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'] = '1';
                 $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';
                 $a_services[$i]['contacts'] = '';
                 $i++;
             }
         }
     }
     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->constructFile("service", $data);
         }
         return array('services.cfg', $config);
     } else {
         return $a_services;
     }
 }