if (isset($_POST['itemtypen'])) {
   $_POST['itemtype'] = $_POST['itemtypen'];
}

$pmComponentscatalog_rule = new PluginMonitoringComponentscatalog_rule();
$pmComponentscatalog = new PluginMonitoringComponentscatalog();


if (isset($_GET['addrule'])) {
   if (!isset($_GET['criteria'])) {
//      $_SESSION['plugin_monitoring_rules'] = $_POST;
   } else {
      $_POST = $_GET;
      $input = array();
      $pmComponentscatalog->getFromDB($_POST['plugin_monitoring_componentscalalog_id']);
      $input['entities_id'] = $pmComponentscatalog->fields['entities_id'];
      $input['is_recursive'] = $pmComponentscatalog->fields['is_recursive'];
      $input['name'] = $_POST['name'];
      $input['itemtype'] = $_POST['itemtype'];
      $input['plugin_monitoring_componentscalalog_id'] = $_POST['plugin_monitoring_componentscalalog_id'];
      unset($_POST['entities_id']);
      unset($_POST['is_recursive']);
      unset($_POST['name']);
      unset($_POST['addrule']);
      unset($_POST['itemtypen']);
      unset($_POST['plugin_monitoring_componentscalalog_id']);
      $input['condition'] = exportArrayToDB($_POST);
      $rules_id = $pmComponentscatalog_rule->add($input);
      unset($_SESSION['plugin_monitoring_rules']);
      unset($_SESSION["glpisearch"][$input['itemtype']]);
   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;
      }
   }
   /**
    * Display graphs of services associated with host
    *
    * @param $itemtype value type of item
    * @param $items_id integer id of the object
    *
    **/
   function showGraphsByHost($itemtype, $items_id) {
      global $CFG_GLPI,$DB;

      PluginMonitoringToolbox::loadLib();
      $pmComponentscatalog = new PluginMonitoringComponentscatalog();
      $pmComponent = new PluginMonitoringComponent();
      $pmServicegraph = new PluginMonitoringServicegraph();
      $networkPort = new NetworkPort();

      $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`
         WHERE `items_id`='".$items_id."'
            AND `itemtype`='".$itemtype."'";
      $result = $DB->query($query);

      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 "<table class='tab_cadre_fixe'>";
      while ($data=$DB->fetch_array($result)) {
         $pmComponentscatalog->getFromDB($data['plugin_monitoring_componentscalalog_id']);

         $querys = "SELECT `glpi_plugin_monitoring_services`.* FROM `glpi_plugin_monitoring_services`
            LEFT JOIN `glpi_plugin_monitoring_components`
               on `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id`
            WHERE `plugin_monitoring_componentscatalogs_hosts_id`='".$data['id']."'
               ORDER BY `name`";
         $results = $DB->query($querys);
         while ($datas=$DB->fetch_array($results)) {
            $pmComponent->getFromDB($datas['plugin_monitoring_components_id']);
            if ($pmComponent->fields['graph_template'] != 0) {
               echo "<tr>";
               echo "<td>";
               echo "<table class='tab_cadre'>";
               echo "<tr class='tab_bg_3'>";
               echo "<th>";
               echo "<a href='".$CFG_GLPI['root_doc']."/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=".$datas['id']."'>";
               echo $pmComponent->fields['name'];
               echo "</a>";
               if (!is_null($datas['networkports_id'])
                       && $datas['networkports_id'] > 0) {
                  $networkPort->getFromDB($datas['networkports_id']);
                  echo " [".$networkPort->getLink()."]";
               }
               echo "</th>";
               echo "</tr>";
               echo "<tr class='tab_bg_1'>";
               echo "<td style='position: relative'>";
               $pmServicegraph->displayGraph($pmComponent->fields['graph_template'],
                                             "PluginMonitoringService",
                                             $datas['id'],
                                             "0",
                                             "2h",
                                             "",
                                             920);
               echo "</td>";
               echo "</tr>";
               echo "</table>";
               echo "</td>";
               echo "</tr>";
            }
         }
      }

      echo "</tr>";
      echo "</table>";

   }
 static function isThisItemCheckRule($parm)
 {
     global $DB;
     $itemtype = get_class($parm);
     $items_id = $parm->fields['id'];
     $a_find = array();
     $pmComponentscatalog_rule = new PluginMonitoringComponentscatalog_rule();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $pmSearch = new PluginMonitoringSearch();
     $query = "SELECT * FROM `" . $pmComponentscatalog_rule->getTable() . "`\n         WHERE `itemtype`='" . $itemtype . "'";
     $result = $DB->query($query);
     $get_tmp = array();
     if (isset($_GET)) {
         $get_tmp = $_GET;
     }
     while ($data = $DB->fetch_array($result)) {
         if (isset($_SESSION["glpisearchcount"][$data['itemtype']])) {
             unset($_SESSION["glpisearchcount"][$data['itemtype']]);
         }
         if (isset($_SESSION["glpisearchcount2"][$data['itemtype']])) {
             unset($_SESSION["glpisearchcount2"][$data['itemtype']]);
         }
         $_GET = importArrayFromDB($data['condition']);
         $_GET["glpisearchcount"] = count($_GET['field']);
         if (isset($_GET['field2'])) {
             $_GET["glpisearchcount2"] = count($_GET['field2']);
         }
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = $parm->fields['entities_id'];
         }
         // Load right entity
         $pmComponentscatalog->getFromDB($data['plugin_monitoring_componentscalalog_id']);
         $default_entity = 0;
         if (isset($_SESSION['glpiactive_entity'])) {
             $default_entity = $_SESSION['glpiactive_entity'];
         }
         $entities_isrecursive = 0;
         if (isset($_SESSION['glpiactiveentities']) and count($_SESSION['glpiactiveentities']) > 1) {
             $entities_isrecursive = 1;
         }
         if (!isset($_SESSION['glpiactiveprofile']['entities'])) {
             $_SESSION['glpiactiveprofile']['entities'] = array($pmComponentscatalog->fields['entities_id'] => array('id' => $pmComponentscatalog->fields['entities_id'], 'name' => '', 'is_recursive' => $pmComponentscatalog->fields['is_recursive']));
         }
         Session::changeActiveEntities($pmComponentscatalog->fields['entities_id'], $pmComponentscatalog->fields['is_recursive']);
         Search::manageGetValues($data['itemtype']);
         $resultr = $pmSearch->constructSQL($itemtype, $_GET, $items_id);
         if ($DB->numrows($resultr) > 0) {
             $a_find[$data['plugin_monitoring_componentscalalog_id']] = 1;
         } else {
             if (!isset($a_find[$data['plugin_monitoring_componentscalalog_id']])) {
                 $a_find[$data['plugin_monitoring_componentscalalog_id']] = 0;
             }
         }
         // Reload current entity
         Session::changeActiveEntities($default_entity, $entities_isrecursive);
     }
     if (count($get_tmp) > 0) {
         $_GET = $get_tmp;
     }
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     foreach ($a_find as $componentscalalog_id => $is_present) {
         if ($is_present == '0') {
             // * Remove from dynamic if present
             $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                  AND `itemtype`='" . $itemtype . "'\n                  AND `items_id`='" . $items_id . "'\n                  AND`is_static`='0'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_array($result)) {
                 $pmComponentscatalog_Host->delete(array('id' => $data['id']));
             }
         } else {
             //  add if not present
             $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                  AND `itemtype`='" . $itemtype . "'\n                  AND `items_id`='" . $items_id . "'\n                     LIMIT 1";
             $result = $DB->query($query);
             if ($DB->numrows($result) == '0') {
                 $input = array();
                 $input['plugin_monitoring_componentscalalog_id'] = $componentscalalog_id;
                 $input['is_static'] = '0';
                 $input['items_id'] = $items_id;
                 $input['itemtype'] = $itemtype;
                 $componentscatalogs_hosts_id = $pmComponentscatalog_Host->add($input);
                 $pmComponentscatalog_Host->linkComponentsToItem($componentscalalog_id, $componentscatalogs_hosts_id);
             } else {
                 $data2 = $DB->fetch_assoc($result);
                 // modify entity of services (if entity of device is changed)
                 $item = new $itemtype();
                 $item->getFromDB($items_id);
                 $queryu = "UPDATE `glpi_plugin_monitoring_services`\n                     SET `entities_id`='" . $item->fields['entities_id'] . "'\n                        WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $data2['id'] . "'";
                 $DB->query($queryu);
             }
         }
     }
     if ($itemtype == 'NetworkEquipment') {
         //Get networkports
         $pmComponentscatalog_rule->isThisItemCheckRuleNetworkport($parm);
     }
 }
 static function listForComponents($components_id)
 {
     global $DB;
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     echo "<table class='tab_cadre' width='400'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . __('Components catalog', 'monitoring') . "</th>";
     echo "</tr>";
     $query = "SELECT `glpi_plugin_monitoring_componentscatalogs`.* FROM `glpi_plugin_monitoring_componentscatalogs_components`\n         LEFT JOIN `glpi_plugin_monitoring_componentscatalogs`\n            ON `plugin_monitoring_componentscalalog_id` =\n               `glpi_plugin_monitoring_componentscatalogs`.`id`\n         WHERE `plugin_monitoring_components_id`='" . $components_id . "'\n         ORDER BY `glpi_plugin_monitoring_componentscatalogs`.`name`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>";
         $pmComponentscatalog->getFromDB($data['id']);
         echo $pmComponentscatalog->getLink(1);
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
 /**
  * Display services associated with host
  *
  * @param $itemtype value type of item
  * @param $items_id integer id of the object
  *
  **/
 function listByHost($itemtype, $items_id)
 {
     global $LANG, $CFG_GLPI, $DB;
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n         WHERE `items_id`='" . $items_id . "'\n            AND `itemtype`='" . $itemtype . "'";
     $result = $DB->query($query);
     //      echo "<form name='form' method='post'
     //         action='".$CFG_GLPI['root_doc']."/plugins/monitoring/front/service.form.php'>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='5'>";
     echo $LANG['plugin_monitoring']['service'][0];
     //      echo "&nbsp;<a href='".$CFG_GLPI['root_doc']."/plugins/monitoring/front/service.form.php?services_id=".$a_hosts['id']."'>
     //         <img src='".$CFG_GLPI['root_doc']."/pics/menu_add.png' /></a>";
     //
     //      echo "&nbsp;<a href='".$CFG_GLPI['root_doc']."/plugins/monitoring/front/servicedef.form.php?add_template=1'>
     //         <img src='".$CFG_GLPI['root_doc']."/pics/menu_addtemplate.png' /></a>";
     echo "</th>";
     echo "</tr>";
     echo "<table>";
     while ($data = $DB->fetch_array($result)) {
         $pmComponentscatalog->getFromDB($data['plugin_monitoring_componentscalalog_id']);
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='12'>" . $pmComponentscatalog->getTypeName() . "&nbsp;:&nbsp;" . $pmComponentscatalog->getLink() . "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<th>";
         echo $LANG['joblist'][0];
         echo "</th>";
         echo "<th>";
         echo $LANG['entity'][0];
         echo "</th>";
         echo "<th>";
         echo $LANG['stats'][7];
         echo "</th>";
         echo "<th>";
         echo $LANG['plugin_monitoring']['component'][0];
         echo "</th>";
         echo "<th>";
         echo $LANG['state'][0];
         echo "</th>";
         echo "<th>";
         echo $LANG['plugin_monitoring']['service'][18];
         echo "</th>";
         echo "<th>";
         echo $LANG['rulesengine'][82];
         echo "</th>";
         echo "<th>";
         echo $LANG['plugin_monitoring']['host'][9];
         echo "</th>";
         echo "<th>" . $LANG['plugin_monitoring']['availability'][1] . " " . showToolTip($LANG['plugin_monitoring']['availability'][0], array('display' => false)) . "</th>";
         echo "<th>" . $LANG['plugin_monitoring']['availability'][2] . " " . showToolTip($LANG['plugin_monitoring']['availability'][0], array('display' => false)) . "</th>";
         echo "<th>" . $LANG['plugin_monitoring']['availability'][3] . " " . showToolTip($LANG['plugin_monitoring']['availability'][0], array('display' => false)) . "</th>";
         echo "<th>";
         echo $LANG['plugin_monitoring']['service'][4];
         echo "</th>";
         echo "</tr>";
         $querys = "SELECT `glpi_plugin_monitoring_services`.* FROM `glpi_plugin_monitoring_services`\n            LEFT JOIN `glpi_plugin_monitoring_components`\n               on `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id`\n            WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $data['id'] . "'\n               ORDER BY `name`";
         $results = $DB->query($querys);
         while ($datas = $DB->fetch_array($results)) {
             $this->getFromDB($datas['id']);
             echo "<tr class='tab_bg_1'>";
             PluginMonitoringDisplay::displayLine($datas, 0);
             echo "</tr>";
         }
         echo "</table>";
     }
     //      echo "<tr class='tab_bg_1'>";
     //      echo "<td colspan='8' align='center'>";
     //      echo "<input type='submit' class='submit' name='update' value='".$LANG['buttons'][7]."'>";
     //      echo "</td>";
     //      echo "</tr>";
     echo "</table>";
     echo "</form>";
 }
 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 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;
     }
 }
 static function getItemsDynamicly($parm)
 {
     global $DB;
     $pmCc_Rule = new PluginMonitoringComponentscatalog_rule();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $devices_present = array();
     if ($pmCc_Rule->getFromDB($parm->fields['id'])) {
         // Load right entity
         $pmComponentscatalog->getFromDB($pmCc_Rule->fields['plugin_monitoring_componentscalalog_id']);
         $default_entity = 0;
         if (isset($_SESSION['glpiactive_entity'])) {
             $default_entity = $_SESSION['glpiactive_entity'];
         }
         $entities_isrecursive = 0;
         if (isset($_SESSION['glpiactiveentities']) and count($_SESSION['glpiactiveentities']) > 1) {
             $entities_isrecursive = 1;
         }
         changeActiveEntities($pmComponentscatalog->fields['entities_id'], $pmComponentscatalog->fields['is_recursive']);
         $get_tmp = '';
         $itemtype = $pmCc_Rule->fields['itemtype'];
         if (isset($_GET)) {
             $get_tmp = $_GET;
         }
         if (isset($_SESSION["glpisearchcount"][$pmCc_Rule->fields['itemtype']])) {
             unset($_SESSION["glpisearchcount"][$pmCc_Rule->fields['itemtype']]);
         }
         if (isset($_SESSION["glpisearchcount2"][$pmCc_Rule->fields['itemtype']])) {
             unset($_SESSION["glpisearchcount2"][$pmCc_Rule->fields['itemtype']]);
         }
         $_GET = importArrayFromDB($pmCc_Rule->fields['condition']);
         $_GET["glpisearchcount"] = count($_GET['field']);
         if (isset($_GET['field2'])) {
             $_GET["glpisearchcount2"] = count($_GET['field2']);
         }
         Search::manageGetValues($pmCc_Rule->fields['itemtype']);
         $queryd = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n            WHERE `plugin_monitoring_componentscalalog_id`='" . $pmCc_Rule->fields["plugin_monitoring_componentscalalog_id"] . "'\n               AND `itemtype`='" . $pmCc_Rule->fields['itemtype'] . "'\n               AND `is_static`='0'";
         $result = $DB->query($queryd);
         while ($data = $DB->fetch_array($result)) {
             $devices_present[$data['id']] = 1;
         }
         $glpilist_limit = $_SESSION['glpilist_limit'];
         $_SESSION['glpilist_limit'] = 500000;
         $result = $pmCc_Rule->constructSQL($itemtype, $_GET);
         $_SESSION['glpilist_limit'] = $glpilist_limit;
         while ($data = $DB->fetch_array($result)) {
             $networkports_id = 0;
             $itemtype_device = $pmCc_Rule->fields['itemtype'];
             $items_id_device = $data['id'];
             if ($itemtype_device == 'PluginMonitoringNetworkport') {
                 $pmNetworkport = new PluginMonitoringNetworkport();
                 $pmNetworkport->getFromDB($data['id']);
                 $itemtype_device = $pmNetworkport->fields['itemtype'];
                 $items_id_device = $pmNetworkport->fields['items_id'];
                 $networkports_id = $pmNetworkport->fields['networkports_id'];
             }
             $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `plugin_monitoring_componentscalalog_id`='" . $pmCc_Rule->fields["plugin_monitoring_componentscalalog_id"] . "'\n                  AND `itemtype`='" . $itemtype_device . "'\n                  AND `items_id`='" . $items_id_device . "'\n                     LIMIT 1";
             $resulth = $DB->query($queryh);
             if ($DB->numrows($resulth) == '0') {
                 $input = array();
                 $input['plugin_monitoring_componentscalalog_id'] = $pmCc_Rule->fields["plugin_monitoring_componentscalalog_id"];
                 $input['is_static'] = '0';
                 $input['items_id'] = $items_id_device;
                 $input['itemtype'] = $itemtype_device;
                 $componentscatalogs_hosts_id = $pmComponentscatalog_Host->add($input);
                 $pmComponentscatalog_Host->linkComponentsToItem($pmCc_Rule->fields["plugin_monitoring_componentscalalog_id"], $componentscatalogs_hosts_id, $networkports_id);
             } else {
                 $data2 = $DB->fetch_assoc($resulth);
                 // modify entity of services (if entity of device is changed)
                 $itemtype = $data2['itemtype'];
                 $item = new $itemtype();
                 $item->getFromDB($data2['items_id']);
                 $queryu = "UPDATE `glpi_plugin_monitoring_services`\n                     SET `entities_id`='" . $item->fields['entities_id'] . "'\n                        WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $data2['id'] . "'";
                 $DB->query($queryu);
                 unset($devices_present[$data2['id']]);
             }
         }
         // Reload current entity
         changeActiveEntities($default_entity, $entities_isrecursive);
     } else {
         // Purge
         $queryd = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n            WHERE `plugin_monitoring_componentscalalog_id`='" . $parm->fields["plugin_monitoring_componentscalalog_id"] . "'\n               AND `itemtype`='" . $parm->fields['itemtype'] . "'\n               AND `is_static`='0'";
         $result = $DB->query($queryd);
         while ($data = $DB->fetch_array($result)) {
             $devices_present[$data['id']] = 1;
         }
     }
     foreach ($devices_present as $id => $num) {
         $pmComponentscatalog_Host->delete(array('id' => $id));
     }
 }
 static function isThisItemCheckRule($parm)
 {
     global $DB;
     $itemtype = get_class($parm);
     $items_id = $parm->fields['id'];
     $session_glpisearch = array();
     if (isset($_SESSION['glpisearch'])) {
         $session_glpisearch = $_SESSION['glpisearch'];
     }
     $session_glpisearchcount = array();
     if (isset($_SESSION['glpisearchcount'])) {
         $session_glpisearchcount = $_SESSION['glpisearchcount'];
     }
     $session_glpisearchcount2 = array();
     if (isset($_SESSION['glpisearchcount2'])) {
         $session_glpisearchcount2 = $_SESSION['glpisearchcount2'];
     }
     $a_find = array();
     $pmComponentscatalog_rule = new PluginMonitoringComponentscatalog_rule();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $query = "SELECT * FROM `" . $pmComponentscatalog_rule->getTable() . "`\n         WHERE `itemtype`='" . $itemtype . "'";
     $result = $DB->query($query);
     $get_tmp = array();
     if (isset($_GET)) {
         $get_tmp = $_GET;
     }
     while ($data = $DB->fetch_array($result)) {
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = $parm->fields['entities_id'];
         }
         // Load right entity
         $pmComponentscatalog->getFromDB($data['plugin_monitoring_componentscalalog_id']);
         $default_entity = 0;
         if (isset($_SESSION['glpiactive_entity'])) {
             $default_entity = $_SESSION['glpiactive_entity'];
         }
         $entities_isrecursive = 0;
         if (isset($_SESSION['glpiactiveentities']) and count($_SESSION['glpiactiveentities']) > 1) {
             $entities_isrecursive = 1;
         }
         if (!isset($_SESSION['glpiactiveprofile']['entities'])) {
             $_SESSION['glpiactiveprofile']['entities'] = array($pmComponentscatalog->fields['entities_id'] => array('id' => $pmComponentscatalog->fields['entities_id'], 'name' => '', 'is_recursive' => $pmComponentscatalog->fields['is_recursive']));
         }
         Session::changeActiveEntities($pmComponentscatalog->fields['entities_id'], $pmComponentscatalog->fields['is_recursive']);
         $itemtype = $data['itemtype'];
         $condition = importArrayFromDB($data['condition']);
         $params = Search::manageParams($itemtype, $condition, FALSE);
         $datar = Search::prepareDatasForSearch($itemtype, $params);
         Search::constructSQL($datar);
         $DBread = DBConnection::getReadConnection();
         $DBread->query("SET SESSION group_concat_max_len = 16384;");
         $resultr = $DBread->query($datar['sql']['search']);
         /// Check group concat limit : if warning : increase limit
         if ($result2 = $DBread->query('SHOW WARNINGS')) {
             if ($DBread->numrows($result2) > 0) {
                 $res = $DBread->fetch_assoc($result2);
                 if ($res['Code'] == 1260) {
                     $DBread->query("SET SESSION group_concat_max_len = 4194304;");
                     $resultr = $DBread->query($datar['sql']['search']);
                 }
             }
         }
         $find = 0;
         while ($datar = $DB->fetch_array($resultr)) {
             if ($datar['id'] == $items_id) {
                 $find = 1;
                 break;
             }
         }
         if ($find == 1) {
             $a_find[$data['plugin_monitoring_componentscalalog_id']] = 1;
         } else {
             if (!isset($a_find[$data['plugin_monitoring_componentscalalog_id']])) {
                 $a_find[$data['plugin_monitoring_componentscalalog_id']] = 0;
             }
         }
         // Reload current entity
         Session::changeActiveEntities($default_entity, $entities_isrecursive);
     }
     if (count($get_tmp) > 0) {
         $_GET = $get_tmp;
     }
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     foreach ($a_find as $componentscalalog_id => $is_present) {
         if ($is_present == '0') {
             // * Remove from dynamic if present
             $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                  AND `itemtype`='" . $itemtype . "'\n                  AND `items_id`='" . $items_id . "'\n                  AND`is_static`='0'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_array($result)) {
                 $pmComponentscatalog_Host->delete(array('id' => $data['id']));
             }
         } else {
             //  add if not present
             $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                  AND `itemtype`='" . $itemtype . "'\n                  AND `items_id`='" . $items_id . "'\n                     LIMIT 1";
             $result = $DB->query($query);
             if ($DB->numrows($result) == '0') {
                 $input = array();
                 $input['plugin_monitoring_componentscalalog_id'] = $componentscalalog_id;
                 $input['is_static'] = '0';
                 $input['items_id'] = $items_id;
                 $input['itemtype'] = $itemtype;
                 $pmComponentscatalog_Host->add($input);
             } else {
                 $data2 = $DB->fetch_assoc($result);
                 // modify entity of services (if entity of device is changed)
                 $item = new $itemtype();
                 $item->getFromDB($items_id);
                 $queryu = "UPDATE `glpi_plugin_monitoring_services`\n                     SET `entities_id`='" . $item->fields['entities_id'] . "'\n                        WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $data2['id'] . "'";
                 $DB->query($queryu);
             }
         }
     }
     if ($itemtype == 'NetworkEquipment') {
         //Get networkports
         $pmComponentscatalog_rule->isThisItemCheckRuleNetworkport($parm);
     }
     $_SESSION['glpisearch'] = $session_glpisearch;
     $_SESSION['glpisearchcount'] = $session_glpisearchcount;
     $_SESSION['glpisearchcount2'] = $session_glpisearchcount2;
 }
Exemple #11
0
 /**
  * Display graphs of services associated with host
  *
  * @param $itemtype value type of item
  * @param $items_id integer id of the object
  *
  **/
 function showGraphsByHost($itemtype, $items_id)
 {
     global $CFG_GLPI, $DB;
     PluginMonitoringServicegraph::loadLib();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $pmComponent = new PluginMonitoringComponent();
     $pmServicegraph = new PluginMonitoringServicegraph();
     $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n         WHERE `items_id`='" . $items_id . "'\n            AND `itemtype`='" . $itemtype . "'";
     $result = $DB->query($query);
     echo '<div id="custom_date" style="display:none"></div>';
     echo '<div id="custom_time" style="display:none"></div>';
     echo "<table class='tab_cadre_fixe'>";
     $td = 0;
     while ($data = $DB->fetch_array($result)) {
         $pmComponentscatalog->getFromDB($data['plugin_monitoring_componentscalalog_id']);
         $querys = "SELECT `glpi_plugin_monitoring_services`.* FROM `glpi_plugin_monitoring_services`\n            LEFT JOIN `glpi_plugin_monitoring_components`\n               on `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id`\n            WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $data['id'] . "'\n               ORDER BY `name`";
         $results = $DB->query($querys);
         while ($datas = $DB->fetch_array($results)) {
             $pmComponent->getFromDB($datas['plugin_monitoring_components_id']);
             if ($pmComponent->fields['graph_template'] != '') {
                 if ($td == 0) {
                     echo "<tr>";
                 }
                 echo "<td width='425'>";
                 echo "<table class='tab_cadre'>";
                 echo "<tr class='tab_bg_3'>";
                 echo "<th width='475'>";
                 echo $pmComponent->fields['name'];
                 echo "</th>";
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td>";
                 $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $datas['id'], "0", "2h", "", 450);
                 echo "</td>";
                 echo "</tr>";
                 echo "</table>";
                 $td++;
                 echo "</td>";
                 if ($td == 2) {
                     echo "</tr>";
                     $td = 0;
                 }
             }
         }
     }
     if ($td == 1) {
         echo "<td></td>";
     }
     echo "</tr>";
     echo "</table>";
 }