function sendAcknowledge($services_id)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $pmComponent = new PluginMonitoringComponent();
     $pmTag = new PluginMonitoringTag();
     $pmService->getFromDB($services_id);
     $hostname = '';
     $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts` \n         WHERE `id` = '" . $pmService->fields['plugin_monitoring_componentscatalogs_hosts_id'] . "'\n         LIMIT 1";
     $resulth = $DB->query($queryh);
     while ($datah = $DB->fetch_array($resulth)) {
         $itemtype = $datah['itemtype'];
         $item = new $itemtype();
         if ($item->getFromDB($datah['items_id'])) {
             $hostname = $itemtype . "-" . $datah['items_id'] . "-" . preg_replace("/[^A-Za-z0-9]/", "", $item->fields['name']);
         }
     }
     $a_component = current($pmComponent->find("`id`='" . $pmService->fields['plugin_monitoring_components_id'] . "'", "", 1));
     $service_description = preg_replace("/[^A-Za-z0-9]/", "", $a_component['name']) . "-" . $pmService->fields['id'];
     $tag = PluginMonitoringEntity::getTagByEntities($pmService->fields['entities_id']);
     $ip = $pmTag->getIP($tag);
     $auth = $pmTag->getAuth($tag);
     $url = 'http://' . $ip . ':7760/';
     $action = 'acknowledge';
     $a_fields = array('host_name' => urlencode($hostname), 'service_description' => urlencode($service_description), 'author' => urlencode($_SESSION['glpiname']), 'comment' => urlencode(''));
     $this->sendCommand($url, $action, $a_fields, '', $auth);
 }
 function sendDowntime($host_id = -1, $service_id = -1, $author = '', $comment = '', $flexible = '0', $start_time = '0', $end_time = '0', $duration = '3600', $operation = '')
 {
     global $DB;
     if ($host_id == -1 && $service_id == -1) {
         return false;
     }
     $pmTag = new PluginMonitoringTag();
     $pmService = new PluginMonitoringService();
     $pmService->getFromDB($service_id);
     $service_description = $pmService->getName(array('shinken' => '1'));
     $pmHost = new PluginMonitoringHost();
     $pmHost->getFromDB($host_id == -1 ? $pmService->getHostID() : $host_id);
     $hostname = $pmHost->getName(true);
     // Downtime an host ...
     $acknowledgeServiceOnly = true;
     $a_fields = array();
     if ($host_id == -1) {
         $tag = PluginMonitoringEntity::getTagByEntities($pmService->getEntityID());
     } else {
         // ... one service of the host.
         $tag = PluginMonitoringEntity::getTagByEntities($pmHost->getEntityID());
     }
     $ip = $pmTag->getIP($tag);
     $auth = $pmTag->getAuth($tag);
     $port = $pmTag->getPort($tag);
     $url = 'http://' . $ip . ':' . $port . '/';
     $action = 'downtime';
     $a_fields = array('action' => empty($operation) ? 'add' : $operation, 'host_name' => $hostname, 'service_description' => $service_description, 'author' => $author, 'comment' => mb_convert_encoding($comment, "iso-8859-1"), 'flexible' => $flexible, 'start_time' => PluginMonitoringServiceevent::convert_datetime_timestamp($start_time), 'end_time' => PluginMonitoringServiceevent::convert_datetime_timestamp($end_time), 'trigger_id' => '0', 'duration' => $duration);
     // Send downtime command ...
     return $this->sendCommand($url, $action, $a_fields, '', $auth);
 }
Esempio n. 3
0
 static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
 {
     if ($item->getID() > 0) {
         if ($tabnum == 0) {
             PluginMonitoringServicegraph::loadLib();
             $pmService = new PluginMonitoringService();
             $pmService->manageServices(get_class($item), $item->fields['id']);
             $pmHostconfig = new PluginMonitoringHostconfig();
             $pmHostconfig->showForm($item->getID(), get_class($item));
         } else {
             if ($tabnum == 1) {
                 $pmService = new PluginMonitoringService();
                 $pmService->showGraphsByHost(get_class($item), $item->fields['id']);
             }
         }
     }
     return true;
 }
 function showWidgetFrame($id, $reduced_interface = false, $is_minemap = FALSE)
 {
     global $DB, $CFG_GLPI;
     $pmParentSC = new PluginMonitoringServicescatalog();
     $pMonitoringBusinessrule = new PluginMonitoringBusinessrule();
     $pMonitoringBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pMonitoringService = new PluginMonitoringService();
     $this->getFromDB($id);
     $derivated = false;
     if ($this->getField('plugin_monitoring_servicescatalogs_id') > 0) {
         $derivated = true;
         $pmParentSC->getFromDB($this->getField('plugin_monitoring_servicescatalogs_id'));
     }
     $data = $this->fields;
     // Toolbox::logInFile("pm", "SC : ".$data['id'].", name : ".$data['name'].", derivated : ".$derivated."\n");
     $colorclass = 'ok';
     switch ($data['state']) {
         case 'CRITICAL':
         case 'DOWNTIME':
             $colorclass = 'crit';
             break;
         case 'WARNING':
         case 'UNKNOWN':
         case 'RECOVERY':
         case 'FLAPPING':
         case '':
             $colorclass = 'warn';
             break;
     }
     echo '<br/><div class="ch-itemup">
      <div class="ch-info-' . $colorclass . '">
      <h1><a href="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/front/servicescatalog.form.php?id=' . $data['id'] . '&detail=1">';
     echo $data['name'];
     if ($data['comment'] != '') {
         echo ' ' . $this->getComments();
     }
     echo '</a></h1>
      </div>
   </div>';
     // If SC is derivated from a template, get groups from its parent ...
     if ($derivated) {
         $a_group = $pMonitoringBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $pmParentSC->fields['id'] . "'");
     } else {
         $a_group = $pMonitoringBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $data['id'] . "'");
     }
     // Array updated dynamically with groups/hosts/services status ...
     $colorclass = 'ok';
     $a_gstate = array();
     $cs_info = array();
     foreach ($a_group as $gdata) {
         // Toolbox::logInFile("pm", "BR group : ".$gdata['id'].", name : ".$gdata['name']."\n");
         $a_brules = $pMonitoringBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $gdata['id'] . "'");
         $state = array();
         $state['OK'] = 0;
         $state['WARNING'] = 0;
         $state['CRITICAL'] = 0;
         $cs_info_hosts = array();
         $cs_info_services = array();
         foreach ($a_brules as $brulesdata) {
             // If SC is derivated from a template, do not care about services not from the same entity  ...
             if (!$pMonitoringService->getFromDB($brulesdata['plugin_monitoring_services_id'])) {
                 continue;
             }
             if ($derivated && $pMonitoringService->getField('entities_id') != $this->getField('entities_id')) {
                 continue;
             }
             // Toolbox::logInFile("pm", "BR : ".$brulesdata['id'].", service : ".$brulesdata['plugin_monitoring_services_id']."\n");
             if (!isset($cs_info_hosts[$pMonitoringService->getHostName()])) {
                 $cs_info_hosts[$pMonitoringService->getHostName()] = array();
             }
             $cs_info_hosts[$pMonitoringService->getHostName()]['id'] = $pMonitoringService->getHostId();
             $cs_info_hosts[$pMonitoringService->getHostName()]['name'] = $pMonitoringService->getHostName();
             $cs_info_hosts[$pMonitoringService->getHostName()]['services'][$pMonitoringService->getName()]['id'] = $pMonitoringService->fields['id'];
             $cs_info_hosts[$pMonitoringService->getHostName()]['services'][$pMonitoringService->getName()]['state'] = $pMonitoringService->fields['state'];
             $cs_info_hosts[$pMonitoringService->getHostName()]['services'][$pMonitoringService->getName()]['last_check'] = $pMonitoringService->fields['last_check'];
             $cs_info_hosts[$pMonitoringService->getHostName()]['services'][$pMonitoringService->getName()]['event'] = $pMonitoringService->fields['event'];
             // Get all host services except if state is ok or is already acknowledged ...
             $a_ret = PluginMonitoringHost::getServicesState($pMonitoringService->getHostId(), "`glpi_plugin_monitoring_services`.`state` != 'OK'");
             $cs_info_hosts[$pMonitoringService->getHostName()]['state'] = $a_ret[0];
             $cs_info_services[$pMonitoringService->getName()] = $pMonitoringService->fields['plugin_monitoring_components_id'];
             switch ($pMonitoringService->fields['state']) {
                 case 'UP':
                 case 'OK':
                     $state['OK']++;
                     break;
                 case 'DOWN':
                 case 'UNREACHABLE':
                 case 'CRITICAL':
                 case 'DOWNTIME':
                     $state['CRITICAL']++;
                     break;
                 case 'WARNING':
                 case 'UNKNOWN':
                 case 'RECOVERY':
                 case 'FLAPPING':
                     $state['WARNING']++;
                     break;
             }
         }
         if ($state['CRITICAL'] >= 1) {
             $a_gstate[$gdata['id']] = "CRITICAL";
         } else {
             if ($state['WARNING'] >= 1) {
                 $a_gstate[$gdata['id']] = "WARNING";
             } else {
                 $a_gstate[$gdata['id']] = "OK";
             }
         }
         $cs_info[$gdata['id']] = array();
         $cs_info[$gdata['id']]['name'] = $gdata['name'];
         $cs_info[$gdata['id']]['state'] = $a_gstate[$gdata['id']];
         $cs_info[$gdata['id']]['hosts'] = $cs_info_hosts;
         $cs_info[$gdata['id']]['services'] = $cs_info_services;
     }
     $state = array();
     $state['OK'] = 0;
     $state['WARNING'] = 0;
     $state['CRITICAL'] = 0;
     foreach ($a_gstate as $value) {
         $state[$value]++;
     }
     $color = 'green';
     if ($state['CRITICAL'] > 0) {
         $color = 'red';
         $colorclass = 'crit';
     } else {
         if ($state['WARNING'] > 0) {
             $color = 'orange';
             $colorclass = 'warn';
         }
     }
     echo '<div class="ch-itemdown">
      <div class="ch-info-' . $colorclass . '">
      <p><font style="font-size: 20px;">';
     if ($colorclass != 'ok') {
         echo __('Degraded mode', 'monitoring') . '!';
     }
     echo '</font></p>
      </div>
   </div>';
     // Show a minemap if requested ...
     echo "<div class='minemapdiv' align='center'>" . "<a onclick='\$(\"#minemapSC-" . $id . "\").toggle();'>" . __('Minemap', 'monitoring') . "</a></div>";
     if (!$is_minemap) {
         echo '<div class="minemapdiv" id="minemapSC-' . $id . '" style="display: none; z-index: 1500">';
     } else {
         echo '<div class="minemapdiv" id="minemapSC-' . $id . '">';
     }
     echo '<table class="tab_cadrehov">';
     foreach ($cs_info as $groupName => $group) {
         echo '<table class="tab_cadrehov">';
         echo '<tr>';
         echo '<th colspan="' . (1 + count($group['services'])) . '">' . __('Business rules group', 'monitoring') . "&nbsp; : " . $group['name'] . '</th>';
         echo '</tr>';
         echo '<tr>';
         echo "<th>";
         echo __('Hosts', 'monitoring');
         echo "</th>";
         foreach ($group['services'] as $serviceName => $service) {
             if (Session::haveRight("plugin_monitoring_service", READ)) {
                 $link = $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/service.php?hidesearch=1" . "&criteria[0][field]=2" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=" . $service . "&itemtype=PluginMonitoringService" . "&start=0'";
                 echo '<th class="vertical">';
                 echo '<a href="' . $link . '"><div class="rotated-text"><span class="rotated-text__inner">' . $serviceName . '</span></div></a>';
                 echo '</th>';
             } else {
                 echo '<th class="vertical">';
                 echo '<div class="rotated-text"><span class="rotated-text__inner">' . $serviceName . '</span></div>';
                 echo '</th>';
             }
         }
         echo '</tr>';
         foreach ($group['hosts'] as $host) {
             echo "<tr class='tab_bg_2' style='height: 50px;'>";
             if (Session::haveRight("plugin_monitoring_service", READ)) {
                 $link = $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/service.php?hidesearch=1" . "&criteria[0][field]=20" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=" . $host['id'] . "&itemtype=PluginMonitoringService" . "&start=0'";
                 echo "<td class='left'><a href='" . $link . "'>" . $host['name'] . "</a></td>";
             } else {
                 echo "<td class='left'>" . $host['name'] . "</td>";
             }
             // echo  "<td class='left'>".$host['name']."</td>";
             foreach ($host['services'] as $serviceName => $service) {
                 echo '<td>';
                 echo '<div title="' . $service['last_check'] . ' - ' . $service['event'] . '" class="service service' . $service['state'] . '"></div>';
                 echo '</td>';
             }
             echo '</tr>';
         }
         echo '</table>';
     }
     echo '</table>';
     echo '</div>';
 }
 function showWidget($id)
 {
     global $LANG, $DB, $CFG_GLPI;
     $pMonitoringBusinessrule = new PluginMonitoringBusinessrule();
     $pMonitoringBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
     $pMonitoringService = new PluginMonitoringService();
     $this->getFromDB($id);
     $data = $this->fields;
     $input = '';
     $input .= '<table  class="tab_cadre_fixe" style="width:200px;height:200px">';
     $input .= '<tr class="tab_bg_1">';
     $input .= '<th colspan="2" style="font-size:20px;" height="50">';
     $input .= $data['name'];
     $input .= '</th>';
     $input .= '</tr>';
     $input .= '<tr class="tab_bg_1">';
     $input .= '<td>';
     $input .= $LANG['state'][0] . "&nbsp;:";
     $input .= '</td>';
     $input .= '<td width="40">';
     switch ($data['state']) {
         case 'UP':
         case 'OK':
             $input .= '<img src="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/box_green_40.png"/>';
             break;
         case 'DOWN':
         case 'UNREACHABLE':
         case 'CRITICAL':
         case 'DOWNTIME':
             $input .= '<img src="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/box_red_40.png"/>';
             break;
         case 'WARNING':
         case 'UNKNOWN':
         case 'RECOVERY':
         case 'FLAPPING':
         case '':
             $input .= '<img src="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/box_orange_40.png"/>';
             break;
     }
     $input .= '</td>';
     $input .= '</tr>';
     $input .= '<tr class="tab_bg_1">';
     $input .= '<td>';
     $input .= $LANG['plugin_monitoring']['servicescatalog'][1] . "&nbsp;:";
     $input .= '</td>';
     $input .= '<td width="40" align="center">';
     $a_group = $pMonitoringBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $data['id'] . "'");
     $a_gstate = array();
     foreach ($a_group as $gdata) {
         $a_brules = $pMonitoringBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $gdata['id'] . "'");
         $state = array();
         $state['OK'] = 0;
         $state['WARNING'] = 0;
         $state['CRITICAL'] = 0;
         foreach ($a_brules as $brulesdata) {
             if ($pMonitoringService->getFromDB($brulesdata['plugin_monitoring_services_id'])) {
                 switch ($pMonitoringService->fields['state']) {
                     case 'UP':
                     case 'OK':
                         $state['OK']++;
                         break;
                     case 'DOWN':
                     case 'UNREACHABLE':
                     case 'CRITICAL':
                     case 'DOWNTIME':
                         $state['CRITICAL']++;
                         break;
                     case 'WARNING':
                     case 'UNKNOWN':
                     case 'RECOVERY':
                     case 'FLAPPING':
                         $state['WARNING']++;
                         break;
                 }
             }
         }
         if ($state['CRITICAL'] >= 1) {
             $a_gstate[$gdata['id']] = "CRITICAL";
         } else {
             if ($state['WARNING'] >= 1) {
                 $a_gstate[$gdata['id']] = "WARNING";
             } else {
                 $a_gstate[$gdata['id']] = "OK";
             }
         }
     }
     $state = array();
     $state['OK'] = 0;
     $state['WARNING'] = 0;
     $state['CRITICAL'] = 0;
     foreach ($a_gstate as $value) {
         $state[$value]++;
     }
     $color = 'green';
     if ($state['CRITICAL'] > 0) {
         $color = 'red';
     } else {
         if ($state['WARNING'] > 0) {
             $color = 'orange';
         }
     }
     $input .= '<img src="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/box_' . $color . '_32.png" />';
     $input .= '</td>';
     $input .= '</tr>';
     $input .= '<tr class="tab_bg_1">';
     $input .= '<td colspan="2" align="center">';
     $input .= '<a href="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/front/servicescatalog.form.php?id=' . $data['id'] . '&detail=1">Détail</a>';
     $input .= '</td>';
     $input .= '</tr>';
     $input .= '</table>';
     return $input;
 }
Esempio n. 6
0
   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;
      }
   }
 static function unlinkComponentsToItem($parm)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $query = "SELECT * FROM `glpi_plugin_monitoring_services`\n         WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $parm->fields['id'] . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $_SESSION['plugin_monitoring_hosts'] = $parm->fields;
         $pmService->delete(array('id' => $data['id']));
     }
 }
 function prepareInputForAdd($input)
 {
     // Toolbox::logInFile("pm-ack", "acknowledge, prepareInputForAdd, item type : ".$input['itemtype']." / ".$input['items_id']."\n");
     if ($this->isExpired()) {
         Session::addMessageAfterRedirect(__('Acknowledge period has already expired!', 'monitoring'), false, ERROR);
         return false;
     }
     // Check user ...
     if ($input["users_id"] == NOT_AVAILABLE) {
         $input["users_id"] = $_SESSION['glpiID'];
     }
     $user = new User();
     $user->getFromDB($input['users_id']);
     $item = new $input['itemtype']();
     $item->getFromDB($input['items_id']);
     $host_id = -1;
     $service_id = -1;
     if ($input['itemtype'] == 'PluginMonitoringHost') {
         $host_id = $input['items_id'];
     } else {
         $service_id = $input['items_id'];
     }
     if ($host_id != -1) {
         // Acknowledge is to be created ...
         // ... send information to shinken via webservice
         $pmShinkenwebservice = new PluginMonitoringShinkenwebservice();
         if ($pmShinkenwebservice->sendAcknowledge($host_id, -1, $user->getName(1), $input['comment'], $input['sticky'], $input['notify'], $input['persistent'], 'add')) {
             // Set host as acknowledged
             $item->setAcknowledged($input['comment']);
             $a_services = $item->getServicesID();
             if (is_array($a_services)) {
                 foreach ($a_services as $service_id) {
                     // Send acknowledge command for a service to shinken via webservice
                     $pmShinkenwebservice = new PluginMonitoringShinkenwebservice();
                     if ($pmShinkenwebservice->sendAcknowledge(-1, $service_id, $user->getName(1), $input['comment'], $input['sticky'], $input['notify'], $input['persistent'], 'add')) {
                         // Set service as acknowledged
                         $pmService = new PluginMonitoringService();
                         $pmService->getFromDB($service_id);
                         // Will force to create a new acknowledgement for a service ... beware of infinite loop in this function !
                         $pmService->setAcknowledged($input['comment'], true);
                     }
                 }
             }
             Session::addMessageAfterRedirect(__('Acknowledge notified to the monitoring application for the host', 'monitoring'));
             $input['notified'] = 1;
         } else {
             Session::addMessageAfterRedirect(__('Acknowledge has not been accepted by the monitoring application for the host', 'monitoring'), false, ERROR);
             return false;
         }
     } else {
         // Send acknowledge command for a service to shinken via webservice
         $pmShinkenwebservice = new PluginMonitoringShinkenwebservice();
         if ($pmShinkenwebservice->sendAcknowledge(-1, $service_id, $user->getName(1), $input['comment'], $input['sticky'], $input['notify'], $input['persistent'], 'add')) {
             // Set service as acknowledged
             $pmService = new PluginMonitoringService();
             $pmService->getFromDB($service_id);
             // Do not create a new acknowledgement for a service ... false will simply update PMService table !
             $pmService->setAcknowledged($input['comment'], false);
             Session::addMessageAfterRedirect(__('Acknowledge notified to the monitoring application:', 'monitoring'));
             $input['notified'] = 1;
         } else {
             Session::addMessageAfterRedirect(__('Acknowledge has not been accepted by the monitoring application:', 'monitoring'), false, ERROR);
             return false;
         }
     }
     return $input;
 }
Esempio n. 9
0
  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2013 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
Session::checkCentralAccess();
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "services");
$pmService = new PluginMonitoringService();
if (isset($_POST['update'])) {
    foreach ($_POST['arg'] as $key => $value) {
        if ($value == '') {
            unset($_POST['arg'][$key]);
        }
    }
    $_POST['arguments'] = exportArrayToDB($_POST['arg']);
    $pmService->update($_POST);
    Html::back();
}
if (PluginMonitoringProfile::haveRight("componentscatalog", 'w')) {
    $pmService->showCustomArguments($_GET['id']);
}
Html::footer();
 function showWidget($id)
 {
     global $LANG, $DB, $CFG_GLPI;
     $pmService = new PluginMonitoringService();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $input = '';
     $this->getFromDB($id);
     $data = $this->fields;
     $input .= '<table  class="tab_cadre_fixe" style="width:158px;">';
     $input .= '<tr class="tab_bg_1">';
     $input .= '<th colspan="2" style="font-size:18px;" height="60">';
     $input .= $data['name'] . "&nbsp;";
     $input .= '</th>';
     $input .= '</tr>';
     $stateg = array();
     $stateg['OK'] = 0;
     $stateg['WARNING'] = 0;
     $stateg['CRITICAL'] = 0;
     $a_gstate = array();
     $nb_ressources = 0;
     $query = "SELECT * FROM `" . $pmComponentscatalog_Host->getTable() . "`\n         WHERE `plugin_monitoring_componentscalalog_id`='" . $data['id'] . "'";
     $result = $DB->query($query);
     while ($dataComponentscatalog_Host = $DB->fetch_array($result)) {
         $queryService = "SELECT * FROM `" . $pmService->getTable() . "`\n            WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $dataComponentscatalog_Host['id'] . "'\n               AND `entities_id` IN (" . $_SESSION['glpiactiveentities_string'] . ")";
         $resultService = $DB->query($queryService);
         while ($dataService = $DB->fetch_array($resultService)) {
             $nb_ressources++;
             $state = array();
             $state['OK'] = 0;
             $state['WARNING'] = 0;
             $state['CRITICAL'] = 0;
             if ($dataService['state_type'] != "HARD") {
                 $a_gstate[$dataService['id']] = "OK";
             } else {
                 switch ($dataService['state']) {
                     case 'UP':
                     case 'OK':
                         $state['OK']++;
                         break;
                     case 'DOWN':
                     case 'UNREACHABLE':
                     case 'CRITICAL':
                     case 'DOWNTIME':
                         $state['CRITICAL']++;
                         break;
                     case 'WARNING':
                     case 'UNKNOWN':
                     case 'RECOVERY':
                     case 'FLAPPING':
                         $state['WARNING']++;
                         break;
                 }
                 if ($state['CRITICAL'] >= 1) {
                     $a_gstate[$dataService['id']] = "CRITICAL";
                 } else {
                     if ($state['WARNING'] >= 1) {
                         $a_gstate[$dataService['id']] = "WARNING";
                     } else {
                         $a_gstate[$dataService['id']] = "OK";
                     }
                 }
             }
         }
     }
     foreach ($a_gstate as $value) {
         $stateg[$value]++;
     }
     $input .= '<tr class="tab_bg_1">';
     $input .= '<td>';
     $input .= $LANG['plugin_monitoring']['service'][0] . "&nbsp;:";
     $input .= '</td>';
     $input .= '<th align="center" height="40" width="50%">';
     $link = $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/service.php?reset=reset&field[0]=8&searchtype[0]=equals&contains[0]=" . $id . "&itemtype=PluginMonitoringService&start=0&glpi_tab=3";
     $input .= '<a href="' . $link . '">' . $nb_ressources . '</a>';
     $input .= '</th>';
     $input .= '</tr>';
     $background = '';
     $count = 0;
     $link = '';
     if ($stateg['CRITICAL'] > 0) {
         $count = $stateg['CRITICAL'];
         $background = 'background="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/bg_critical.png"';
         $link = $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/service.php?reset=reset&field[0]=3&searchtype[0]=equals&contains[0]=CRITICAL" . "&link[1]=AND&field[1]=8&searchtype[1]=equals&contains[1]=" . $id . "&link[2]=OR&field[2]=3&searchtype[2]=equals&contains[2]=DOWN" . "&link[3]=AND&field[3]=8&searchtype[3]=equals&contains[3]=" . $id . "&link[4]=OR&field[4]=3&searchtype[4]=equals&contains[4]=UNREACHABLE" . "&link[5]=AND&field[5]=8&searchtype[5]=equals&contains[5]=" . $id . "&itemtype=PluginMonitoringService&start=0&glpi_tab=3";
     } else {
         if ($stateg['WARNING'] > 0) {
             $count = $stateg['WARNING'];
             $background = 'background="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/bg_warning.png"';
             $link = $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/service.php?reset=reset&field[0]=3&searchtype[0]=equals&contains[0]=WARNING" . "&link[1]=AND&field[1]=8&searchtype[1]=equals&contains[1]=" . $id . "&link[2]=OR&field[2]=3&searchtype[2]=equals&contains[2]=UNKNOWN" . "&link[3]=AND&field[3]=8&searchtype[3]=equals&contains[3]=" . $id . "&link[4]=OR&field[4]=3&searchtype[4]=equals&contains[4]=RECOVERY" . "&link[5]=AND&field[5]=8&searchtype[5]=equals&contains[5]=" . $id . "&link[6]=OR&field[6]=3&searchtype[6]=equals&contains[6]=FLAPPING" . "&link[7]=AND&field[7]=8&searchtype[7]=equals&contains[7]=" . $id . "&itemtype=PluginMonitoringService&start=0&glpi_tab=3";
         } else {
             if ($stateg['OK'] > 0) {
                 $count = $stateg['OK'];
                 $background = 'background="' . $CFG_GLPI['root_doc'] . '/plugins/monitoring/pics/bg_ok.png"';
                 $link = $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/service.php?reset=reset&field[0]=3&searchtype[0]=equals&contains[0]=OK" . "&link[1]=AND&field[1]=8&searchtype[1]=equals&contains[1]=" . $id . "&link[2]=OR&field[2]=3&searchtype[2]=equals&contains[2]=UP" . "&itemtype=PluginMonitoringService&start=0&glpi_tab=3";
             }
         }
     }
     $input .= "<tr " . $background . ">";
     $input .= '<th style="background-color:transparent;" ' . $background . ' colspan="2" height="100">';
     $input .= '<a href="' . $link . '"><font style="font-size: 52px; color:black">' . $count . '</font></a>';
     $input .= '</th>';
     $input .= '</tr>';
     $input .= '</table>';
     return $input;
 }
Esempio n. 11
0
   function drawMap($weathermaps_id, $widthw=100, $config=0) {
      global $DB, $CFG_GLPI;

      $this->getFromDB($weathermaps_id);

      PluginMonitoringSecurity::updateSession();

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

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

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

      var color = d3.scale.category10();

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

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

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

              echo ';


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

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


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

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

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

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

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

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

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

     ';

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

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

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


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


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

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

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

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

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

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

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

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

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

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


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

     };
';

echo '        </script>';


   }
Esempio n. 12
0
 static function convertArgument($services_id, $argument)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmService->getFromDB($services_id);
     $pmComponentscatalog_Host->getFromDB($pmService->fields['plugin_monitoring_componentscatalogs_hosts_id']);
     $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
     $item = new $itemtype();
     $item->getFromDB($pmComponentscatalog_Host->fields['items_id']);
     $argument = str_replace("[", "", $argument);
     $argument = str_replace("]", "", $argument);
     $a_arg = explode(":", $argument);
     $devicetype = '';
     $devicedata = array();
     if ($itemtype == "NetworkPort") {
         $itemtype2 = $item->fields['itemtype'];
         $item2 = new $itemtype2();
         $item2->getFromDB($item->fields['items_id']);
         $devicetype = $itemtype2;
         $devicedata = $item2->fields;
     } else {
         $devicetype = $itemtype;
         $devicedata = $item->fields;
     }
     if ($devicetype == "NetworkEquipment") {
         if (class_exists("PluginFusinvsnmpCommonDBTM")) {
             $PluginFusinvsnmpNetworkEquipment = new PluginFusinvsnmpCommonDBTM("glpi_plugin_fusinvsnmp_networkequipments");
             $PluginFusinvsnmpNetworkEquipment->load($devicedata['id']);
             switch ($a_arg[0]) {
                 case 'OID':
                     // Load SNMP model and get oid.portnum
                     $query = "SELECT `glpi_plugin_fusioninventory_mappings`.`name` AS `mapping_name`,\n                                   `glpi_plugin_fusinvsnmp_modelmibs`.*\n                            FROM `glpi_plugin_fusinvsnmp_modelmibs`\n                                 LEFT JOIN `glpi_plugin_fusioninventory_mappings`\n                                           ON `glpi_plugin_fusinvsnmp_modelmibs`.`plugin_fusioninventory_mappings_id`=\n                                              `glpi_plugin_fusioninventory_mappings`.`id`\n                            WHERE `plugin_fusinvsnmp_models_id`='" . $PluginFusinvsnmpNetworkEquipment->getValue("plugin_fusinvsnmp_models_id") . "'\n                              AND `is_active`='1'\n                              AND `oid_port_counter`='0'\n                              AND `glpi_plugin_fusioninventory_mappings`.`name`='" . $a_arg[1] . "'";
                     $result = $DB->query($query);
                     while ($data = $DB->fetch_array($result)) {
                         return Dropdown::getDropdownName('glpi_plugin_fusinvsnmp_miboids', $data['plugin_fusinvsnmp_miboids_id']) . "." . $item->fields['logical_number'];
                     }
                     return '';
                     break;
                 case 'SNMP':
                     if ($PluginFusinvsnmpNetworkEquipment->getValue("plugin_fusinvsnmp_configsecurities_id") == '0') {
                         switch ($a_arg[1]) {
                             case 'version':
                                 return '2c';
                                 break;
                             case 'authentication':
                                 return 'public';
                                 break;
                         }
                     }
                     $pFusinvsnmpConfigSecurity = new PluginFusinvsnmpConfigSecurity();
                     $pFusinvsnmpConfigSecurity->getFromDB($PluginFusinvsnmpNetworkEquipment->getValue("plugin_fusinvsnmp_configsecurities_id"));
                     switch ($a_arg[1]) {
                         case 'version':
                             if ($pFusinvsnmpConfigSecurity->fields['snmpversion'] == '2') {
                                 $pFusinvsnmpConfigSecurity->fields['snmpversion'] = '2c';
                             }
                             return $pFusinvsnmpConfigSecurity->fields['snmpversion'];
                             break;
                         case 'authentication':
                             return $pFusinvsnmpConfigSecurity->fields['community'];
                             break;
                     }
                     break;
             }
         }
     }
     return $argument;
 }
Esempio n. 13
0
  ------------------------------------------------------------------------

  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2012 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
define('GLPI_ROOT', '../..');
include GLPI_ROOT . "/inc/includes.php";
$a_services = array();
$pmService = new PluginMonitoringService();
$a_services = $pmService->find("`plugin_monitoring_components_id`='12'");
for ($i = 0; $i < 1000000000; $i++) {
    foreach ($a_services as $id => $data) {
        $perf = "inUsage=0.00%;85;98 outUsage=0.00%;85;98 " . "inBandwidth=" . rand(1, 100000) . ".00bps outBandwidth=" . rand(1, 100000) . ".00bps inAbsolut=0 outAbsolut=12665653";
        $ins = "INSERT INTO `glpi_plugin_monitoring_serviceevents`\n         (`plugin_monitoring_services_id`, `date`, `perf_data`, `state`, `state_type`)\n         VALUES('" . $id . "', '" . date('Y-m-d H:i:s') . "', '" . $perf . "', 'OK', 'HARD')";
        $DB->query($ins);
        $rand = rand(0, 100);
        if ($rand < 40) {
            sleep(1);
        }
    }
}
commonFooter();
   function getRessources($componentscatalogs_id, $state, $state_type='HARD') {
      global $DB;

      $a_services = array();

      $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
      $pmService = new PluginMonitoringService();

      $query = "SELECT * FROM `glpi_plugin_monitoring_services`
         LEFT JOIN `".$pmComponentscatalog_Host->getTable()."`
            ON `plugin_monitoring_componentscatalogs_hosts_id`=
               `".$pmComponentscatalog_Host->getTable()."`.`id`
         WHERE `plugin_monitoring_componentscalalog_id`='".$componentscatalogs_id."'
            AND `state_type` LIKE '".$state_type."'
         ORDER BY `name`";
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         $pmService->getFromDB($dataService["id"]);
         if ($pmService->getShortState()) {
         // if (PluginMonitoringHost::getState($data['state'],
                                               // $data['state_type'],
                                               // '',
                                               // $data['is_acknowledged']) == $state) {
            $a_services[] = $data;
         }
      }
      return $a_services;
   }
Esempio n. 15
0
 function parseToDB($plugin_monitoring_services_id)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $pmComponent = new PluginMonitoringComponent();
     if ($pmService->getFromDB($plugin_monitoring_services_id)) {
         $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
         if (!isset($pmComponent->fields['plugin_monitoring_commands_id'])) {
             return;
         }
         if (is_null($pmComponent->fields['graph_template'])) {
             return;
         }
         $pmUnavaibility = new PluginMonitoringUnavaibility();
         $pmUnavaibility->runUnavaibility($plugin_monitoring_services_id);
         $a_dateold = array();
         // *** 1 day (x 30 min)
         $dateold = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m'), date('d') - 1, date('Y')));
         $a_dateold['30m'] = $dateold;
         // Gest last value, and see if we must calculate new values
         $query = "SELECT * FROM `" . $this->getTable() . "`\n               WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                  AND `type`='30m'\n               ORDER BY `date` DESC\n               LIMIT 1";
         $result = $DB->query($query);
         $lastdate = $dateold;
         $new_date = '';
         if ($DB->numrows($result) == '1') {
             $data = $DB->fetch_assoc($result);
             $new_date = PluginMonitoringServiceevent::convert_datetime_timestamp($data['date']);
             $new_date += 30 * 60;
         } else {
             $split = explode(" ", $lastdate);
             $a_time = explode(":", $split[1]);
             $a_date = explode("-", $split[0]);
             $new_date = date('U', mktime($a_time[0], '0', '0', $a_date[1], $a_date[2], $a_date[0]));
         }
         //get data in serviceevents for each 30 minutes from this date to now
         while ($new_date + 15 * 60 < date('U')) {
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                  WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                     AND `date` >= '" . date('Y-m-d H:i:m', $new_date - 15 * 60) . "'\n                     AND`date` <= '" . date('Y-m-d H:i:m', $new_date + 15 * 60) . "'\n                  ORDER BY `date`";
             $result = $DB->query($query);
             // get data
             $mydatat = array();
             $pmServiceevent = new PluginMonitoringServiceevent();
             $pmService = new PluginMonitoringService();
             $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template']);
             if (is_array($ret)) {
                 $mydatat = $ret[0];
             }
             $array_data = array();
             foreach ($mydatat as $name => $a_values) {
                 $valfloat = array_sum($a_values) / count($a_values);
                 if ($valfloat > 2) {
                     $array_data[$name] = round($valfloat);
                 } else {
                     $array_data[$name] = round($valfloat, 2);
                 }
             }
             $input = array();
             $input['plugin_monitoring_services_id'] = $plugin_monitoring_services_id;
             $input['date'] = date('Y-m-d H:i:s', $new_date);
             $input['data'] = exportArrayToDB($array_data);
             $input['type'] = '30m';
             $this->add($input);
             $new_date = $new_date + 30 * 60;
         }
         // *** 1w (x 6 hours)
         $dateold = date('Y-m-d H:i:s', date('U') - 7 * 24 * 3600);
         $a_dateold['6h'] = $dateold;
         // Gest last value, and see if we must calculate new values
         $query = "SELECT * FROM `" . $this->getTable() . "`\n               WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                  AND `type`='6h'\n               ORDER BY `date` DESC\n               LIMIT 1";
         $result = $DB->query($query);
         $lastdate = $dateold;
         $new_date = '';
         if ($DB->numrows($result) == '1') {
             $data = $DB->fetch_assoc($result);
             $new_date = PluginMonitoringServiceevent::convert_datetime_timestamp($data['date']);
             $new_date += 6 * 3600;
         } else {
             $split = explode(" ", $lastdate);
             $a_time = explode(":", $split[1]);
             $a_date = explode("-", $split[0]);
             $hour = '0';
             $addtime = 0;
             if ($a_time[0] > 18) {
                 $hour = 0;
                 $addtime = 24 * 3600;
             } else {
                 if ($a_time[0] > 12) {
                     $hour = 18;
                 } else {
                     if ($a_time[0] > 6) {
                         $hour = 12;
                     } else {
                         $hour = 6;
                     }
                 }
             }
             $new_date = date('U', mktime($hour, '0', '0', $a_date[1], $a_date[2], $a_date[0])) + $addtime;
         }
         //get data in serviceevents for each 6 hours from this date to now
         while ($new_date + 3 * 3600 < date('U')) {
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                  WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                     AND `date` >= '" . date('Y-m-d H:i:m', $new_date - 3 * 3600) . "'\n                     AND`date` <= '" . date('Y-m-d H:i:m', $new_date + 3 * 3600) . "'\n                  ORDER BY `date`";
             $result = $DB->query($query);
             // get data
             $mydatat = array();
             $pmServiceevent = new PluginMonitoringServiceevent();
             $pmService = new PluginMonitoringService();
             $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template']);
             if (is_array($ret)) {
                 $mydatat = $ret[0];
             }
             $array_data = array();
             foreach ($mydatat as $name => $a_values) {
                 $valfloat = array_sum($a_values) / count($a_values);
                 if ($valfloat > 2) {
                     $array_data[$name] = round($valfloat);
                 } else {
                     $array_data[$name] = round($valfloat, 2);
                 }
             }
             $input = array();
             $input['plugin_monitoring_services_id'] = $plugin_monitoring_services_id;
             $input['date'] = date('Y-m-d H:i:s', $new_date);
             $input['data'] = exportArrayToDB($array_data);
             $input['type'] = '6h';
             $this->add($input);
             $new_date = $new_date + 6 * 3600;
         }
         // *** 1m (x 1 day)
         $dateold = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m') - 1, date('d'), date('Y')));
         //            $a_dateold['1d'] = $dateold; //NOTE to keep data for each day (if we want use it in future)
         // Gest last value, and see if we must calculate new values
         $query = "SELECT * FROM `" . $this->getTable() . "`\n               WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                  AND `type`='1d'\n               ORDER BY `date` DESC\n               LIMIT 1";
         $result = $DB->query($query);
         $lastdate = $dateold;
         $new_date = '';
         if ($DB->numrows($result) == '1') {
             $data = $DB->fetch_assoc($result);
             $new_date = PluginMonitoringServiceevent::convert_datetime_timestamp($data['date']);
             $new_date += 24 * 3600;
         } else {
             $split = explode(" ", $lastdate);
             $a_date = explode("-", $split[0]);
             $new_date = date('U', mktime('0', '0', '0', $a_date[1], $a_date[2], $a_date[0]));
         }
         //get data in serviceevents for each 6 hours from this date to now
         while ($new_date + 12 * 3600 < date('U')) {
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                  WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                     AND `date` >= '" . date('Y-m-d H:i:m', $new_date - 12 * 3600) . "'\n                     AND`date` <= '" . date('Y-m-d H:i:m', $new_date + 12 * 3600) . "'\n                  ORDER BY `date`";
             $result = $DB->query($query);
             // get data
             $mydatat = array();
             $pmServiceevent = new PluginMonitoringServiceevent();
             $pmService = new PluginMonitoringService();
             $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template']);
             if (is_array($ret)) {
                 $mydatat = $ret[0];
             }
             $array_data = array();
             foreach ($mydatat as $name => $a_values) {
                 $valfloat = array_sum($a_values) / count($a_values);
                 if ($valfloat > 2) {
                     $array_data[$name] = round($valfloat);
                 } else {
                     $array_data[$name] = round($valfloat, 2);
                 }
             }
             $input = array();
             $input['plugin_monitoring_services_id'] = $plugin_monitoring_services_id;
             $input['date'] = date('Y-m-d H:i:s', $new_date);
             $input['data'] = exportArrayToDB($array_data);
             $input['type'] = '1d';
             $this->add($input);
             $new_date = $new_date + 24 * 3600;
         }
         // *** 6m (x 5 days)
         $dateold = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m') - 6, date('d'), date('Y')));
         $a_dateold['5d'] = $dateold;
         // Gest last value, and see if we must calculate new values
         $query = "SELECT * FROM `" . $this->getTable() . "`\n               WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                  AND `type`='5d'\n               ORDER BY `date` DESC\n               LIMIT 1";
         $result = $DB->query($query);
         $lastdate = $dateold;
         $new_date = '';
         if ($DB->numrows($result) == '1') {
             $data = $DB->fetch_assoc($result);
             $new_date = PluginMonitoringServiceevent::convert_datetime_timestamp($data['date']);
             $new_date += 5 * 24 * 3600;
         } else {
             $split = explode(" ", $lastdate);
             $a_date = explode("-", $split[0]);
             $new_date = date('U', mktime('0', '0', '0', $a_date[1], $a_date[2], $a_date[0]));
         }
         //get data in serviceevents for each 6 hours from this date to now
         while ($new_date + 5 * 24 * 3600 / 2 < date('U')) {
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                  WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                     AND `date` >= '" . date('Y-m-d H:i:m', $new_date - 5 * 24 * 3600 / 2) . "'\n                     AND`date` <= '" . date('Y-m-d H:i:m', $new_date + 5 * 24 * 3600 / 2) . "'\n                  ORDER BY `date`";
             $result = $DB->query($query);
             // get data
             $mydatat = array();
             $pmServiceevent = new PluginMonitoringServiceevent();
             $pmService = new PluginMonitoringService();
             $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template']);
             if (is_array($ret)) {
                 $mydatat = $ret[0];
             }
             $array_data = array();
             foreach ($mydatat as $name => $a_values) {
                 $valfloat = array_sum($a_values) / count($a_values);
                 if ($valfloat > 2) {
                     $array_data[$name] = round($valfloat);
                 } else {
                     $array_data[$name] = round($valfloat, 2);
                 }
             }
             $input = array();
             $input['plugin_monitoring_services_id'] = $plugin_monitoring_services_id;
             $input['date'] = date('Y-m-d H:i:s', $new_date);
             $input['data'] = exportArrayToDB($array_data);
             $input['type'] = '5d';
             $this->add($input);
             $new_date = $new_date + 5 * 24 * 3600;
         }
         // *** 1y (x 10 days)
         $dateold = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m') - 10, date('d'), date('Y')));
         $a_dateold['5d'] = $dateold;
         // Gest last value, and see if we must calculate new values
         $query = "SELECT * FROM `" . $this->getTable() . "`\n               WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                  AND `type`='10d'\n               ORDER BY `date` DESC\n               LIMIT 1";
         $result = $DB->query($query);
         $lastdate = $dateold;
         $new_date = '';
         if ($DB->numrows($result) == '1') {
             $data = $DB->fetch_assoc($result);
             $new_date = PluginMonitoringServiceevent::convert_datetime_timestamp($data['date']);
             $new_date += 10 * 24 * 3600;
         } else {
             $split = explode(" ", $lastdate);
             $a_date = explode("-", $split[0]);
             $new_date = date('U', mktime('0', '0', '0', $a_date[1], $a_date[2], $a_date[0]));
         }
         //get data in serviceevents for each 6 hours from this date to now
         while ($new_date + 5 * 24 * 3600 < date('U')) {
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                  WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                     AND `date` >= '" . date('Y-m-d H:i:m', $new_date - 5 * 24 * 3600) . "'\n                     AND`date` <= '" . date('Y-m-d H:i:m', $new_date + 5 * 24 * 3600) . "'\n                  ORDER BY `date`";
             $result = $DB->query($query);
             // get data
             $mydatat = array();
             $pmServiceevent = new PluginMonitoringServiceevent();
             $pmService = new PluginMonitoringService();
             $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template']);
             if (is_array($ret)) {
                 $mydatat = $ret[0];
             }
             $array_data = array();
             foreach ($mydatat as $name => $a_values) {
                 $valfloat = array_sum($a_values) / count($a_values);
                 if ($valfloat > 2) {
                     $array_data[$name] = round($valfloat);
                 } else {
                     $array_data[$name] = round($valfloat, 2);
                 }
             }
             $input = array();
             $input['plugin_monitoring_services_id'] = $plugin_monitoring_services_id;
             $input['date'] = date('Y-m-d H:i:s', $new_date);
             $input['data'] = exportArrayToDB($array_data);
             $input['type'] = '10d';
             $this->add($input);
             $new_date = $new_date + 10 * 24 * 3600;
         }
         // *** Delete old values
         foreach ($a_dateold as $name => $date) {
             $query = "DELETE FROM `" . $this->getTable() . "`\n               WHERE `plugin_monitoring_services_id`='" . $plugin_monitoring_services_id . "'\n                  AND `type`='" . $name . "'\n                  AND `date` < '" . $date . "'";
             $result = $DB->query($query);
         }
     }
 }
 function removeComponentToItems($componentscatalogs_id, $components_id)
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n         WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $querys = "SELECT * FROM `glpi_plugin_monitoring_services`\n            WHERE `plugin_monitoring_componentscatalogs_hosts_id`='" . $data['id'] . "'\n               AND `plugin_monitoring_components_id`='" . $components_id . "'";
         $results = $DB->query($querys);
         while ($datas = $DB->fetch_array($results)) {
             $_SESSION['plugin_monitoring_hosts'] = $data;
             $pmService->delete(array('id' => $datas['id']));
         }
     }
 }
 static function displayLine($data, $displayhost = 1, $displayCounters = 0, $displayGraphs = true)
 {
     global $CFG_GLPI;
     $pMonitoringService = new PluginMonitoringService();
     $pMonitoringService->getFromDB($data['id']);
     $pMonitoringComponent = new PluginMonitoringComponent();
     $pMonitoringComponent->getFromDB($data[1][0]['id']);
     $networkPort = new NetworkPort();
     // If host is acknowledged, force service to be displayed as unknown acknowledged.
     if (isset($data[7][0]['name']) && $data[7][0]['name']) {
         $shortstate = 'yellowblue';
         $data['state'] = 'UNKNOWN';
     } else {
         $shortstate = PluginMonitoringHost::getState($data[2]['displayname'], $data[3]['displayname'], $data[5]['displayname'], $pMonitoringService->isCurrentlyAcknowledged());
     }
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if ($displayGraphs) {
         if (!isset($_SESSION['plugin_monitoring_reduced_interface']) || !$_SESSION['plugin_monitoring_reduced_interface']) {
             echo "<td class='center'>";
             // Even if not exist incremental perfdata ...
             if ($pMonitoringComponent->hasPerfdata()) {
                 echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['id'] . "'>";
                 ob_start();
                 $pmServicegraph = new PluginMonitoringServicegraph();
                 $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "div", "600");
                 $div = ob_get_contents();
                 ob_end_clean();
                 $chart = "<table width='600' class='tab_cadre'><tr><td>" . $div . "</td></tr></table>";
                 $qtip = Html::showToolTip($chart, array('img' => $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/stats_32.png' width='26' height='32'", 'display' => false));
                 $qtip = str_replace('qtip-shadow qtip-bootstrap', 'qtip-shadow qtip-bootstrap qtip-monitoring', $qtip);
                 echo $qtip;
                 $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "js");
                 echo "</a>";
             }
             echo "</td>";
         }
     }
     if ($displayhost) {
         $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
         $pmComponentscatalog_Host->getFromDB($data[10]["displayname"]);
         if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
             echo "<td>";
             $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
             $item = new $itemtype();
             $item->getFromDB($pmComponentscatalog_Host->fields['items_id']);
             // echo "<span>".$item->getLink(array ("monitoring" => "1"))."</span>&nbsp;";
             if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
                 $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
                 echo "[" . $networkPort->getLink() . "] ";
             }
             $pm_Host = new PluginMonitoringHost();
             $pm_Host->getFromDB($pMonitoringService->getHostID());
             echo "<span>" . $pm_Host->getLink(array("monitoring" => "1")) . "</span>";
             echo "</td>";
         } else {
             echo "<td>" . __('Resources', 'monitoring') . "</td>";
         }
     }
     echo "<td>";
     if (Session::haveRight("plugin_monitoring_component", READ)) {
         echo $pMonitoringComponent->getLink();
     } else {
         echo $pMonitoringComponent->getName();
     }
     if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
         $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
         echo " [" . $networkPort->getLink() . "]";
     }
     echo "</td>";
     if ($displayCounters) {
         $ar_counters = $pMonitoringComponent->hasCounters();
         // Toolbox::logInFile("pm", "Counters : ".serialize($ar_counters)."\n");
         if (is_array($ar_counters)) {
             $pmServicegraph = new PluginMonitoringServicegraph();
             foreach ($ar_counters as $counter => $counter_title) {
                 PluginMonitoringDisplay::$ar_counterTypes[$counter] = $counter_title;
                 $html = $pmServicegraph->displayCounter($pMonitoringComponent->fields['graph_template'], $data['id'], false, $counter, $counter_title);
                 echo "<td class='center'>{$html}</td>";
             }
         }
     } else {
         echo "<td class='center page foldtl resource" . $data[2]['displayname'] . " resource" . $data[3]['displayname'] . "'>";
         echo "<div class=''>";
         echo "<div>";
         echo $data[2]['displayname'];
         echo "</div>";
         echo "</div>";
         echo "</td>";
         echo "<td>";
         echo Html::convDate($data[4]['displayname']) . ' ' . substr($data[4]['displayname'], 11, 8);
         echo "</td>";
         echo "<td>";
         echo $data[5]['displayname'];
         echo "</td>";
         echo "<td align='center'>";
         $segments = CalendarSegment::getSegmentsBetween($pMonitoringComponent->fields['calendars_id'], date('w', date('U')), date('H:i:s'), date('w', date('U')), date('H:i:s'));
         if (count($segments) == '0') {
             echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_pause.png' />";
         } else {
             echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_run.png' />";
         }
         echo "</td>";
         if (!$displayhost) {
             $pmUnavailability = new PluginMonitoringUnavailability();
             $pmUnavailability->displayValues($pMonitoringService->fields['id'], 'currentmonth', 1);
             $pmUnavailability->displayValues($pMonitoringService->fields['id'], 'lastmonth', 1);
             $pmUnavailability->displayValues($pMonitoringService->fields['id'], 'currentyear', 1);
             echo "<td class='center'>";
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/unavailability.php?" . "&criteria[0][field]=2" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=" . $pMonitoringService->fields['id'] . "&itemtype=PluginMonitoringUnavailability" . "&start=0" . "&sort=1" . "&order=DESC'>\n               <img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/info.png'/></a>";
             echo "</td>";
         }
         if (Session::haveRight("plugin_monitoring_acknowledge", READ)) {
             echo "<td>";
             if ($pMonitoringService->isCurrentlyAcknowledged()) {
                 if (Session::haveRight("plugin_monitoring_acknowledge", CREATE)) {
                     echo "<span>";
                     echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/acknowledge.form.php?itemtype=Service&items_id=" . $data['id'] . "'>" . "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/acknowledge_ok.png'" . " alt='" . htmlspecialchars(__('Modify acknowledge comment for the service', 'monitoring'), ENT_QUOTES) . "'" . " title='" . htmlspecialchars(__('Modify acknowledge comment for the service', 'monitoring'), ENT_QUOTES) . "'" . " width='25' height='20'/>" . "</a>";
                     echo "&nbsp;&nbsp;</span>";
                 } else {
                     echo "<span>";
                     echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/acknowledge_ok.png'" . " alt='" . htmlspecialchars(__('Service problem has been acknowledged', 'monitoring'), ENT_QUOTES) . "'" . " title='" . htmlspecialchars(__('Service problem has been acknowledged', 'monitoring'), ENT_QUOTES) . "'" . " width='25' height='20'/>";
                     echo "&nbsp;&nbsp;</span>";
                 }
                 // Display acknowledge data ...
                 $pMonitoringService->getAcknowledge();
             } else {
                 if ($shortstate == 'red' || $shortstate == 'yellow' || $shortstate == 'orange' || !empty($data['host_services_state_list'])) {
                     if (Session::haveRight("plugin_monitoring_acknowledge", CREATE)) {
                         echo "<span>";
                         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/acknowledge.form.php?itemtype=Service&items_id=" . $data['id'] . "'>" . "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/acknowledge_ko.png'" . " alt='" . htmlspecialchars(__('Add an acknowledge for the service', 'monitoring'), ENT_QUOTES) . "'" . " title='" . htmlspecialchars(__('Add an acknowledge for the service', 'monitoring'), ENT_QUOTES) . "'" . " width='25' height='20'/>" . "</a>";
                         echo "&nbsp;&nbsp;</span>";
                     }
                 }
             }
             echo "</td>";
         }
     }
     if ($displayhost == '0') {
         echo "<td>";
         if (Session::haveRight("plugin_monitoring_componentscatalog", UPDATE)) {
             if ($pMonitoringComponent->fields['remotesystem'] == 'nrpe' && $pMonitoringComponent->fields['is_arguments'] == 0) {
                 echo __('Managed by NRPE', 'monitoring');
             } else {
                 $a_arg = importArrayFromDB($pMonitoringService->fields['arguments']);
                 $cnt = '';
                 if (count($a_arg) > 0) {
                     $cnt = " (" . count($a_arg) . ")";
                 }
                 echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/servicearg.form.php?id=" . $data['id'] . "'>" . __('Configure', 'monitoring') . $cnt . "</a>";
             }
         }
         echo "</td>";
     }
 }
Esempio n. 18
0
   /**
    * Form to modify acknowledge on a service
    */
   function showUpdateAcknowledgeForm($id='-1') {
      global $CFG_GLPI;

      Session::checkRight("plugin_monitoring_acknowledge", UPDATE);

      if ($id == -1) {
         $pm_Service = $this;
      } else {
         $pm_Service = new PluginMonitoringService();
         $pm_Service->getFromDB($id);
      }

      // Modify acknowledge of a service ...
      echo "<form name='form' method='post'
         action='".$CFG_GLPI['root_doc']."/plugins/monitoring/front/acknowledge.form.php'>";
      echo "<table class='tab_cadre_fixe'>";
      echo "<tr class='tab_bg_1'>";
      echo "<th colspan='2'>";
      echo __('Modify acknowledge for the service', 'monitoring').' : '.$pm_Service->getName();
      echo "</td>";
      echo "</tr>";

      echo "</td>";
      echo "</tr>";
      echo "<tr class='tab_bg_1'>";
      echo "<td>";
      echo __('Acknowledge comment', 'monitoring');
      echo "</td>";
      echo "<td>";
      echo "<textarea cols='80' rows='4' name='acknowledge_comment' >".$pm_Service->fields['acknowledge_comment']."</textarea>";
      echo "</td>";
      echo "</tr>";
      echo "<tr class='tab_bg_1'>";
      echo "<td colspan='2' align='center'>";
      echo "<input type='hidden' name='id' value='".$pm_Service->fields['id']."' />";
      echo "<input type='hidden' name='is_acknowledged' value='1' />";
      echo "<input type='hidden' name='acknowledge_users_id' value='".$_SESSION['glpiID']."' />";
      echo "<input type='hidden' name='referer' value='".$_SERVER['HTTP_REFERER']."' />";

      echo "<tr class='tab_bg_1'>";
      echo "<td>";
      echo __('Acknowledge user', 'monitoring');
      echo "</td>";
      echo "<td>";
      $user = new User();
      $user->getFromDB($pm_Service->fields['acknowledge_users_id']);
      echo $user->getName(1);
      echo "</td>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td colspan='3' align='center'>";
      echo "<input type='submit' name='update' value=\"".__('Update acknowledge comment', 'monitoring')."\" class='submit'>";
      echo "</td>";
      echo "</tr>";

      echo "</table>";
      Html::closeForm();
   }
Esempio n. 19
0
   /**
    * Form to add acknowledge on an host
    */
   function showAddAcknowledgeForm($id, $allServices=false) {
      global $CFG_GLPI,$DB;

      if ($id == -1) {
         $pm_Host = $this;
      } else {
         $pm_Host = new PluginMonitoringHost();
         $pm_Host->getFromDB($id);
      }
      $hostname = $pm_Host->getName();
      $id = $pm_Host->fields['id'];

      if (empty($hostname)) return false;

      // Acknowledge an host ...
      echo "<form name='form' method='post'
            action='".$CFG_GLPI['root_doc']."/plugins/monitoring/front/acknowledge.form.php'>";

      echo "<input type='hidden' name='host_id' value='$id' />";
      echo "<input type='hidden' name='hostname' value='$hostname' />";

      echo "<table class='tab_cadre_fixe'>";
      echo "<tr class='tab_bg_1'>";
      echo "<th colspan='3'>";
      if ($allServices) {
         echo __('Add an acknowledge for all faulty services of the host', 'monitoring').' : '.$pm_Host->getLink();
      } else {
         echo __('Add an acknowledge for the host and all faulty services of the host', 'monitoring').' : '.$pm_Host->getLink();
      }
      echo "</td>";
      echo "</tr>";

      echo "<tr><td colspan='3'><hr/></td></tr>";

      // Acknowledge host AND all faulty services ...
      // Get all host services except if state is ok or is already acknowledged ...
      $a_ret = PluginMonitoringHost::getServicesState($id,
                                                      "`glpi_plugin_monitoring_services`.`state` != 'OK'
                                                      AND `glpi_plugin_monitoring_services`.`is_acknowledged` = '0'");
      $host_services_state = $a_ret[0];
      $host_services_state_list = $a_ret[1];
      $host_services = $a_ret[2];

      if (count($host_services)) {
         echo "<tr><td colspan='3'>".__('All these services will be acknowledged', 'monitoring')." : </td></tr>";
         echo "<input type='hidden' name='serviceCount' value='".count($host_services)."' />";

         $i=0;
         foreach ($host_services as $data) {
            // Toolbox::logInFile("pm", "data : ".serialize($data)."\n");
            $pmService = new PluginMonitoringService();
            $pmService->getFromDB($data);
            echo "<tr class='tab_bg_1'>";
            echo "<td colspan='1'></td>";
            echo "<td colspan='2'>".Html::convDateTime($pmService->fields['last_check'])." : ".$pmService->fields['name']." - ".$pmService->fields['state']." : ".$pmService->fields['event']."</td>";
            echo "</tr>";
            echo "<input type='hidden' name='serviceId$i' value='".$pmService->fields['id']."' />";
            $i++;
         }
         echo "<tr><td colspan='3'><hr/></td></tr>";
      }

      if (! $allServices) {
         echo "<input type='hidden' name='hostAcknowledge' value='$hostname' />";
      }

      echo "<tr class='tab_bg_1'>";
      echo "<td>";
      echo __('Acknowledge comment', 'monitoring');
      echo "</td>";
      echo "<td colspan='2'>";
      echo "<textarea cols='80' rows='4' name='acknowledge_comment' ></textarea>";
      echo "</td>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td colspan='3' align='center'>";
      echo "<input type='hidden' name='id' value='$id' />";
      echo "<input type='hidden' name='is_acknowledged' value='1' />";
      echo "<input type='hidden' name='acknowledge_users_id' value='".$_SESSION['glpiID']."' />";
      echo "<input type='hidden' name='referer' value='".$_SERVER['HTTP_REFERER']."' />";

      echo "<input type='submit' name='add' value=\"".__('Add an acknowledge for host', 'monitoring')."\" class='submit'>";
      echo "</td>";
      echo "</tr>";

      if (Session::haveRight('create_ticket', 1)) {
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='3' align='center'>";
         echo "<input type='hidden' name='name' value='".__('Host is down', 'monitoring')."' />";
         echo "<input type='hidden' name='redirect' value='".$CFG_GLPI["root_doc"]."/front/ticket.form.php' />";
         echo "<input type='submit' name='add_and_ticket' value=\"".__('Add an acknowledge for host and create a ticket', 'monitoring')."\" class='submit'>";
         echo "</td>";
         echo "</tr>";
      }

      echo "</table>";
      Html::closeForm();

      return true;
   }
 function generateConfig($weathermaps_id)
 {
     global $DB, $CFG_GLPI;
     if ($weathermaps_id < 1) {
         return;
     }
     $conf = "\n";
     $pmWeathermapnode = new PluginMonitoringWeathermapnode();
     $pmComponent = new PluginMonitoringComponent();
     $pmService = new PluginMonitoringService();
     $this->getFromDB($weathermaps_id);
     if ($this->fields['background'] != '') {
         $conf .= "BACKGROUND " . GLPI_PLUGIN_DOC_DIR . "/monitoring/weathermapbg/" . $this->fields['background'] . "\n";
         //$conf .= "BACKGROUND http://192.168.20.194".$CFG_GLPI['root_doc']."/plugins/monitoring/front/send.php?file=weathermapbg/".$this->fields['background']."\n";
     }
     // image file to generate
     $conf .= "IMAGEOUTPUTFILE " . GLPI_PLUGIN_DOC_DIR . "/monitoring/weathermap-" . $weathermaps_id . ".png\n";
     $conf .= "\n";
     $conf .= "WIDTH " . $this->fields["width"] . "\nHEIGHT " . $this->fields["height"] . "\nHTMLSTYLE overlib\nTITLE " . $this->fields["name"] . "\nTIMEPOS 10 20 Cree le : " . convDateTime(date("Y-m-d H:i:s")) . "\n\nKEYPOS DEFAULT 10 " . ($this->fields["height"] - $this->fields["width"] / 16) . "\nKEYSTYLE  DEFAULT horizontal " . $this->fields["width"] / 4 . "\nKEYTEXTCOLOR 0 0 0\nKEYOUTLINECOLOR 0 0 0\nKEYBGCOLOR 255 255 255\nBGCOLOR 255 255 255\nTITLECOLOR 0 0 0\nTIMECOLOR 0 0 0\nSCALE DEFAULT 0.0001 0.1   255 255 255   255 255 255  \nSCALE DEFAULT 0.1 50   0 255 0   255 215 0  \nSCALE DEFAULT 50 100   255 215 0   255 0 0  \n\nSET key_hidezero_DEFAULT 1\n\n# End of global section\n\n# TEMPLATE-only NODEs:\nNODE DEFAULT\n\tMAXVALUE 100\n\n# TEMPLATE-only LINKs:\nLINK DEFAULT\n\tWIDTH 4\n\tBANDWIDTH 100M\n\n# regular NODEs:\n";
     $query = "SELECT * FROM `" . getTableForItemType("PluginMonitoringWeathermapnode") . "`\n         WHERE `plugin_monitoring_weathermaps_id`='" . $weathermaps_id . "'\n         ORDER BY `name`";
     $result = $DB->query($query);
     $link = '';
     while ($data = $DB->fetch_array($result)) {
         $name = $data['name'];
         if ($name == '') {
             $itemtype = $data['itemtype'];
             $item = new $itemtype();
             $item->getFromDB($data['items_id']);
             $name = $item->getName();
             $link = $item->getLinkURL();
         }
         $conf .= "NODE " . preg_replace("/[^A-Za-z0-9_]/", "", $data['name']) . "_" . $data['id'] . "\n" . "   LABEL " . $name . "\n" . "   POSITION " . $data['x'] . " " . $data['y'] . "\n";
         if ($link != '') {
             $conf .= "   INFOURL " . $link . "\n";
         }
         $conf .= "\n";
     }
     $conf .= "\n\n# regular LINKs:\n";
     $bwlabelpos = array();
     $bwlabelpos[0] = "BWLABELPOS 81 39";
     $bwlabelpos[1] = "BWLABELPOS 71 29";
     $i = 0;
     $doublelink = array();
     $doublelinkbegin = array();
     $doublelinkdiff = array();
     $doublelinknumber = array();
     $query = "SELECT `" . getTableForItemType("PluginMonitoringWeathermaplink") . "`.*, \n            count(`" . getTableForItemType("PluginMonitoringWeathermaplink") . "`.`id`) as `cnt` \n            FROM `" . getTableForItemType("PluginMonitoringWeathermaplink") . "` \n         LEFT JOIN `" . getTableForItemType("PluginMonitoringWeathermapnode") . "`\n            ON `plugin_monitoring_weathermapnodes_id_1` = `" . getTableForItemType("PluginMonitoringWeathermapnode") . "`.`id`\n\n         WHERE `plugin_monitoring_weathermaps_id`='" . $weathermaps_id . "'\n         group by `plugin_monitoring_weathermapnodes_id_1`, `plugin_monitoring_weathermapnodes_id_2`\n         HAVING cnt >1";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $tlink = $data['plugin_monitoring_weathermapnodes_id_1'] . "-" . $data['plugin_monitoring_weathermapnodes_id_2'];
         $doublelink[$tlink] = $data['cnt'];
         $doublelinknumber[$tlink] = 0;
         $beg = 0;
         $diff = 0;
         switch ($data['cnt']) {
             case 2:
                 $beg = -22;
                 $diff = 44;
                 break;
             case 3:
                 $beg = -33;
                 $diff = 33;
                 break;
             case 4:
                 $beg = -39;
                 $diff = 26;
                 break;
             case 5:
                 $beg = -60;
                 $diff = 30;
                 break;
         }
         $doublelinkbegin[$tlink] = $beg;
         $doublelinkdiff[$tlink] = $diff;
     }
     $query = "SELECT * FROM `" . getTableForItemType("PluginMonitoringWeathermapnode") . "`\n         WHERE `plugin_monitoring_weathermaps_id`='" . $weathermaps_id . "'\n         ORDER BY `name`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $queryl = "SELECT * FROM `" . getTableForItemType("PluginMonitoringWeathermaplink") . "`\n            WHERE `plugin_monitoring_weathermapnodes_id_1`='" . $data['id'] . "'";
         $resultl = $DB->query($queryl);
         while ($datal = $DB->fetch_array($resultl)) {
             $bandwidth = $datal['bandwidth_in'] . " " . $datal['bandwidth_out'];
             if ($datal['bandwidth_in'] == $datal['bandwidth_out']) {
                 $bandwidth = $datal['bandwidth_in'];
             }
             $pmWeathermapnode->getFromDB($datal['plugin_monitoring_weathermapnodes_id_2']);
             $queryevent = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n               WHERE `plugin_monitoring_services_id`='" . $datal['plugin_monitoring_services_id'] . "'\n                  ORDER BY `id` DESC\n                  LIMIT 1";
             $resultevent = $DB->query($queryevent);
             $in = '';
             $out = '';
             while ($dataevent = $DB->fetch_array($resultevent)) {
                 $pmService->getFromDB($datal['plugin_monitoring_services_id']);
                 $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
                 $matches1 = array();
                 preg_match("/" . $pmComponent->fields['weathermap_regex_in'] . "/m", $dataevent['perf_data'], $matches1);
                 if (isset($matches1[1])) {
                     $in = $matches1[1];
                 }
                 $matches1 = array();
                 preg_match("/" . $pmComponent->fields['weathermap_regex_out'] . "/m", $dataevent['perf_data'], $matches1);
                 if (isset($matches1[1])) {
                     $out = $matches1[1];
                 }
             }
             $in = $this->checkBandwidth("in", $in, $bandwidth);
             $out = $this->checkBandwidth("out", $out, $bandwidth);
             $nodesuffix = '';
             $tlink = $datal['plugin_monitoring_weathermapnodes_id_1'] . "-" . $datal['plugin_monitoring_weathermapnodes_id_2'];
             if (isset($doublelink[$tlink])) {
                 $nodesuffix = ":" . ($doublelinkbegin[$tlink] + $doublelinknumber[$tlink] * $doublelinkdiff[$tlink]) . ":0";
                 $doublelinknumber[$tlink]++;
             }
             $conf .= "LINK " . preg_replace("/[^A-Za-z0-9_]/", "", $data['name']) . "_" . $data['id'] . "-" . preg_replace("/[^A-Za-z0-9_]/", "", $pmWeathermapnode->fields['name']) . "_" . $pmWeathermapnode->fields['id'] . $nodesuffix . "\n";
             $timezone = '0';
             if (isset($_SESSION['plugin_monitoring_timezone'])) {
                 $timezone = $_SESSION['plugin_monitoring_timezone'];
             }
             $timezone_file = str_replace("+", ".", $timezone);
             //            if (file_exists(GLPI_ROOT."/files/_plugins/monitoring/PluginMonitoringService-".$datal['plugin_monitoring_services_id']."-2h".$timezone_file.".gif")) {
             $conf .= "   INFOURL " . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $datal['plugin_monitoring_services_id'] . "\n" . "   OVERLIBGRAPH " . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/send.php?file=PluginMonitoringService-" . $datal['plugin_monitoring_services_id'] . "-2h" . $timezone_file . ".png\n";
             //            }
             $conf .= "   " . $bwlabelpos[$i] . "\n";
             $conf .= "   TARGET static:" . $in . ":" . $out . "\n";
             $conf .= "   NODES " . preg_replace("/[^A-Za-z0-9_]/", "", $data['name']) . "_" . $data['id'] . $nodesuffix . " " . preg_replace("/[^A-Za-z0-9_]/", "", $pmWeathermapnode->fields['name']) . "_" . $pmWeathermapnode->fields['id'] . $nodesuffix . "\n";
             $conf .= "   BANDWIDTH " . $bandwidth . "\n\n";
             $i++;
             if ($i == '2') {
                 $i = 0;
             }
         }
     }
     return $conf;
 }
Esempio n. 21
0
  (at your option) any later version.

  Plugin Monitoring for GLPI is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Monitoring. If not, see <http://www.gnu.org/licenses/>.

  ------------------------------------------------------------------------

  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2013 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2013

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
Session::checkCentralAccess();
Html::header(__('Monitoring', 'monitoring'), $_SERVER["PHP_SELF"], "plugins", "monitoring", "display");
PluginMonitoringServicegraph::loadLib();
$pmService = new PluginMonitoringService();
$pmService->manageServices($_GET['itemtype'], $_GET['items_id']);
Html::footer();
Esempio n. 22
0
function plugin_headings_monitoring_resources($item)
{
    $pmService = new PluginMonitoringService();
    $pmService->manageServices(get_class($item), $item->fields['id']);
    $pmHostconfig = new PluginMonitoringHostconfig();
    $pmHostconfig->showForm($item->getID(), get_class($item));
}
Esempio n. 23
0
 static function displayLine($data, $displayhost = 1)
 {
     global $DB, $CFG_GLPI;
     $pMonitoringService = new PluginMonitoringService();
     $networkPort = new NetworkPort();
     $pMonitoringComponent = new PluginMonitoringComponent();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $entity = new Entity();
     $pMonitoringService->getFromDB($data['id']);
     echo "<td width='32' class='center'>";
     $shortstate = self::getState($data['state'], $data['state_type'], $data['event'], $data['is_acknowledged']);
     $alt = __('Ok', 'monitoring');
     if ($shortstate == 'orange') {
         $alt = __('Warning (data)', 'monitoring');
     } else {
         if ($shortstate == 'yellow') {
             $alt = __('Warning (connection)', 'monitoring');
         } else {
             if ($shortstate == 'red') {
                 $alt = __('Critical', 'monitoring');
             } else {
                 if ($shortstate == 'redblue') {
                     $alt = __('Critical / Acknowledge', 'monitoring');
                 }
             }
         }
     }
     echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/box_" . $shortstate . "_32.png'\n         title='" . $alt . "' alt='" . $alt . "' />";
     echo "</td>";
     echo "<td>";
     $entity->getFromDB($data['entities_id']);
     echo $entity->fields['completename'];
     echo "</td>";
     $pMonitoringComponent->getFromDB($data['plugin_monitoring_components_id']);
     echo "<td class='center'>";
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if ($pMonitoringComponent->fields['graph_template'] != '') {
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['id'] . "'>";
         $pmServicegraph = new PluginMonitoringServicegraph();
         ob_start();
         $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "div", "600");
         $div = ob_get_contents();
         ob_end_clean();
         $chart = "<table width='600' class='tab_cadre'><tr><td>" . $div . "</td></tr></table>";
         Html::showToolTip($chart, array('img' => $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/stats_32.png"));
         $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "js");
     }
     echo "</a>";
     echo "</td>";
     if ($displayhost == '1') {
         $pmComponentscatalog_Host->getFromDB($data["plugin_monitoring_componentscatalogs_hosts_id"]);
         if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
             $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
             $item = new $itemtype();
             $item->getFromDB($pmComponentscatalog_Host->fields['items_id']);
             echo "<td>";
             echo $item->getTypeName() . " : " . $item->getLink();
             if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
                 $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
                 echo " [" . $networkPort->getLink() . "]";
             }
             echo "</td>";
         } else {
             echo "<td>" . __('Resources', 'monitoring') . "</td>";
         }
     }
     echo "<td>" . $pMonitoringComponent->getLink();
     if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
         $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
         echo " [" . $networkPort->getLink() . "]";
     }
     echo "</td>";
     //      $nameitem = '';
     //      if (isset($itemmat->fields['name'])) {
     //         $nameitem = "[".$itemmat->getLink(1)."]";
     //      }
     //if ($pMonitoringService->fields['plugin_monitoring_services_id'] == '0') {
     //echo "<td>".$itemmat->getLink(1)."</td>";
     //      } else {
     //         $pMonitoringServiceH->getFromDB($pMonitoringService->fields['plugin_monitoring_services_id']);
     //         $itemtypemat = $pMonitoringServiceH->fields['itemtype'];
     //         $itemmat = new $itemtypemat();
     //         $itemmat->getFromDB($pMonitoringServiceH->fields['items_id']);
     //         echo "<td>".$pMonitoringService->getLink(1).$nameitem." ".__('on', 'monitoring')." ".$itemmat->getLink(1)."</td>";
     //      }
     //      unset($itemmat);
     echo "<td class='center'>";
     if ($shortstate == 'red') {
         echo "<table>";
         echo "<tr>";
         echo "<td>";
         echo $data['state'];
         echo "</td>";
         echo "<td>";
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/acknowledge.form.php?id=" . $data['id'] . "'>" . "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/acknowledge_checked.png'" . " alt='" . __('Define an acknowledge', 'monitoring') . "'" . " title='" . __('Define an acknowledge', 'monitoring') . "'/>" . "</a>";
         echo "</td>";
         echo "</tr>";
         echo "</table>";
     } else {
         echo $data['state'];
     }
     echo "</td>";
     echo "<td>";
     echo Html::convDate($data['last_check']) . ' ' . substr($data['last_check'], 11, 8);
     echo "</td>";
     echo "<td>";
     echo $data['event'];
     echo "</td>";
     echo "<td align='center'>";
     $segments = CalendarSegment::getSegmentsBetween($pMonitoringComponent->fields['calendars_id'], date('w', date('U')), date('H:i:s'), date('w', date('U')), date('H:i:s'));
     if (count($segments) == '0') {
         echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_pause.png' />";
     } else {
         echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_run.png' />";
     }
     echo "</td>";
     if ($displayhost == '0') {
         $pmUnavaibility = new PluginMonitoringUnavaibility();
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentmonth', 1);
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'lastmonth', 1);
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentyear', 1);
         echo "<td class='center'>";
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/unavaibility.php?" . "field[0]=2&searchtype[0]=equals&contains[0]=" . $pMonitoringService->fields['id'] . "&sort=3&order=DESC&itemtype=PluginMonitoringUnavaibility'>\n            <img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/info.png'/></a>";
         echo "</td>";
     }
     echo "<td>";
     if ($shortstate == 'redblue') {
         echo "<i>" . _n('User', 'Users', 1) . " : </i>";
         $user = new User();
         $user->getFromDB($data['acknowledge_users_id']);
         echo $user->getName(1);
         echo "<br/>";
         echo "<i>" . __('Comments') . " : </i>" . $data['acknowledge_comment'];
     }
     echo "</td>";
     if ($displayhost == '0') {
         echo "<td>";
         if (PluginMonitoringProfile::haveRight("componentscatalog", 'w')) {
             $a_arg = importArrayFromDB($pMonitoringService->fields['arguments']);
             $cnt = '';
             if (count($a_arg) > 0) {
                 $cnt = " (" . count($a_arg) . ")";
             }
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/servicearg.form.php?id=" . $data['id'] . "'>" . __('Configure', 'monitoring') . $cnt . "</a>";
         }
         echo "</td>";
     }
 }
Esempio n. 24
0
 function generateWeathermap($weathermaps_id, $force = 0, $makehtml = 0)
 {
     if ($force == '0' and file_exists(GLPI_PLUGIN_DOC_DIR . "/monitoring/weathermap-" . $weathermaps_id . ".png")) {
         $time_generate = filectime(GLPI_PLUGIN_DOC_DIR . "/monitoring/weathermap-" . $weathermaps_id . ".png");
         if ($time_generate + 150 > date('U')) {
             return;
         }
     }
     require_once GLPI_ROOT . "/plugins/monitoring/lib/weathermap/WeatherMap.functions.php";
     require_once GLPI_ROOT . "/plugins/monitoring/lib/weathermap/HTML_ImageMap.class.php";
     require_once GLPI_ROOT . "/plugins/monitoring/lib/weathermap/Weathermap.class.php";
     require_once GLPI_ROOT . "/plugins/monitoring/lib/weathermap/WeatherMapNode.class.php";
     require_once GLPI_ROOT . "/plugins/monitoring/lib/weathermap/WeatherMapLink.class.php";
     $map = new WeatherMap();
     if ($map->ReadConfig($this->generateConfig($weathermaps_id))) {
         $imagefile = GLPI_PLUGIN_DOC_DIR . "/monitoring/weathermap-" . $weathermaps_id . ".png";
         $map->ReadData();
         if ($imagefile != '') {
             $map->DrawMap($imagefile);
             $map->imagefile = $imagefile;
         }
     } else {
         echo "Problem to generate weathermap";
     }
     if ($makehtml == '1') {
         $map->htmlstyle = '';
         $fd = fopen(GLPI_PLUGIN_DOC_DIR . "/monitoring/weathermap-" . $weathermaps_id . ".html", 'w');
         $html = $map->MakeHTML();
         $lines = explode("\n", $html);
         $objects_id = array();
         $services_id = array();
         foreach ($lines as $line) {
             $match = array();
             preg_match_all("/\\<area id=\"([\\w\\d:]*)\"  href=\"(?:.*)items_id=(\\d+)\" /", $line, $match);
             if (isset($match[1][0])) {
                 $objects_id[$match[1][0]] = $match[1][0];
                 $services_id[$match[1][0]] = $match[2][0];
             }
         }
         $pmService = new PluginMonitoringService();
         $pmComponent = new PluginMonitoringComponent();
         $pmServicegraph = new PluginMonitoringServicegraph();
         $i = 0;
         foreach ($objects_id as $o_id) {
             $pmService->getFromDB($services_id[$o_id]);
             $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
             ob_start();
             $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $services_id[$o_id], "0", '2h', "div", "400");
             $chart = '';
             $chart = ob_get_contents();
             ob_end_clean();
             $chart = str_replace('<div id="chart' . $services_id[$o_id] . '2h">', '<div id="chart' . $services_id[$o_id] . '2h' . $i . '">', $chart);
             $chart = str_replace('<div id="updategraph' . $services_id[$o_id] . '2h">', '<div id="updategraph' . $services_id[$o_id] . '2h' . $i . '">', $chart);
             $chart = "<table width='400' class='tab_cadre'><tr><td>" . $chart . "</td></tr></table>";
             $html .= "\n" . $this->showToolTip($chart, array('applyto' => $o_id, 'display' => false));
             ob_start();
             $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], "PluginMonitoringService", $services_id[$o_id], "0", '2h', "js");
             $chart = '';
             $chart = ob_get_contents();
             ob_end_clean();
             $chart = str_replace('"updategraph' . $services_id[$o_id] . '2h"', '"updategraph' . $services_id[$o_id] . '2h' . $i . '"', $chart);
             $chart = str_replace('&time=2h&', '&time=2h&suffix=' . $i . '&', $chart);
             $html .= "\n" . $chart;
             $i++;
         }
         fwrite($fd, $html);
         fwrite($fd, '<hr /><span id="byline">Network Map created with <a href="http://www.network-weathermap.com/?vs=
         0.97a">PHP Network Weathermap v0.97a</a></span></body></html>');
         fclose($fd);
     }
 }
   function generateData($rrdtool_template, $itemtype, $items_id, $timezone, $time, $enddate='', $todisplay=array()) {
      global $DB;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

               $a_labelsNew = array();
               $nb = 1;
               $val = 0;
               foreach ($a_labels as $value) {
                  if ($nb == 1) {
                     $a_labelsNew[] = $value;
                  }
                  $nb++;
                  if ($nb > $nb_val_period) {
                     $nb = 1;
                  }
               }
               $a_labels = $a_labelsNew;
            }
            break;
      }
      return array($mydatat, $a_labels, $dateformat);
   }
 static function isThisItemCheckRuleNetworkport($parm)
 {
     global $DB;
     $pmComponentscatalog_rule = new self();
     $pmService = new PluginMonitoringService();
     $pmSearch = new PluginMonitoringSearch();
     $a_networkports_id = array();
     if (get_class($parm) == 'PluginMonitoringNetworkport') {
         $a_networkports_id[$parm->fields['networkports_id']] = $parm->fields['items_id'];
     } else {
         if (get_class($parm) == 'NetworkEquipment') {
             $query = "SELECT * FROM `glpi_plugin_monitoring_networkports`\n            WHERE `items_id`='" . $parm->fields['id'] . "'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_array($result)) {
                 $a_networkports_id[$data['networkports_id']] = $parm->fields['id'];
             }
         }
     }
     foreach ($a_networkports_id as $networkports_id => $networkequipments_id) {
         $a_find = array();
         $query = "SELECT * FROM `" . $pmComponentscatalog_rule->getTable() . "`\n            WHERE `itemtype`='PluginMonitoringNetworkport'";
         $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'];
             }
             Search::manageGetValues($data['itemtype']);
             $resultr = $pmSearch->constructSQL("PluginMonitoringNetworkport", $_GET, $networkports_id);
             if ($DB->numrows($resultr) > 0) {
                 $a_find[$data['plugin_monitoring_componentscalalog_id']][$networkports_id] = 1;
             } else {
                 if (!isset($a_find[$data['plugin_monitoring_componentscalalog_id']][$networkports_id])) {
                     $a_find[$data['plugin_monitoring_componentscalalog_id']][$networkports_id] = 0;
                 }
             }
         }
         if (count($get_tmp) > 0) {
             $_GET = $get_tmp;
         }
         $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
         foreach ($a_find as $componentscalalog_id => $datan) {
             foreach ($datan as $networkports_id => $is_present) {
                 // Get all networports in this rule
                 if ($is_present == '0') {
                     // * Remove from dynamic if present
                     $query = "SELECT `glpi_plugin_monitoring_services`.`id`,\n                        `glpi_plugin_monitoring_componentscatalogs_hosts`.`id` as hid\n                        FROM `glpi_plugin_monitoring_services`\n                     LEFT JOIN `glpi_plugin_monitoring_componentscatalogs_hosts` ON\n                        `plugin_monitoring_componentscatalogs_hosts_id` = `glpi_plugin_monitoring_componentscatalogs_hosts`.`id`\n                     WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                        AND `itemtype`='NetworkEquipment'\n                        AND `items_id`='" . $networkequipments_id . "'\n                        AND `is_static`='0'\n                        AND `networkports_id`='" . $networkports_id . "'";
                     $result = $DB->query($query);
                     while ($data = $DB->fetch_array($result)) {
                         $pmComponentscatalog_Host->getFromDB($data['hid']);
                         $_SESSION['plugin_monitoring_hosts'] = $pmComponentscatalog_Host->fields;
                         $pmService->delete(array('id' => $data['id']));
                     }
                 } else {
                     //  add if not present
                     // * Add componentscatalogs_hosts if not exist
                     $componentscatalogs_hosts_id = 0;
                     $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n                     WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                        AND `itemtype`='NetworkEquipment'\n                        AND `items_id`='" . $networkequipments_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['itemtype'] = "NetworkEquipment";
                         $input['items_id'] = $networkequipments_id;
                         $componentscatalogs_hosts_id = $pmComponentscatalog_Host->add($input);
                     } else {
                         $a_componentscatalogs_hosts = $DB->fetch_assoc($result);
                         $componentscatalogs_hosts_id = $a_componentscatalogs_hosts['id'];
                     }
                     // * Add service if not exist
                     $pmComponentscatalog_Host->linkComponentsToItem($componentscalalog_id, $componentscatalogs_hosts_id, $networkports_id);
                 }
             }
         }
     }
 }
 function getSpecificData($perfdatas_id, $items_id, $which = 'last', $state = "AND `state` = 'OK'")
 {
     global $DB;
     // ** Get in table serviceevents
     $mydatat = array();
     $a_labels = array();
     $a_ref = array();
     $pmService = new PluginMonitoringService();
     $pmService->getFromDB($items_id);
     $_SESSION['plugin_monitoring_checkinterval'] = PluginMonitoringComponent::getTimeBetween2Checks($pmService->fields['plugin_monitoring_components_id']);
     $enddate = date('U');
     $counters = array();
     switch ($which) {
         case 'first':
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n               WHERE `plugin_monitoring_services_id`='" . $items_id . "'\n                  AND `perf_data` != ''\n                  " . $state . "\n               ORDER BY `date` ASC\n               LIMIT 1";
             break;
         case 'last':
             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n               WHERE `plugin_monitoring_services_id`='" . $items_id . "'\n                  AND `perf_data` != ''\n                  " . $state . "\n               ORDER BY `date` DESC\n               LIMIT 1";
             break;
         default:
             return $counters;
             break;
     }
     $resultevent = $DB->query($query);
     $dataevent = $DB->fetch_assoc($resultevent);
     $result = $DB->query($query);
     $ret = $this->getData($result, $perfdatas_id, $dataevent['date'], $dataevent['date']);
     /*
           if (is_array($ret)) {
              foreach ($ret[0] as $name=>$data) {
                 $counters[$name] = $data[0];
              }
           }
     */
     if (is_array($ret) && is_array($ret[0]) && is_array($ret[4])) {
         foreach ($ret[4] as $name => $data) {
             // Toolbox::logInFile("pm", "$name -> $data = ".$ret[0][$data][0]."\n");
             $counter = array();
             $counter['id'] = preg_replace("/[^A-Za-z0-9\\-_]/", "", $name);
             $counter['name'] = $data;
             $counter['value'] = $ret[0][$data][0];
             $counters[] = $counter;
         }
     }
     return $counters;
 }
 function type_other($type = 'average')
 {
     global $DB;
     $pmService = new PluginMonitoringService();
     $pmServiceevent = new PluginMonitoringServiceevent();
     $pmComponent = new PluginMonitoringComponent();
     $pmPerfdataDetail = new PluginMonitoringPerfdataDetail();
     $a_date = PluginMonitoringCustomitem_Common::getTimeRange($this->fields);
     $val = 0;
     $a_val = array();
     $nb_val = 0;
     $a_tocheck = array('warn' => 0, 'crit' => 0, 'limit' => 0);
     $a_types = array('warn', 'crit', 'limit');
     for ($i = 0; $i < count($a_types); $i++) {
         if (is_numeric($this->fields['aggregate_' . $a_types[$i]])) {
             $a_ret[$a_types[$i]] = $this->fields['aggregate_' . $a_types[$i]];
         } else {
             $a_ret[$a_types[$i]] = 0;
             $a_tocheck[$a_types[$i]] = 1;
         }
     }
     $items = importArrayFromDB($this->fields['aggregate_items']);
     foreach ($items as $itemtype => $data) {
         switch ($itemtype) {
             case 'PluginMonitoringService':
                 foreach ($data as $items_id => $data2) {
                     $pmService->getFromDB($items_id);
                     $_SESSION['plugin_monitoring_checkinterval'] = PluginMonitoringComponent::getTimeBetween2Checks($pmService->fields['plugin_monitoring_components_id']);
                     $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
                     $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                     WHERE `plugin_monitoring_services_id`='" . $items_id . "'\n                        AND `date` >= '" . $a_date['begin'] . "'\n                     ORDER BY `date`";
                     $result = $DB->query($query);
                     $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template'], $a_date['begin'], $a_date['end']);
                     foreach ($data2 as $a_perfdatadetails) {
                         $pmPerfdataDetail->getFromDB($a_perfdatadetails['perfdatadetails_id']);
                         $nb_val += count($ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                         $val += array_sum($ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                         $a_val = array_merge($a_val, $ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                     }
                     // for manage warn, crit and limit
                     foreach ($a_tocheck as $other_type => $num_type) {
                         if ($num_type == 1) {
                             $other_items = importArrayFromDB($this->fields['aggregate_' . $other_type]);
                             foreach ($other_items[$itemtype][$items_id] as $a_perfdatadetails) {
                                 $pmPerfdataDetail->getFromDB($a_perfdatadetails['perfdatadetails_id']);
                                 $a_ret[$other_type] += array_sum($ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                             }
                         }
                     }
                 }
                 break;
             case 'PluginMonitoringComponentscatalog':
                 $pmComponentscatalog = new PluginMonitoringComponentscatalog();
                 foreach ($data as $items_id => $data2) {
                     $ret = $pmComponentscatalog->getInfoOfCatalog(str_replace('id', '', $items_id));
                     $a_hosts = $ret[6];
                     foreach ($data2['PluginMonitoringComponent'] as $items_id_components => $data4) {
                         $query = "SELECT * FROM `glpi_plugin_monitoring_services`\n                        WHERE `plugin_monitoring_components_id`='" . str_replace('id', '', $items_id_components) . "'\n                           AND `plugin_monitoring_componentscatalogs_hosts_id` IN\n                              ('" . implode("','", $a_hosts) . "')\n                           AND `entities_id` IN (" . $_SESSION['glpiactiveentities_string'] . ")";
                         $result = $DB->query($query);
                         while ($dataq = $DB->fetch_array($result)) {
                             $pmService->getFromDB($dataq['id']);
                             $_SESSION['plugin_monitoring_checkinterval'] = PluginMonitoringComponent::getTimeBetween2Checks($pmService->fields['plugin_monitoring_components_id']);
                             $pmComponent->getFromDB($dataq['plugin_monitoring_components_id']);
                             $query = "SELECT * FROM `glpi_plugin_monitoring_serviceevents`\n                           WHERE `plugin_monitoring_services_id`='" . $dataq['id'] . "'\n                              AND `date` >= '" . $a_date['begin'] . "'\n                           ORDER BY `date`";
                             $result = $DB->query($query);
                             $ret = $pmServiceevent->getData($result, $pmComponent->fields['graph_template'], $a_date['begin'], $a_date['end']);
                             foreach ($data4 as $a_perfdatadetails) {
                                 $pmPerfdataDetail->getFromDB($a_perfdatadetails['perfdatadetails_id']);
                                 $nb_val += count($ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                                 $val += array_sum($ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                                 $a_val = array_merge($a_val, $ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                             }
                             // for manage warn, crit and limit
                             foreach ($a_tocheck as $other_type => $num_type) {
                                 if ($num_type == 1) {
                                     $other_items = importArrayFromDB($this->fields['aggregate_' . $other_type]);
                                     foreach ($other_items[$itemtype][$items_id]['PluginMonitoringComponent'][$items_id_components] as $a_perfdatadetails) {
                                         $pmPerfdataDetail->getFromDB($a_perfdatadetails['perfdatadetails_id']);
                                         $a_ret[$other_type] += array_sum($ret[0][$pmPerfdataDetail->fields['dsname' . $a_perfdatadetails['perfdatadetails_dsname']]]);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 break;
         }
     }
     if ($nb_val != 0) {
         if ($type == 'average') {
             $val = $val / $nb_val;
         } else {
             if ($type == 'median') {
                 sort($a_val);
                 $count = count($a_val);
                 //total numbers in array
                 $middleval = floor(($count - 1) / 2);
                 // find the middle value, or the lowest middle value
                 if ($count % 2) {
                     // odd number, middle is the median
                     $median = $a_val[$middleval];
                 } else {
                     // even number, calculate avg of 2 medians
                     $low = $arr[$middleval];
                     $high = $arr[$middleval + 1];
                     $median = ($low + $high) / 2;
                 }
                 $val = $median;
             }
         }
     }
     foreach ($a_tocheck as $other_type => $num_type) {
         if ($num_type == 1) {
             $a_ret[$other_type] = $a_ret[$other_type] / $nb_val;
         }
     }
     $a_ret['val'] = $val;
     return $a_ret;
 }
Esempio n. 29
0
 public function testPHPlogs()
 {
     global $CFG_GLPI, $PLUGIN_HOOKS;
     $_SESSION['glpi_use_mode'] = 2;
     $_SESSION["glpiID"] = 2;
     $_SESSION["glpiactiveentities_string"] = 0;
     $PLUGIN_HOOKS = plugin_init_monitoring();
     plugin::load("monitoring");
     $CFG_GLPI['root_doc'] = "http://127.0.0.1/fusion0.80/";
     loadLanguage("en_GB");
     $pmComponent = new PluginMonitoringComponent();
     $pmComponentscatalog = new PluginMonitoringComponentscatalog();
     $pmComponentscatalog_Component = new PluginMonitoringComponentscatalog_Component();
     $pmComponentscatalog_rule = new PluginMonitoringComponentscatalog_rule();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmService = new PluginMonitoringService();
     $computer = new Computer();
     // Add components
     $input = array();
     $input['name'] = 'Host alive';
     $input['plugin_monitoring_commands_id '] = '21';
     $input['plugin_monitoring_checks_id'] = '1';
     $input['calendars_id'] = '1';
     $components_id = $pmComponent->add($input);
     // Add components catalog
     $input = array();
     $input['name'] = 'linux servers';
     $catalogs_id = $pmComponentscatalog->add($input);
     $input = array();
     $input['plugin_monitoring_componentscalalog_id'] = $catalogs_id;
     $input['plugin_monitoring_components_id'] = $components_id;
     $pmComponentscatalog_Component->add($input);
     // Add Computer
     $input = array();
     $input['name'] = 'pc1';
     $input['entities_id'] = 0;
     $pc1 = $computer->add($input);
     // Check computer pc1 not added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '0', '[f1] Computer in component cataglog and may not be');
     $input = array();
     $input['plugin_monitoring_componentscalalog_id'] = $catalogs_id;
     $input['name'] = 'all have name';
     $input['itemtype'] = 'Computer';
     $input['condition'] = '{"field":["1"],"searchtype":["contains"],"contains":["pc"],"itemtype":"Computer","start":"0"}';
     $rules_id = $pmComponentscatalog_rule->add($input);
     // Check computer pc1 not added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '1', '[f2] Computer may be in component catalog');
     // Check service of this computer created
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '1', '[s2] One service may be created');
     // Add Computer
     $input = array();
     $input['name'] = 'pc2';
     $input['entities_id'] = 0;
     $pc2 = $computer->add($input);
     // Check computer pc1 not added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '2', '[f3] 2 computers may be in component catalog');
     // Check service of this computer created
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '2', '[s3] 2 services may be created');
     // Remove pc2
     $computer->delete(array('id' => $pc2), 1);
     // Check computer pc1 added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '1', '[f4] Computer may be unique in component catalog');
     // Check service of this computer created
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '1', '[s4] One service may be created');
     // Modify rule
     $input['id'] = $rules_id;
     $input['condition'] = '{"field":["1"],"searchtype":["contains"],"contains":["tc"],"itemtype":"Computer","start":"0"}';
     $pmComponentscatalog_rule->update($input);
     // Check no computer in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '0', '[f5] Computer may be deleted on rule update');
     // Check service
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '0', '[s5] No service may be created');
     // Modify rule
     $input['id'] = $rules_id;
     $input['condition'] = '{"field":["1"],"searchtype":["contains"],"contains":["pc"],"itemtype":"Computer","start":"0"}';
     $pmComponentscatalog_rule->update($input);
     // Check computer pc1 added in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '1', '[f6] Computer may be unique in component catalog');
     // Delete rule
     $pmComponentscatalog_rule->delete(array('id' => $rules_id), 1);
     // Check not have computer in ressources
     $a_hosts = $pmComponentscatalog_Host->find("`plugin_monitoring_componentscalalog_id`='" . $catalogs_id . "'");
     $this->assertEquals(count($a_hosts), '0', '[f7] must have no computer in component catalog');
     // Check service
     $a_services = $pmService->find();
     $this->assertEquals(count($a_services), '0', '[s7] No service may be created');
 }
Esempio n. 30
0
 static function displayLine($data, $displayhost = 1)
 {
     global $DB, $CFG_GLPI, $LANG;
     $pMonitoringService = new PluginMonitoringService();
     $networkPort = new NetworkPort();
     $pMonitoringComponent = new PluginMonitoringComponent();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $pmServicegraph = new PluginMonitoringServicegraph();
     $entity = new Entity();
     $pMonitoringService->getFromDB($data['id']);
     echo "<td width='32' class='center'>";
     $shortstate = self::getState($data['state'], $data['state_type']);
     echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/box_" . $shortstate . "_32.png'/>";
     echo "</td>";
     echo "<td>";
     $entity->getFromDB($data['entities_id']);
     echo $entity->fields['completename'];
     echo "</td>";
     $pMonitoringComponent->getFromDB($data['plugin_monitoring_components_id']);
     echo "<td class='center'>";
     $img = '';
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     $timezone_file = str_replace("+", ".", $timezone);
     $img = "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/send.php?file=PluginMonitoringService-" . $data['id'] . "-2h" . $timezone_file . ".png'/>";
     echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['id'] . "'>";
     if (file_exists(GLPI_ROOT . "/files/_plugins/monitoring/PluginMonitoringService-" . $data['id'] . "-2h" . $timezone_file . ".png") or $pMonitoringComponent->fields['graph_template'] != '') {
         $img = "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/send.php?file=PluginMonitoringService-" . $data['id'] . "-2h" . $timezone_file . ".png'/>";
         showToolTip($img, array('img' => $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/stats_32.png"));
     } else {
     }
     echo "</a>";
     echo "</td>";
     if ($displayhost == '1') {
         $pmComponentscatalog_Host->getFromDB($data["plugin_monitoring_componentscatalogs_hosts_id"]);
         if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
             $itemtype = $pmComponentscatalog_Host->fields['itemtype'];
             $item = new $itemtype();
             $item->getFromDB($pmComponentscatalog_Host->fields['items_id']);
             echo "<td>";
             echo $item->getTypeName() . " : " . $item->getLink();
             if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
                 $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
                 echo " [" . $networkPort->getLink() . "]";
             }
             echo "</td>";
         } else {
             echo "<td>" . $LANG['plugin_monitoring']['service'][0] . "</td>";
         }
     }
     echo "<td>" . $pMonitoringComponent->getLink();
     if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) {
         $networkPort->getFromDB($pMonitoringService->fields['networkports_id']);
         echo " [" . $networkPort->getLink() . "]";
     }
     echo "</td>";
     //      $nameitem = '';
     //      if (isset($itemmat->fields['name'])) {
     //         $nameitem = "[".$itemmat->getLink(1)."]";
     //      }
     //if ($pMonitoringService->fields['plugin_monitoring_services_id'] == '0') {
     //echo "<td>".$itemmat->getLink(1)."</td>";
     //      } else {
     //         $pMonitoringServiceH->getFromDB($pMonitoringService->fields['plugin_monitoring_services_id']);
     //         $itemtypemat = $pMonitoringServiceH->fields['itemtype'];
     //         $itemmat = new $itemtypemat();
     //         $itemmat->getFromDB($pMonitoringServiceH->fields['items_id']);
     //         echo "<td>".$pMonitoringService->getLink(1).$nameitem." ".$LANG['networking'][25]." ".$itemmat->getLink(1)."</td>";
     //      }
     //      unset($itemmat);
     echo "<td class='center'>";
     echo $data['state'];
     echo "</td>";
     echo "<td>";
     echo convDate($data['last_check']) . ' ' . substr($data['last_check'], 11, 8);
     echo "</td>";
     echo "<td>";
     echo $data['event'];
     echo "</td>";
     echo "<td align='center'>";
     $segments = CalendarSegment::getSegmentsBetween($pMonitoringComponent->fields['calendars_id'], date('w', date('U')), date('H:i:s'), date('w', date('U')), date('H:i:s'));
     if (count($segments) == '0') {
         echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_pause.png' />";
     } else {
         echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_run.png' />";
     }
     echo "</td>";
     if ($displayhost == '0') {
         $pmUnavaibility = new PluginMonitoringUnavaibility();
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentmonth', 1);
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'lastmonth', 1);
         $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentyear', 1);
         echo "<td>";
         $a_arg = importArrayFromDB($pMonitoringService->fields['arguments']);
         $cnt = '';
         if (count($a_arg) > 0) {
             $cnt = " (" . count($a_arg) . ")";
         }
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/servicearg.form.php?id=" . $data['id'] . "'>" . $LANG['plugin_monitoring']['service'][25] . $cnt . "</a>";
         echo "</td>";
     }
 }