static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {

      switch ($item->getType()) {
         case 'Central' :
            $pmDisplay = new PluginMonitoringDisplay();
            // $pmDisplay->showHostsCounters("Hosts", 1, 1);
            $pmDisplay->showHostsBoard();
            return true;

      }
      if ($item->getID() > 0) {
         if ($tabnum == 0) {
            PluginMonitoringToolbox::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 displayGraphs($itemtype, $items_id)
 {
     global $CFG_GLPI;
     $pmComponent = new PluginMonitoringComponent();
     $pmConfig = new PluginMonitoringConfig();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $networkPort = new NetworkPort();
     $item = new $itemtype();
     $item->getFromDB($items_id);
     $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
     if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
         PluginMonitoringToolbox::loadPreferences($pmComponent->fields['id']);
     }
     $css_width = '950';
     if (isset($_GET['mobile'])) {
         $css_width = '300';
     }
     echo "<table class='tab_cadre' width='" . $css_width . "'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     $title = Dropdown::getDropdownName(getTableForItemType('PluginMonitoringComponent'), $item->fields['plugin_monitoring_components_id']);
     if (!is_null($item->fields['networkports_id']) && $item->fields['networkports_id'] > 0) {
         $networkPort->getFromDB($item->fields['networkports_id']);
         $title .= " [" . $networkPort->getLink() . "]";
     }
     $title .= ' ' . __('on', 'monitoring') . ' ';
     $pmComponentscatalog_Host->getFromDB($item->fields["plugin_monitoring_componentscatalogs_hosts_id"]);
     if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
         $itemtype2 = $pmComponentscatalog_Host->fields['itemtype'];
         $item2 = new $itemtype2();
         $item2->getFromDB($pmComponentscatalog_Host->fields['items_id']);
         $title .= str_replace("'", "\"", $item2->getLink() . " (" . $item2->getTypeName() . ")");
     }
     echo $title;
     echo "</th>";
     echo "<th width='200'>";
     if (!isset($_GET['mobile'])) {
         echo "<form method='post'>";
         $a_timezones = PluginMonitoringConfig::getTimezones();
         if (!isset($_SESSION['plugin_monitoring_timezone'])) {
             $_SESSION['plugin_monitoring_timezone'] = '0';
         }
         $a_timezones_allowed = array();
         $pmConfig->getFromDB(1);
         $a_temp = importArrayFromDB($pmConfig->fields['timezones']);
         foreach ($a_temp as $key) {
             $a_timezones_allowed[$key] = $a_timezones[$key];
         }
         if (count($a_timezones_allowed) == '0') {
             $a_timezones_allowed['0'] = $a_timezones['0'];
         }
         Dropdown::showFromArray('plugin_monitoring_timezone', $a_timezones_allowed, array('value' => $_SESSION['plugin_monitoring_timezone']));
         echo "&nbsp;<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>";
         Html::closeForm();
     }
     echo "</th>";
     echo "</tr>";
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if (!isset($_GET['mobile'])) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo "<div id='legendlink'><a onClick='\$(\"#options\").toggle();'>[ Options ]</a></div>";
         echo "</th>";
         echo "</tr>";
         // * Display perfname
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         echo "<div id='options' style='display:none'>";
         PluginMonitoringToolbox::preferences($pmComponent->fields['id'], 0);
         echo "</div>";
         echo "</td>";
         echo "</tr>";
         // * Display date slider
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo __('Select date', 'monitoring') . " - " . __('Select time', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         $start = time();
         $oldvalue = current(getAllDatasFromTable('glpi_plugin_monitoring_serviceevents', "`plugin_monitoring_services_id`='" . $items_id . "'", false, 'date ASC LIMIT 1'));
         $date = new DateTime($oldvalue['date']);
         if ($date->getTimestamp() < $start) {
             $start = $date->getTimestamp();
         }
         $nbdays = round((date('U') - $start) / 86400);
         echo "<script type=\"text/javascript\">\n            \$(function() {\n                \$( \"#custom_date\" ).datepicker({ minDate: -" . $nbdays . ", maxDate: \"+0D\", dateFormat:'mm/dd/yy' });\n                \$( \"#custom_time\" ).timepicker();\n\n            });\n         </script>";
         echo '<center><input type="text" id="custom_date" value="' . date('m/d/Y') . '"> ' . ' <input type="text" id="custom_time" value="' . date('H:i') . '"></center>';
         echo "</th>";
         echo "</tr>";
     }
     $a_list = array();
     $a_list["2h"] = __("Last 2 hours", "monitoring");
     $a_list["12h"] = __("Last 12 hours", "monitoring");
     $a_list["1d"] = __("Last 24 hours", "monitoring");
     $a_list["1w"] = __("Last 7 days (average)", "monitoring");
     //      $a_list["1m"]     = __("Last month (average)", "monitoring");
     //      $a_list["0y6m"]   = __("Last 6 months (average)", "monitoring");
     //      $a_list["1y"]     = __("Last year (average)", "monitoring");
     foreach ($a_list as $time => $name) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo $name;
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center' colspan='2' style='position: relative'>";
         $pmServicegraph = new PluginMonitoringServicegraph();
         $part = '';
         $width = '950';
         if (isset($_GET['mobile'])) {
             $width = '294';
         }
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $part, $width);
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
   function slideSlider($id) {
      global $CFG_GLPI, $DB;

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

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

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

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

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

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

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

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

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

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

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

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

            echo "<script type='text/javascript'>
            var mgr = new Ext.UpdateManager('pluginmap');
            mgr.startAutoRefresh(50, \"".$CFG_GLPI["root_doc"].
                    "/plugins/monitoring/ajax/widgetPluginmap.php\","
                    . " \"extra_infos=".
                    $data['extra_infos']."&sess_id=".$sess_id.
                    "&glpiID=".$_SESSION['glpiID'].
                    "&plugin_monitoring_securekey=".$_SESSION['plugin_monitoring_securekey'].
                    "\", \"\", true);
            </script>";
         }
      }
      echo "</td>";
      echo "</tr>";
      echo "</table>";
   }
 function showWidget($id)
 {
     PluginMonitoringToolbox::loadLib();
     return "<div id=\"updatecustomitem_gauge" . $id . "\"></div>";
 }
   static function methodShinkenGetConffiles($params, $protocol) {

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting methodShinkenGetConffiles ...\n"
      );

      if (isset ($params['help'])) {
         return array('file'  => 'config filename to get : commands.cfg, hosts.cfg, ... use all to get all files.',
                      'help'  => 'bool,optional');
      }

      if (!isset($params['tag'])) {
         $params['tag'] = '';
      }

      ini_set("max_execution_time", "0");
      ini_set("memory_limit", "-1");

      $pmShinken = new PluginMonitoringShinken();
      switch ($params['file']) {

         case 'commands.cfg':
            $array = $pmShinken->generateCommandsCfg(1);
            return array($array[0]=>$array[1]);
            break;

         case 'hosts.cfg':
            $array = $pmShinken->generateHostsCfg(1, $params['tag']);
            return array($array[0]=>$array[1]);
            break;

         case 'hostgroups.cfg':
            $array = $pmShinken->generateHostgroupsCfg(1, $params['tag']);
            return array($array[0]=>$array[1]);
            break;

         case 'contacts.cfg':
            $array = $pmShinken->generateContactsCfg(1, $params['tag']);
            return array($array[0]=>$array[1]);
            break;

         case 'timeperiods.cfg':
            $array = $pmShinken->generateTimeperiodsCfg(1, $params['tag']);
            return array($array[0]=>$array[1]);
            break;

         case 'services.cfg':
            $array = $pmShinken->generateServicesCfg(1, $params['tag']);
            return array($array[0]=>$array[1]);
            break;

         case 'templates.cfg':
            $array = $pmShinken->generateTemplatesCfg(1, $params['tag']);
            return array($array[0]=>$array[1]);
            break;

         case 'all':
            $output = array();
            $array = $pmShinken->generateCommandsCfg(1);
            $output[$array[0]] = $array[1];
            $array = $pmShinken->generateHostsCfg(1, $params['tag']);
            $output[$array[0]] = $array[1];
            $array = $pmShinken->generateHostgroupsCfg(1, $params['tag']);
            $output[$array[0]] = $array[1];
            $array = $pmShinken->generateContactsCfg(1, $params['tag']);
            $output[$array[0]] = $array[1];
            $array = $pmShinken->generateTimeperiodsCfg(1, $params['tag']);
            $output[$array[0]] = $array[1];
            $array = $pmShinken->generateTemplatesCfg(1, $params['tag']);
            $output[$array[0]] = $array[1];
            $array = $pmShinken->generateServicesCfg(1, $params['tag']);
            $output[$array[0]] = $array[1];
            return $output;
            break;

      }
   }
   function displayGraph($rrdtool_template, $itemtype, $items_id, $timezone, $time='1d', $part='', $width='900') {
      global $CFG_GLPI;

      $pmComponent = new PluginMonitoringComponent();
//      if (isset($_GET['itemtype'])) {
//         $itemtype = $_GET['itemtype'];
//         $items_id = $_GET['items_id'];
//      }
      $item = new $itemtype();
      if ($item->getFromDB($items_id)) {
         $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
         $ident = $items_id.$time;

         if ($part == ''
                 OR $part == 'div') {
            echo '<div id="chart'.$ident.'">'.
                '<svg style="width: '.$width.'px;display: block;"></svg>'.
              '</div>';

            echo "<div id=\"updategraph".$items_id.$time."\"></div>";
         }
         if ($part == ''
                 OR $part == 'js') {
            if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
               PluginMonitoringToolbox::loadPreferences($pmComponent->fields['id']);
            }
            if (! isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
               $format = '%H:%M';
            } else {
               if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']][''])) {
                  unset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']]['']);
               }
               $pmServicegraph = new PluginMonitoringServicegraph();
               $a_ret = $pmServicegraph->generateData($rrdtool_template,
                                            $itemtype,
                                            $items_id,
                                            $timezone,
                                            $time,
                                            '',
                                            $_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']]);
               $format = $a_ret[2];
            }
            echo "<script>";
            $formaty = ".0f";
            echo '

            var data'.$ident.' = [];
            var chart'.$ident.';
            redraw'.$ident.' = function () {
               nv.addGraph(function() {
                  chart'.$ident.' = nv.models.lineChart();

                  chart'.$ident.'.useInteractiveGuideline(true);

                  chart'.$ident.'.xAxis
                     .tickFormat(function(d) { return d3.time.format("'.$format.'")(new Date(d)); });

                  chart'.$ident.'.yAxis
                     .axisLabel("test")
                     .tickFormat(d3.format(\''.$formaty.'\'));

                  chart'.$ident.'.forceY([0]);

                  d3.select("#chart'.$ident.' svg")
                    .attr("height", 300)
                    .datum(data'.$ident.')
                    .transition().duration(50)
                    .call(chart'.$ident.');



                 return chart'.$ident.';
               });
            };';

            echo "
            (function worker".$items_id.$time."() {
              startDate = new Date($('#custom_date').val());
              startTime = Date.parse('04/03/1980 ' + ($('#custom_time').val()) + ':00');
              $.getJSON('".$CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/updateChart.php"
                    ."?rrdtool_template=".$rrdtool_template."&itemtype=".$itemtype.
                          "&items_id=".$items_id.
                          "&timezone=".$timezone.
                          "&time=".$time."&customdate=' + (startDate.getTime()/1000.0) + '".
                          "&customtime=' + (startTime/1000.0) + '".
                          "&components_id=".$pmComponent->fields['id']."', function(data) {
                data".$ident." = data;

                redraw".$ident."();
                setTimeout(worker".$items_id.$time.", 30000);
              });
            })();";
            echo "
            </script>";
         }

                 }
      return;
   }
   function view($id, $config=0) {
      global $DB, $CFG_GLPI;

      $pmDisplayview       = new PluginMonitoringDisplayview();
      $pmDisplayview_rule  = new PluginMonitoringDisplayview_rule();

      $pmDisplayview->getFromDB($id);

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

      PluginMonitoringToolbox::loadLib();

      $style = '';
      if ($config == '1') {
         $this->addItem($id);
         $pmDisplayview_rule->showReplayRulesForm($id);
         echo "<div id='updatecoordonates'></div>";
         if ($pmDisplayview->fields['width'] > 950) {
            $style = ";position:relative;left:-".(($pmDisplayview->fields['width'] - 950) / 2)."px";
         }
      } else {
         if (!is_null($pmDisplayview->fields['counter'])) {
            $pmDisplay = new PluginMonitoringDisplay();
            $pmDisplay->showCounters($pmDisplayview->fields['counter']);
         }
      }

      echo "<table class='tab_cadre_fixe' id='test' style='width:".$pmDisplayview->fields['width']."px".$style."'>";

      echo "<tr class='tab_bg_1'>";
      echo "<th>";

      echo $pmDisplayview->fields['name'];
      echo "</th>";
      echo "</tr>";

      echo "<tr class='tab_bg_1' id='date_text'>";
      echo "<th>";
      echo __('Select date', 'monitoring')." - ".__('Select time', 'monitoring');
      echo "</th>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td>";

      $query = "SELECT * FROM `glpi_plugin_monitoring_displayviews_items`
         WHERE `plugin_monitoring_displayviews_id`='".$id."'
            AND `itemtype`='PluginMonitoringService'";
      $result = $DB->query($query);
      $a_items = array();
      $end = time();
      $start = time();

      $pmComponent = new PluginMonitoringComponent();
      while ($data=$DB->fetch_array($result)) {
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         $item->getFromDB($data['items_id']);
         if (isset($item->fields['plugin_monitoring_components_id'])) {
            $oldvalue = current(getAllDatasFromTable(
                    'glpi_plugin_monitoring_serviceevents',
                    "`plugin_monitoring_services_id`='".$data['items_id']."'",
                    false,
                    'date ASC LIMIT 1'));
            $date = new DateTime($oldvalue['date']);
            if ($date->getTimestamp() < $start) {
               $start = $date->getTimestamp();
            }
            $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);

            $a_items["item".$data['id']] = array(
                'rrdtool_template'  => $pmComponent->fields['graph_template'],
                'itemtype'          => $data['itemtype'],
                'items_id'          => $data['items_id'],
                'timezone'          => 0,
                'time'              => $data['extra_infos'],
                'pmComponents_id'   => $pmComponent->fields['id']
            );
         }
      }
      $nbdays = round((date('U') - $start) / 86400);

      echo "<script type=\"text/javascript\">
      $(function() {
          $( \"#custom_date\" ).datepicker({ minDate: -".$nbdays.", maxDate: \"+0D\", dateFormat:'mm/dd/yy' });
          $( \"#custom_time\" ).timepicker();

      });
      </script>";

      echo '<center><input type="text" id="custom_date" value="'.date('m/d/Y').'"> '
              . ' <input type="text" id="custom_time" value="'.date('H:i').'"></center>';
      echo "</td>";
      echo "</tr>";

     echo "<tr class='tab_bg_1' id='time_text' style='display: none;'>";
      echo "<th>";
      echo __('Select time', 'monitoring');
      echo "</th>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<th>";
      echo __('View', 'monitoring');
      echo "</th>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td>";
      echo "<input type='hidden' name='updateviewid' id='updateviewid' value='".$id."' />";
      if ($config == 0) {
         echo "<div id='filariane'>&nbsp;</div>";
         echo "<input type='hidden' name='updatefil' id='updatefil' value='".$id."!' />";

/*
         echo "<script type=\"text/javascript\">
            function reloadfil() {
               Ext.get('filariane').load({
                   url: '".$CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/updateFilariane.php',
                   scripts: true,
                      params:'updatefil=' + Ext.get('updatefil').getValue() + '&id=".$id.
                 "&currentview=' + Ext.get('updateviewid').getValue()
               });
            }
            reloadfil();
         </script>";
 */
      }
      echo "</td>";
      echo "</tr>";


      echo "<tr class='tab_bg_1'>";
      echo "<td height='1200' id='panel'>";

      $queryitems = "SELECT * FROM `glpi_plugin_monitoring_displayviews_items`
         WHERE `plugin_monitoring_displayviews_id`='".$id."'";
      $resultitems = $DB->query($queryitems);
      $a_items = array();
      while ($dataitems=$DB->fetch_array($resultitems)) {
//         if ($this->displayItem($dataitems, $config)) {
            $a_items[] = $dataitems;
//         }
//         }
      }

echo "
<script type=\"text/javascript\">
$(function() {
";


foreach ($a_items as $item) {
   if ($config == '1') {
      $event = ", stop: function() {
           pos = $('#draggable".$item['id']."').position();
           $.get('".$CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/displayview_itemcoordinates.php"
                          ."?id=".$item['id']
                          ."&x=' + pos.left + '&y=' + pos.top);
         }";
   } else {
      $event = '';
   }
   $size = $this->getSizeOfWidget($item['itemtype']);
   echo "$( \"#draggable".$item['id']."\" ).draggable({ cursor: 'move', cursorAt: { "
           . "top: ".($size['height']/2).", left: ".($size['width']/2).", "
           . " }, grid: [ 10, 10 ]".$event." } );";
}
echo "
});
</script>";

      echo "<div id='viewform' style='width: ".$pmDisplayview->fields['width']."px;height:1200px;position: relative;'>";

foreach ($a_items as $item) {
   $size = $this->getSizeOfWidget($item['itemtype']);
   echo '<div id="draggable'.$item['id'].'" ';
   if ($item['itemtype'] != 'PluginMonitoringServicescatalog'
           && $item['itemtype'] != 'PluginMonitoringComponentscatalog') {
      echo 'class="ui-widget-content" ';
   }
   echo  'style="width: '.$size['width'].'px; height: '.$size['height'].'px; '
           . 'position: absolute; left: '.$item['x'].'px; top: '.$item['y'].'px;">';

   if ($item['itemtype'] == 'PluginMonitoringService') {
      $pmComponent = new PluginMonitoringComponent();
      $pmService = new PluginMonitoringService();

      $pmService->getFromDB($item['items_id']);
      $pmComponent->getFromDB($pmService->fields['plugin_monitoring_components_id']);
      $pmServicegraph = new PluginMonitoringServicegraph();
      $pmServicegraph->displayGraph($pmComponent->fields['graph_template'],
                                    "PluginMonitoringService",
                                    $item['items_id'],
                                    "0",
                                    $item['extra_infos'],
                                    "",
                                    ($size['width'] - 15));
   } else if ($item['itemtype'] == 'PluginMonitoringWeathermap') {

   } else {
      echo "<div id=\"update".$item['itemtype'].$item['items_id']."\"></div>";

            echo "<script type=\"text/javascript\">";
            echo "
               (function worker() {
                 $.get('".$CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/updateWidgetComponentscatalog.php"
                       ."?id=".$item['items_id']."&is_minemap=".$item['is_minemap'].
                             "', function(data) {
                   $('#update".$item['itemtype'].$item['items_id']."').html(data);
                   setTimeout(worker, 30000);
                 });
               })();";
            echo "</script>";

   }

   echo '</div>';
}

//      echo "<script type='text/javascript'>
//
//        //Simple 'border layout' panel to house both grids
//        var displayPanel = new Ext.Panel({
//          id       : 'viewpanel',
//          width    : ".$pmDisplayview->fields['width'].",
//          height   : 1200,
//          layout: 'absolute',
//          renderTo : 'panel',
//          items    : []
//        });
//
//      </script>";




      echo "</div>";
//      echo "<script type=\"text/javascript\">
//         function reloadview() {
//            Ext.get('viewform').load({
//                url: '".$CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/loadView.php',
//                scripts: true,
//                   params:'id=' + Ext.get('updateviewid').getValue() + '&config=".$config."'
//            });
//         }
//         reloadview();
//      </script>";

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

   }
    function displayGraph($rrdtool_template, $itemtype, $items_id, $timezone, $time = '1d', $part = '', $width = '900')
    {
        global $CFG_GLPI;
        $pmComponent = new PluginMonitoringComponent();
        //      if (isset($_GET['itemtype'])) {
        //         $itemtype = $_GET['itemtype'];
        //         $items_id = $_GET['items_id'];
        //      }
        $item = new $itemtype();
        if ($item->getFromDB($items_id)) {
            $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
            $ident = $items_id . $time;
            if ($part == '' or $part == 'div') {
                echo '<div id="chart' . $ident . '">' . '<svg style="width: ' . $width . 'px;display: block;height: 300px;"></svg>' . '</div>';
                echo "<div id=\"updategraph" . $items_id . $time . "\"></div>";
            }
            if ($part == '' or $part == 'js') {
                if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
                    PluginMonitoringToolbox::loadPreferences($pmComponent->fields['id']);
                }
                if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
                    $format = '%H:%M';
                } else {
                    if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']][''])) {
                        unset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']]['']);
                    }
                    $pmServicegraph = new PluginMonitoringServicegraph();
                    $a_ret = $pmServicegraph->generateData($rrdtool_template, $itemtype, $items_id, $timezone, $time, '', $_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']]);
                    $format = $a_ret[2];
                }
                echo "<script>";
                echo '

            var formaty = ".0f";
            var data' . $ident . ' = [];
            var chart' . $ident . ';
            redraw' . $ident . ' = function () {
               nv.addGraph(function() {
                  if (typeof data' . $ident . '[0] != "undefined") {
                     formaty = data' . $ident . '[0]["formaty"];
                  }
                  chart' . $ident . ' = nv.models.lineChart();

                  chart' . $ident . '.useInteractiveGuideline(true);

                  chart' . $ident . '.xAxis
                     .tickFormat(function(d) { return d3.time.format("' . $format . '")(new Date(d)); });

                  chart' . $ident . '.yAxis
                     .axisLabel("test")
                     .tickFormat(d3.format(formaty));

                  chart' . $ident . '.forceY([0]);

                  d3.select("#chart' . $ident . ' svg")
                    .attr("height", 300)
                    .datum(data' . $ident . ')
                    .transition().duration(50)
                    .call(chart' . $ident . ');

                 return chart' . $ident . ';
               });
            };';
                echo "\n            (function worker" . $items_id . $time . "() {\n              startDate = new Date(\$('#custom_date').val());\n              startTime = Date.parse('04/03/1980 ' + (\$('#custom_time').val()) + ':00');\n              \$.getJSON('" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/updateChart.php" . "?rrdtool_template=" . $rrdtool_template . "&itemtype=" . $itemtype . "&items_id=" . $items_id . "&timezone=" . $timezone . "&time=" . $time . "&customdate=' + (startDate.getTime()/1000.0) + '" . "&customtime=' + (startTime/1000.0) + '" . "&components_id=" . $pmComponent->fields['id'] . "', function(data) {\n                data" . $ident . " = data;\n\n                var newDate = \$('#custom_date').val() + ' ' + \$('#custom_time').val();\n                var timestamp = new Date(newDate).getTime();\n                if (timestamp > (new Date().getTime() - 3600000)) {\n                    var datenow = new Date();\n                    \$('#custom_time').val(datenow.getHours() + ':' + datenow.getMinutes());\n                    \$('#custom_date').val((datenow.getMonth() + 1) + '/' + datenow.getDate() + '/' + datenow.getFullYear());\n                }\n\n                redraw" . $ident . "();\n                ";
                $refresh = 30;
                // 30 seconds
                if ($time == '12h') {
                    $refresh = 240;
                    // 4 minutes
                } else {
                    if ($time == '1d') {
                        $refresh = 600;
                        // 10 minutes
                    } else {
                        if ($time == '1w') {
                            $refresh = 1800;
                            // 30 minutes
                        }
                    }
                }
                echo "\n                setTimeout(worker" . $items_id . $time . ", " . $refresh . "000);\n              });\n            })();";
                echo "\n            </script>";
            }
        }
        return;
    }
   function showSyntheseReport($componentscatalogs_id) {
      global $CFG_GLPI;

      if (!isset($_SESSION['glpi_plugin_monitoring']['synthese'])) {
         $_SESSION['glpi_plugin_monitoring']['synthese'] = array();
      }
      if (!isset($_SESSION['glpi_plugin_monitoring']['synthese'][$componentscatalogs_id])) {
         $_SESSION['glpi_plugin_monitoring']['synthese'][$componentscatalogs_id] = array();
      }
      $sess = $_SESSION['glpi_plugin_monitoring']['synthese'][$componentscatalogs_id];
      $pmComponentscatalog_Component = new PluginMonitoringComponentscatalog_Component();
      $pmComponent = new PluginMonitoringComponent();
      $a_options = array();

      $this->getFromDB($componentscatalogs_id);

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

      echo "<table class='tab_cadre_fixe'>";
      echo '<tr class="tab_bg_1">';
      echo '<th colspan="5">';
      echo __('Report');
      echo "<input type='hidden' name='componentscatalogs_id' value='".$componentscatalogs_id."' />";
      echo "<input type='hidden' name='reporttype' value='synthese' />";
      $a_options['componentscatalogs_id'] = $componentscatalogs_id;
      echo '</th>';
      echo '</tr>';

      echo '<tr class="tab_bg_1">';
      echo '<td>';
      echo '</td>';
      echo '<td colspan="2">';
      $default_value = 12;
      if (isset($sess['synthesenumber'])) {
         $default_value = $sess['synthesenumber'];
      }
      Dropdown::showNumber("synthesenumber", array(
                'value' => $default_value,
                'min'   => 2,
                'max'   => 30)
      );
      $a_options['synthesenumber'] = $default_value;
      echo "&nbsp;";
      $a_time = array('week' => __('Week'),
                      'month' => __('Month'),
                      'year' => __('Year'));
      $default_value = 'week';
      if (isset($sess['synthesenumber'])) {
         $default_value = $sess['synthesenumber'];
      }
      Dropdown::showFromArray("syntheseperiod", $a_time, array('value' => $default_value));
      $a_options['syntheseperiod'] = $default_value;
      echo '</td>';
      echo "<td>".__('End date')." :</td>";
      echo "<td>";
      $default_value = date('Y-m-d');
      if (isset($sess['synthesedate_end'])) {
         $default_value = $sess['synthesedate_end'];
      }
      Html::showDateFormItem("synthesedate_end", $default_value);
      $a_options['synthesedate_end'] = $default_value;
      echo "</td>";
      echo '</tr>';

      echo "</table>";

      echo "<table class='tab_cadre_fixe'>";
      $a_composants = $pmComponentscatalog_Component->find("`plugin_monitoring_componentscalalog_id`='".$componentscatalogs_id."'");
      foreach ($a_composants as $comp_data) {
         $pmComponent->getFromDB($comp_data['plugin_monitoring_components_id']);

         echo "<tr class='tab_bg_1'>";
         echo "<td width='10'>";
         //echo "<input type='checkbox' name='components_id[]' value='".$pmComponent->getID()."' checked />";
         echo "<input type='hidden' name='components_id[]' value='".$pmComponent->getID()."' />";
         $a_options['components_id'][] = $pmComponent->getID();
         echo "</td>";
         echo "<td>";
         echo $pmComponent->getLink();
         echo "</td>";
         echo "</tr>";

         echo "<tr class='tab_bg_1'>";
         echo "<td width='10'>";
         echo "</td>";
         echo "<td>";

         PluginMonitoringToolbox::loadPreferences($pmComponent->getID());

         $a_perfnames = PluginMonitoringServicegraph::getperfdataNames($pmComponent->fields['graph_template']);
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_3'>";
         echo "<td rowspan='".count($a_perfnames)."' width='90'>";
         echo __('Use for report', 'monitoring')."&nbsp;:";

         echo "</td>";
         $i = 0;
         $j = 0;
         if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->getID()])) {
            foreach ($a_perfnames as $name) {
               $_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->getID()][$name] = 'checked';
            }
         }

         foreach ($a_perfnames as $name) {
            if ($i > 0) {
               echo "<tr class='tab_bg_3'>";
            }
            echo "<td>";
            $checked = "checked";
            if (isset($sess['perfname'])
                 && isset($sess['perfname'][$pmComponent->getID()])) {

               if (isset($sess['perfname'][$pmComponent->getID()])) {
                  $checked = "";
               }
               if (isset($sess['perfname'][$pmComponent->getID()][$name])) {
                  $checked = "checked";
               }
            } else {
               if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->getID()])) {
                  $checked = "";
               }
               if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->getID()][$name])) {
                  $checked = $_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->getID()][$name];
               }
            }
            echo "<input type='checkbox' name='perfname[".$pmComponent->getID()."][".$name."]' value='".$name."' ".$checked."/> ".$name;
            if ($checked == 'checked') {
               $a_options['perfname'][$pmComponent->getID()][] = $name;
            }
            echo "</td>";
            echo "<td>";
            echo __('Best is high value', 'monitoring').' :';
            echo "</td>";
            echo "<td>";
            $default_value = 1;
            if (isset($sess['perfname_val'])
                 && isset($sess['perfname_val'][$pmComponent->getID()])) {

               if (isset($sess['perfname_val'][$pmComponent->getID()][$name])) {
                  $default_value = $sess['perfname_val'][$pmComponent->getID()][$name];
               }
            }
            Dropdown::showYesNo('perfname_val['.$pmComponent->getID().']['.$name.']', $default_value);
            if ($checked == 'checked') {
               $a_options['perfname_val'][$pmComponent->getID()][$name] = $default_value;
            }
            echo "</td>";
            echo "</tr>";
            $i++;
         }

         echo "</table>";

         echo "</td>";

         echo "</tr>";
      }
      echo "<tr class='tab_bg_1'>";
      echo "<td colspan='2' align='center'>";
      echo "<input type='submit' class='submit' name='update' value='".__('Save')."'/>";
      echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type='submit' class='submit' name='generatepdf' value='".__('Generate PDF', 'monitoring')."'/>";
      echo "</td>";
      echo "</tr>";
      echo "</table>";

      Html::closeForm();

      if (isset($_SESSION['plugin_monitoring_report'])) {
//         $a_options = $_SESSION['plugin_monitoring_report'];
      }
      $this->generateSyntheseReport(
              $_SESSION['glpi_plugin_monitoring']['synthese'][$componentscatalogs_id],
              FALSE);
   }
 function hasCounters()
 {
     if ($this->fields['graph_template'] == 0) {
         return false;
     }
     // Get component graph configuration ...
     if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$this->fields['id']])) {
         PluginMonitoringToolbox::loadPreferences($this->fields['id']);
     }
     $a_perf = PluginMonitoringPerfdata::getArrayPerfdata($this->fields['graph_template']);
     $myPerfdata = array();
     foreach ($a_perf['parseperfdata'] as $data) {
         $i = 0;
         foreach ($data['DS'] as $data2) {
             $counter = preg_replace("/[^A-Za-z0-9\\-_]/", "", $data['name']);
             if ($data['incremental'][$i] == '1') {
                 $myPerfdata[$counter] = $data2['dsname'];
             }
             $i++;
         }
     }
     return $myPerfdata;
 }
if ($_GET['customdate'] == '' && $_GET['customtime'] == '') {
    $enddate = '';
} else {
    if ($_GET['customdate'] == '') {
        $enddate = mktime(date('H', $_GET['customtime']), date('i', $_GET['customtime']), date('s', $_GET['customtime']));
    } else {
        if ($_GET['customtime'] == '') {
            $enddate = $_GET['customdate'];
        } else {
            // have the 2 defined
            $enddate = mktime(date('H', $_GET['customtime']), date('i', $_GET['customtime']), date('s', $_GET['customtime']), date('n', $_GET['customdate']), date('d', $_GET['customdate']), date('Y', $_GET['customdate']));
        }
    }
}
if (isset($_GET['components_id']) && !isset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']])) {
    PluginMonitoringToolbox::loadPreferences($_GET['components_id']);
}
if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']])) {
    echo json_encode(array());
    //   echo __('No data ...', 'monitoring');
    exit;
}
if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']][''])) {
    unset($_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']]['']);
}
$a_ret = $pmServicegraph->generateData($_GET['rrdtool_template'], $_GET['itemtype'], $_GET['items_id'], $_GET['timezone'], $_GET['time'], $enddate, $_SESSION['glpi_plugin_monitoring']['perfname'][$_GET['components_id']]);
$mydatat = $a_ret[0];
$a_labels = $a_ret[1];
$pmComponent = new PluginMonitoringComponent();
$pmCommand = new PluginMonitoringCommand();
$pmComponent->getFromDB($_GET['components_id']);
    static function preferences($components_id, $loadpreferences = 1, $displayonly = 0)
    {
        global $CFG_GLPI;
        if ($loadpreferences == 1) {
            if (!PluginMonitoringToolbox::loadPreferences($components_id)) {
                return false;
            }
        }
        $pmComponent = new PluginMonitoringComponent();
        $pmComponent->getFromDB($components_id);
        $a_perfnames = array();
        $a_perfnames = PluginMonitoringServicegraph::getperfdataNames($pmComponent->fields['graph_template']);
        echo "<table class='tab_cadre_fixe'>";
        echo "<tr class='tab_bg_3'>";
        echo "<td rowspan='" . ceil(count($a_perfnames) / 7) . "' width='90'>";
        echo __('Display', 'monitoring') . "&nbsp;:";
        echo "</td>";
        $i = 0;
        $j = 0;
        if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$components_id])) {
            foreach ($a_perfnames as $name) {
                $_SESSION['glpi_plugin_monitoring']['perfname'][$components_id][$name] = 'checked';
            }
        }
        echo "<td>";
        $a_incremental = array();
        $a_perfdatadetails = getAllDatasFromTable('glpi_plugin_monitoring_perfdatadetails', "plugin_monitoring_perfdatas_id='" . $pmComponent->fields['graph_template'] . "'");
        foreach ($a_perfdatadetails as $data) {
            for ($nb = 1; $nb <= 15; $nb++) {
                if ($data['dsnameincr' . $nb] == '1') {
                    $a_incremental[$data['dsname' . $nb]] = 1;
                }
            }
        }
        $a_list = array();
        $a_list_val = array();
        foreach ($a_perfnames as $name) {
            $a_list[] = $name;
            if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$components_id][$name])) {
                $a_list_val[] = $name;
            }
            if (isset($a_incremental[$name])) {
                $name .= ' | diff';
                if (isset($_SESSION['glpi_plugin_monitoring']['perfname'][$components_id][$name])) {
                    $a_list_val[] = $name;
                }
                $a_list[] = $name;
            }
        }
        //      <input name="perfname" id="jquery-tagbox-select" type="text" value="'.implode('####', $a_list_val).'" />';
        echo '      <div id="tagbox-container"></div>';
        echo "        <script>\n            \$('#tagbox-container').tagbox({\n                taglist: ['" . implode("', '", $a_list) . "'],\n                selectedlist: ['" . implode("', '", $a_list_val) . "'],\n                cols: 3,\n                maxtags: 4,\n                expand: true\n            });\n\n            \$('#tagbox-container').on('tagAdded', function() {\n               \$.get('" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/updatePerfname.php" . "?components_id=" . $components_id . "&db=" . $loadpreferences . "&perfname=' + \$('.tagbox').data('selected'));\n            });\n            \$('#tagbox-container').on('tagRemoved', function() {\n               \$.get('" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/updatePerfname.php" . "?components_id=" . $components_id . "&db=" . $loadpreferences . "&perfname=' + \$('.tagbox').data('selected'));\n            });\n        </script>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
        if ($displayonly == 1) {
            return;
        }
        // * Invert perfname
        $a_perfnames = array();
        $a_perfnames = PluginMonitoringServicegraph::getperfdataNames($pmComponent->fields['graph_template']);
        echo "<table class='tab_cadre_fixe'>";
        echo "<tr class='tab_bg_3'>";
        echo "<td rowspan='" . ceil(count($a_perfnames) / 7) . "' width='90'>";
        echo __('Invert values', 'monitoring') . "&nbsp;:";
        echo "</td>";
        $i = 0;
        $j = 0;
        echo "<td>";
        echo '<select id="jquery-tagbox-select2-options">';
        $a_incremental = array();
        $a_perfdatadetails = getAllDatasFromTable('glpi_plugin_monitoring_perfdatadetails', "plugin_monitoring_perfdatas_id='" . $pmComponent->fields['graph_template'] . "'");
        foreach ($a_perfdatadetails as $data) {
            for ($nb = 1; $nb <= 15; $nb++) {
                if ($data['dsnameincr' . $nb] == '1') {
                    $a_incremental[$data['dsname' . $nb]] = 1;
                }
            }
        }
        $a_list_val2 = array();
        foreach ($a_list_val as $name) {
            $disabled = '';
            if (isset($_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$components_id][$name])) {
                $a_list_val2[] = $name;
                $disabled = 'disabled="disabled"';
            }
            echo '<option value="' . $name . '" ' . $disabled . '>' . $name . '</option>';
            if (isset($a_incremental[$name])) {
                $name .= ' | diff';
                $disabled = '';
                if (isset($_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$components_id][$name])) {
                    $a_list_val[] = $name;
                    $disabled = 'disabled="disabled"';
                }
                echo '<option value="' . $name . '" ' . $disabled . '>' . $name . '</option>';
            }
        }
        echo '</select>
      <input name="perfnameinvert" id="jquery-tagbox-select2" type="text" value="' . implode('####', $a_list_val2) . '" />';
        echo "</td>";
        //      foreach ($a_perfnames as $name) {
        //         if ($i == 'O'
        //                 AND $j == '1') {
        //            echo "<tr>";
        //         }
        //         echo "<td>";
        //         $checked = "";
        //         if (isset($_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$components_id][$name])) {
        //            $checked = $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$components_id][$name];
        //         }
        //         echo "<input type='checkbox' name='perfnameinvert[]' value='".$name."' ".$checked."/> ".$name;
        //         echo "</td>";
        //         $i++;
        //         if ($i == 6) {
        //            $i = 0;
        //            echo "</tr>";
        //         }
        //         $j = 1;
        //      }
        //      if ($i != 6) {
        //         echo "<td colspan='".(6-$i)."'></td>";
        //         echo "</tr>";
        //      }
        echo "<tr class='tab_bg_3'>";
        echo "<td colspan='9' align='center'>";
        echo "<input type='hidden' name='id' value='" . $components_id . "'/>";
        echo "<input type='submit' name='updateperfdata' value=\"" . __('Save') . "\" class='submit'>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
        // * Define color of perfname
        $a_perfnames = array();
        $a_perfnames = PluginMonitoringServicegraph::getperfdataNames($pmComponent->fields['graph_template']);
        foreach ($a_perfnames as $key => $name) {
            if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$components_id][$name])) {
                unset($a_perfnames[$key]);
            }
        }
        echo "<table class='tab_cadre_fixe'>";
        echo "<tr class='tab_bg_1'>";
        echo "<td rowspan='" . ceil(count($a_perfnames) / 4) . "' width='90'>";
        echo __('Colors', 'monitoring') . "&nbsp;:";
        echo "</td>";
        $i = 0;
        $j = 0;
        $a_colors_warn = PluginMonitoringServicegraph::colors("warn");
        $a_colors_crit = PluginMonitoringServicegraph::colors("crit");
        $a_colors = PluginMonitoringServicegraph::colors();
        foreach ($a_list_val as $name) {
            if ($i == 'O' and $j == '1') {
                echo "<tr>";
            }
            echo "<td>";
            echo $name . "&nbsp;:";
            echo "</td>";
            echo "<td>";
            $color = 'ffffff';
            if (isset($_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$components_id][$name])) {
                $color = $_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$components_id][$name];
            } else {
                if (strstr($name, "warn")) {
                    $color = array_shift($a_colors_warn);
                } else {
                    if (strstr($name, "crit")) {
                        $color = array_shift($a_colors_crit);
                    } else {
                        $color = array_shift($a_colors);
                    }
                }
            }
            echo ' <input class="color" id="color' . $name . '" name="perfnamecolor[' . $name . ']" value="' . $color . '" size="6" />';
            echo '<script type="text/javascript">
var myPicker = new jscolor.color(document.getElementById(\'color' . $name . '\'), {})
myPicker.fromString(\'' . $color . '\')
</script>
';
            //         echo " <select name='perfnamecolor[".$name."]' id='color".$name."'>";
            //         echo "<option value=''>".Dropdown::EMPTY_VALUE."</option>";
            //         foreach ($a_colors as $color) {
            //            $checked = '';
            //            if (isset($_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$components_id][$name])
            //                    AND $_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$components_id][$name] == $color) {
            //               $checked = 'selected';
            //            }
            //            echo "<option value='".$color."' style='background-color: #".$color.";' ".$checked.">".$color."</option>";
            //         }
            //         echo "</select>";
            echo "</td>";
            $i++;
            if ($i == 4) {
                $i = 0;
                echo "</tr>";
            }
            $j = 1;
        }
        if ($i != 4) {
            echo "<td colspan='" . (4 - $i) * 2 . "'></td>";
            echo "</tr>";
        }
        echo "<tr>";
        echo "<td colspan='9' align='center'>";
        echo "<input type='hidden' name='id' value='" . $components_id . "'/>";
        echo "<input type='submit' name='updateperfdata' value=\"" . __('Save') . "\" class='submit'>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
        Html::closeForm();
        return true;
    }
 function view($id, $config = 0)
 {
     global $DB, $CFG_GLPI;
     $pmDisplayview = new PluginMonitoringDisplayview();
     $pmDisplayview_rule = new PluginMonitoringDisplayview_rule();
     $pmDisplayview->getFromDB($id);
     echo "<script type='text/javascript'>\n            function fittext(itemid) {\n               document.getElementById(itemid).style.fontSize = '50px';\n               var fontsize = 50;\n               while(document.getElementById(itemid).offsetWidth > 120) {\n                  fontsize--;\n                  if (fontsize > 20) {\n                     fontsize--;\n                  }\n                  document.getElementById(itemid).style.fontSize = fontsize + 'px';\n               }\n               while(document.getElementById(itemid).offsetHeight > 67) {\n                  fontsize--;\n                  document.getElementById(itemid).style.fontSize = fontsize + 'px';\n               }\n               if (fontsize > 30) {\n                  document.getElementById(itemid).style.fontSize = '30px';\n               }\n               if (fontsize < 7) {\n                  document.getElementById(itemid).style.fontSize = '7px';\n               }\n            }\n         </script>";
     PluginMonitoringToolbox::loadLib();
     $style = '';
     if ($config == '1') {
         $this->addItem($id);
         $pmDisplayview_rule->showReplayRulesForm($id);
         echo "<div id='updatecoordonates'></div>";
         if ($pmDisplayview->fields['width'] > 950) {
             $style = ";position:relative;left:-" . ($pmDisplayview->fields['width'] - 950) / 2 . "px";
         }
     } else {
         if (!is_null($pmDisplayview->fields['counter'])) {
             $pmDisplay = new PluginMonitoringDisplay();
             $pmDisplay->showCounters($pmDisplayview->fields['counter']);
         }
     }
     echo "<table class='tab_cadre_fixe' id='test' style='width:" . $pmDisplayview->fields['width'] . "px" . $style . "'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     echo $pmDisplayview->fields['name'];
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1' id='date_text'>";
     echo "<th>";
     echo __('Select date', 'monitoring') . " - " . __('Select time', 'monitoring');
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     $query = "SELECT * FROM `glpi_plugin_monitoring_displayviews_items`\n         WHERE `plugin_monitoring_displayviews_id`='" . $id . "'\n            AND `itemtype`='PluginMonitoringService'";
     $result = $DB->query($query);
     $a_items = array();
     $end = time();
     $start = time();
     $pmComponent = new PluginMonitoringComponent();
     while ($data = $DB->fetch_array($result)) {
         $itemtype = $data['itemtype'];
         $item = new $itemtype();
         $item->getFromDB($data['items_id']);
         if (isset($item->fields['plugin_monitoring_components_id'])) {
             $oldvalue = current(getAllDatasFromTable('glpi_plugin_monitoring_serviceevents', "`plugin_monitoring_services_id`='" . $data['items_id'] . "'", false, 'date ASC LIMIT 1'));
             $date = new DateTime($oldvalue['date']);
             if ($date->getTimestamp() < $start) {
                 $start = $date->getTimestamp();
             }
             $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
             $a_items["item" . $data['id']] = array('rrdtool_template' => $pmComponent->fields['graph_template'], 'itemtype' => $data['itemtype'], 'items_id' => $data['items_id'], 'timezone' => 0, 'time' => $data['extra_infos'], 'pmComponents_id' => $pmComponent->fields['id']);
         }
     }
     $nbdays = round((date('U') - $start) / 86400);
     echo "<script type=\"text/javascript\">\n      \$(function() {\n          \$( \"#custom_date\" ).datepicker({ minDate: -" . $nbdays . ", maxDate: \"+0D\", dateFormat:'mm/dd/yy' });\n          \$( \"#custom_time\" ).timepicker();\n\n      });\n      </script>";
     echo '<center><input type="text" id="custom_date" value="' . date('m/d/Y') . '"> ' . ' <input type="text" id="custom_time" value="' . date('H:i') . '"></center>';
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1' id='time_text' style='display: none;'>";
     echo "<th>";
     echo __('Select time', 'monitoring');
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     echo __('View', 'monitoring');
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo "<input type='hidden' name='updateviewid' id='updateviewid' value='" . $id . "' />";
     if ($config == 0) {
         echo "<div id='filariane'>&nbsp;</div>";
         echo "<input type='hidden' name='updatefil' id='updatefil' value='" . $id . "!' />";
         echo "<script type=\"text/javascript\">\n            function reloadfil() {\n              \$.get('" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/updateFilariane.php?updatefil=' + \$('#updatefil').val() + '&id=" . $id . "&currentview=' + \$('#updateviewid').val(), function(data) {\n                \$('#filariane').html(data);\n               });\n            }\n            reloadfil();\n         </script>";
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td height='1200' id='panel'>";
     echo "<script type=\"text/javascript\">\n           \$.get('" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/ajax/showPanel.php?id=" . $id . "&config=" . $config . "', function(data) {\n             \$('#panel').html(data);\n            });\n      </script>";
     echo "</td>";
     echo "</tr>";
     echo "</table>";
     echo "<br/>";
 }
function plugin_monitoring_searchOptionsValues($item)
{
    global $CFG_GLPI;
    // Fred : Add a log to check whether this function is still called ...
    PluginMonitoringToolbox::logIfExtradebug('pm', "plugin_monitoring_searchOptionsValues is called ..\n");
    // Search options for services
    if ($item['searchoption']['table'] == 'glpi_plugin_monitoring_services' and $item['searchoption']['field'] == 'state') {
        $input = array();
        $input['CRITICAL'] = 'CRITICAL';
        $input['DOWNTIME'] = 'DOWNTIME';
        $input['FLAPPING'] = 'FLAPPING';
        $input['OK'] = 'OK';
        $input['RECOVERY'] = 'RECOVERY';
        $input['UNKNOWN'] = 'UNKNOWN';
        $input['WARNING'] = 'WARNING';
        Dropdown::showFromArray($item['name'], $input, array('value' => $item['value']));
        return true;
    } else {
        if ($item['searchoption']['table'] == 'glpi_plugin_monitoring_services' and $item['searchoption']['field'] == 'state_type') {
            $input = array();
            $input['HARD'] = 'HARD';
            $input['SOFT'] = 'SOFT';
            Dropdown::showFromArray($item['name'], $input, array('value' => $item['value']));
            return true;
        } else {
            if ($item['searchoption']['table'] == 'glpi_plugin_monitoring_services' and ($item['searchoption']['field'] == 'Computer' or $item['searchoption']['field'] == 'Printer' or $item['searchoption']['field'] == 'NetworkEquipment')) {
                $itemtype = $item['searchoption']['field'];
                $use_ajax = false;
                if ($CFG_GLPI["use_ajax"]) {
                    $nb = countElementsInTable("glpi_plugin_monitoring_componentscatalogs_hosts", "`itemtype`='Computer'");
                    if ($nb > $CFG_GLPI["ajax_limit_count"]) {
                        $use_ajax = true;
                    }
                }
                $params = array();
                $params['itemtype'] = $itemtype;
                $params['searchText'] = '';
                $params['myname'] = $item['name'];
                $params['rand'] = '';
                $params['value'] = $item['value'];
                $default = "<select name='" . $item['name'] . "' id='dropdown_" . $item['name'] . "0'>";
                if (isset($item['value']) and !empty($item['value'])) {
                    $itemm = new $itemtype();
                    $itemm->getFromDB($item['value']);
                    $default .= "<option value='" . $item['value'] . "'>" . $itemm->getName() . "</option></select>";
                }
                Ajax::dropdown($use_ajax, "/plugins/monitoring/ajax/dropdownDevices.php", $params, $default);
                return true;
            }
        }
    }
    // Search options for hosts
    if ($item['searchoption']['table'] == 'glpi_plugin_monitoring_hosts' and $item['searchoption']['field'] == 'state') {
        $input = array();
        $input['DOWN'] = 'DOWN';
        $input['DOWNTIME'] = 'DOWNTIME';
        $input['FLAPPING'] = 'FLAPPING';
        $input['RECOVERY'] = 'RECOVERY';
        $input['UNKNOWN'] = 'UNKNOWN';
        $input['UNREACHABLE'] = 'UNREACHABLE';
        $input['UP'] = 'UP';
        Dropdown::showFromArray($item['name'], $input, array('value' => $item['value']));
        return true;
    } else {
        if ($item['searchoption']['table'] == 'glpi_plugin_monitoring_hosts' and $item['searchoption']['field'] == 'state_type') {
            $input = array();
            $input['HARD'] = 'HARD';
            $input['SOFT'] = 'SOFT';
            Dropdown::showFromArray($item['name'], $input, array('value' => $item['value']));
            return true;
        }
    }
}
   function configureNodesLinks($weathermaps_id) {
      global $DB,$CFG_GLPI;

      $networkPort = new NetworkPort();

      $this->getFromDB($weathermaps_id);

      $style = '';
      if ($this->fields['width'] > 950) {
         $style = ";position:relative;left:-".(($this->fields['width'] - 950) / 2)."px";
      }


      echo "<table class='tab_cadre' style='width:".
              $this->fields['width']."px;height:".$this->fields['height']."px".
              $style."'>";
      echo "<tr class='tab_bg_1'>";
      echo "<th colspan='2'>";
      echo __('Nodes and links', 'monitoring');
      echo "</th>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td valign='top'>";
      echo "<div>";
      PluginMonitoringToolbox::loadLib();
      $this->drawMap($weathermaps_id, 100, 1);
      echo "</div>";
      echo "</td>";
      echo "<td valign='top'>";

      echo "<div style='position: fixed;top: 30px;right: 0;z-index:999;' >";
      echo "<table class='tab_cadre' width='100%'>";
      echo "<tr>";
      echo "<td>";
      echo "<a onClick='Ext.get(\"weathermapform\").toggle();'>
      <img src='".$CFG_GLPI["root_doc"]."/pics/deplier_down.png' />&nbsp;
         ".__('Display weathermap form', 'monitoring')."
      &nbsp;<img src='".$CFG_GLPI["root_doc"]."/pics/deplier_down.png' /></a>";
      echo "</td>";
      echo "</tr>";
      echo"</table>";
      echo "</div>";

      echo "<div style='position: fixed;top: 50px;right: 0;z-index:1000;' id='weathermapform' >";
      echo '<form name="pointform" method="post" action="'.$CFG_GLPI['root_doc'].'/plugins/monitoring/front/weathermapnode.form.php">';
      echo "<table>";
      echo "<tr>";
      echo "<td>";

         echo "<table class='tab_cadre' width='100%'>";
         echo "<tr>";
         echo "<th colspan='2'>";
         echo "x : ";
         echo '<input type="text" name="x" size="4" value="50" />';
         echo " ";
         echo "y : ";
         echo '<input type="text" name="y" size="4" value="50"/>';
         echo "</th>";
         echo "</tr>";

         // * Add node
         echo "<tr>";
         echo "<th colspan='2'>";
         echo "<input type='hidden' name='plugin_monitoring_weathermaps_id' value='".$weathermaps_id."' />";
         echo __('Add a node', 'monitoring');
         echo "</th>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Node', 'monitoring')."&nbsp;:";
         echo "</td>";
         echo "<td>";
         Dropdown::showAllItems("items_id");
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Name')."&nbsp;:";
         echo "</td>";
         echo "<td>";
         echo "<input type='text' name='name' value='' />";
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Position of label', 'monitoring')." :";
         echo "</td>";
         echo "<td>";
         $positions = array(
             'middle' => __('Center', 'monitoring'),
             'start' => __('Right', 'monitoring'),
             'end' => __('Left', 'monitoring')
         );
         Dropdown::showFromArray('position', $positions);
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td align='center' colspan='2'>";
         echo "<input type='submit' name='add' value=\"".__('Add')."\" class='submit'>";
         echo "</td>";
         echo "</tr>";


         // * Change node position
         echo "<tr>";
         echo "<th colspan='2'>";
         echo __('Edit a node', 'monitoring');
         echo "</th>";
         echo "</tr>";

         echo "<tr>";
         echo "<td colspan='2' align='center'>";

         $query = "SELECT * FROM `".getTableForItemType("PluginMonitoringWeathermapnode")."`
            WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
            ORDER BY `name`";
         $result = $DB->query($query);
         $elements = array();
         $elements[0] = Dropdown::EMPTY_VALUE;
         $result = $DB->query($query);
         while ($data=$DB->fetch_array($result)) {
            $itemtype = $data['itemtype'];
            if ($itemtype == '0') {
               $pmWeathermapnode->delete($data);
            } else {
               $item = new $itemtype();
               $item->getFromDB($data['items_id']);
               $name = $data['name'];
               if ($name == '') {
                  $name = $item->getName();
               }
               $elements[$data['id']] = $name;
            }
         }
         $rand = Dropdown::showFromArray('id_update', $elements);

         $params = array('items_id'        => '__VALUE__',
                         'rand'            => $rand);

         Ajax::updateItemOnSelectEvent("dropdown_id_update$rand", "show_updatenode$rand",
                                     $CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/dropdownWnode.php",
                                     $params, TRUE);

         echo "<span id='show_updatenode$rand'></span>\n";

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

         echo "<tr>";
         echo "<td align='center' colspan='2'>";
         echo "<input type='submit' name='update' value=\"".__('Save')."\" class='submit'>";
         echo "</td>";
         echo "</tr>";


         // * Delete node
         echo "<tr>";
         echo "<th colspan='2'>";
         echo __('Delete a node', 'monitoring');
         echo "</th>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo "</td>";
         echo "<td>";
         $query = "SELECT * FROM `".getTableForItemType("PluginMonitoringWeathermapnode")."`
            WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
            ORDER BY `name`";
         $result = $DB->query($query);
         $elements = array();
         $elements[0] = Dropdown::EMPTY_VALUE;
         $result = $DB->query($query);
         while ($data=$DB->fetch_array($result)) {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            $name = $data['name'];
            if ($name == '') {
               $name = $item->getName();
            }
            $elements[$data['id']] = $name;
         }
         Dropdown::showFromArray('id', $elements);
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td align='center' colspan='2'>";
         echo "<input type='submit' name='purge' value=\"".__('Delete permanently')."\" class='submit'>";
         echo "</td>";
         echo "</tr>";

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

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

         echo '<form name="formlink" method="post" action="'.$CFG_GLPI['root_doc'].'/plugins/monitoring/front/weathermaplink.form.php">';
         echo "<table class='tab_cadre' width='100%'>";
         // *Add Link
         echo "<tr>";
         echo "<th colspan='2'>";
         echo __('Add a link', 'monitoring');
         echo "</th>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Source', 'monitoring')."*&nbsp;:";
         echo "</td>";
         echo "<td>";

         $query = "SELECT `glpi_plugin_monitoring_weathermapnodes`.`id` as `id`,
               `glpi_plugin_monitoring_weathermapnodes`.`name` as `name`,
               `glpi_plugin_monitoring_componentscatalogs_hosts`.`itemtype`,
               `glpi_plugin_monitoring_componentscatalogs_hosts`.`items_id`,
               `glpi_plugin_monitoring_services`.`id` as `services_id`,
               `glpi_plugin_monitoring_components`.`name` as `components_name`,
               `plugin_monitoring_commands_id`, `glpi_plugin_monitoring_components`.`arguments`,
               `glpi_plugin_monitoring_services`.`networkports_id`
            FROM `glpi_plugin_monitoring_weathermapnodes`

            LEFT JOIN `glpi_plugin_monitoring_componentscatalogs_hosts`
               ON (`glpi_plugin_monitoring_weathermapnodes`.`items_id`=`glpi_plugin_monitoring_componentscatalogs_hosts`.`items_id`
                  AND `glpi_plugin_monitoring_weathermapnodes`.`itemtype`=`glpi_plugin_monitoring_componentscatalogs_hosts`.`itemtype`)

            LEFT JOIN `glpi_plugin_monitoring_services`
               ON `plugin_monitoring_componentscatalogs_hosts_id`= `glpi_plugin_monitoring_componentscatalogs_hosts`.`id`

            LEFT JOIN `glpi_plugin_monitoring_components`
               ON `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id`


            WHERE `is_weathermap` = '1'
               AND `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
            ORDER BY `itemtype`,`items_id`,`glpi_plugin_monitoring_components`.`name`";
         $elements = array();
         $elements[0] = Dropdown::EMPTY_VALUE;
         $elements2 = array();
         $result = $DB->query($query);
         while ($data=$DB->fetch_array($result)) {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            $name = $data['name'];
            if ($name == '') {
               $name = $item->getName();
            }
            // Try to get device/node connected on this port
            $device_connected = '';
            if ($data['arguments'] != '') {
               $arguments = importArrayFromDB($data['arguments']);
               foreach ($arguments as $argument) {
                  if (!is_numeric($argument)) {
                     if (strstr($argument, "[[NETWORKPORTDESCR]]")){
                        if (class_exists("PluginFusinvsnmpNetworkPort")) {
                           $pfNetworkPort = new PluginFusinvsnmpNetworkPort();
                           $pfNetworkPort->loadNetworkport($data['networkports_id']);
                           $argument = $pfNetworkPort->getValue("ifdescr");
                        }
                     } elseif (strstr($argument, "[[NETWORKPORTNUM]]")){
                        $networkPort = new NetworkPort();
                        $networkPort->getFromDB($data['networkports_id']);
                        $argument = $pfNetworkPort->fields['logical_number'];
                     } elseif (strstr($argument, "[[NETWORKPORTNAME]]")){
                        $networkPort = new NetworkPort();
                        $networkPort->getFromDB($data['networkports_id']);
                        $argument = $pfNetworkPort->fields['name'];
                     }


                     // Search networkport have this name or description
                     $a_ports = $networkPort->find("`itemtype`='".$itemtype."'
                        AND `items_id`='".$data['items_id']."'
                        AND `name`='".$argument."'");
                     foreach ($a_ports as $pdata) {
                        if ($device_connected == '') {
                           $oppositeports_id = $networkPort->getContact($pdata['id']);
                           if ($oppositeports_id) {
                              $networkPort->getFromDB($oppositeports_id);
                              $a_nodes = $pmWeathermapnode->find("
                                 `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
                                 AND `itemtype`='".$networkPort->fields['itemtype']."'
                                 AND `items_id`='".$networkPort->fields['items_id']."'", "", 1);
                              if (count($a_nodes) > 0) {
                                 $a_node = current($a_nodes);
                                 $device_connected = $pmWeathermapnode->getNodeName($a_node['id']);
                              }
                           }
                        }
                     }
                     if ($device_connected == ''
                             AND class_exists("PluginFusinvsnmpNetworkPort")) {
                        $queryn = "SELECT `glpi_networkports`.`id` FROM `glpi_plugin_fusinvsnmp_networkports`

                           LEFT JOIN `glpi_networkports`
                              ON `glpi_networkports`.`id`=`networkports_id`

                           WHERE `itemtype`='".$itemtype."'
                           AND `items_id`='".$data['items_id']."'
                           AND `ifdescr`='".$argument."'";
                        $resultn = $DB->query($queryn);
                        while ($pdata=$DB->fetch_array($resultn)) {
                           if ($device_connected == '') {
                              $oppositeports_id = $networkPort->getContact($pdata['id']);
                              if ($oppositeports_id) {
                                 $networkPort->getFromDB($oppositeports_id);
                                 $a_nodes = $pmWeathermapnode->find("
                                    `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
                                    AND `itemtype`='".$networkPort->fields['itemtype']."'
                                    AND `items_id`='".$networkPort->fields['items_id']."'", "", 1);
                                 if (count($a_nodes) > 0) {
                                    $a_node = current($a_nodes);

                                    $queryl = "SELECT `plugin_monitoring_weathermapnodes_id_1`
                                       FROM `glpi_plugin_monitoring_weathermaplinks`

                                       LEFT JOIN `glpi_plugin_monitoring_weathermapnodes`
                                          ON `glpi_plugin_monitoring_weathermapnodes`.`id` = `plugin_monitoring_weathermapnodes_id_1`

                                       WHERE ((`plugin_monitoring_weathermapnodes_id_1`='".$data['id']."'
                                                   AND `plugin_monitoring_weathermapnodes_id_2`='".$a_node['id']."')
                                                OR (`plugin_monitoring_weathermapnodes_id_1`='".$a_node['id']."'
                                                   AND `plugin_monitoring_weathermapnodes_id_2`='".$data['id']."'))
                                          AND `plugin_monitoring_weathermaps_id` = '".$weathermaps_id."'";
                                    $resultl = $DB->query($queryl);
                                    if ($DB->numrows($resultl) == '0') {
                                       $device_connected = $pmWeathermapnode->getNodeName($a_node['id']);
                                    }
                                 }
                              }
                           }
                        }
                     }
                  }
               }
            }
            if ($device_connected == '') {
               $networkPort->getFromDB($data['networkports_id']);
               $elements2[$data['id']."-".$data['services_id']] = $name." [".$networkPort->getfield('name')."] (".$data['components_name'].")";
            } else {
               $networkPort->getFromDB($data['networkports_id']);
               $elements[$data['id']."-".$data['services_id']] = $name." [".$networkPort->getfield('name')."] (".$data['components_name'].") > ".$device_connected;
            }
         }
         if (count($elements) > 1
                 AND count($elements2) > 0) {

            $elements = array_merge($elements,array('0'=>Dropdown::EMPTY_VALUE));
            $elements = array_merge($elements, $elements2);

         } else {
            $elements = array_merge($elements, $elements2);
         }

         Dropdown::showFromArray('linksource', $elements);

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

         echo "<tr>";
         echo "<td>";
         echo __('Destination', 'monitoring')."&nbsp;:";
         echo "</td>";
         echo "<td>";

         echo "<div id='nodedestination'>";

         $query = "SELECT * FROM `".getTableForItemType("PluginMonitoringWeathermapnode")."`
            WHERE `plugin_monitoring_weathermaps_id`='".$weathermaps_id."'
            ORDER BY `name`";
         $result = $DB->query($query);
         $elements = array();
         $elements[0] = Dropdown::EMPTY_VALUE;
         $result = $DB->query($query);
         while ($data=$DB->fetch_array($result)) {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            $name = $data['name'];
            if ($name == '') {
               $name = $item->getName();
            }
            $elements[$data['id']] = $name;
         }
         Dropdown::showFromArray('plugin_monitoring_weathermapnodes_id_2', $elements);
         echo "</div>";
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Max bandwidth input', 'monitoring')."&nbsp;:";
         echo "</td>";
         echo "<td>";
         echo "<input type='text' name='bandwidth_in' value=''/>";
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Max bandwidth output', 'monitoring')."&nbsp;:";
         echo "</td>";
         echo "<td>";
         echo "<input type='text' name='bandwidth_out' value=''/>";
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td align='center' colspan='2'>";
         echo "<input type='submit' name='add' value=\"".__('Add')."\" class='submit'>";
         echo "</td>";
         echo "</tr>";

         // * Edit link
         echo "<tr>";
         echo "<th colspan='2'>";
         echo __('Edit a link', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr>";
         echo "<td colspan='2' align='center'>";
         $pmWeathermapnode = new PluginMonitoringWeathermapnode();
         $query = "SELECT `glpi_plugin_monitoring_weathermaplinks`.`id` as `id`,
               `itemtype`, `items_id`, `name`, `plugin_monitoring_weathermapnodes_id_2`
            FROM `glpi_plugin_monitoring_weathermaplinks`

            LEFT JOIN `glpi_plugin_monitoring_weathermapnodes`
               ON `glpi_plugin_monitoring_weathermapnodes`.`id` = `plugin_monitoring_weathermapnodes_id_1`

            WHERE `plugin_monitoring_weathermaps_id` = '".$weathermaps_id."'";
         $elements = array();
         $elements[0] = Dropdown::EMPTY_VALUE;
         $result = $DB->query($query);
         while ($data=$DB->fetch_array($result)) {
            $itemtype = $data['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($data['items_id']);
            $name1 = $data['name'];
            if ($name1 == '') {
               $name1 = $item->getName();
            }
            $pmWeathermapnode->getFromDB($data['plugin_monitoring_weathermapnodes_id_2']);
            $itemtype = $pmWeathermapnode->fields['itemtype'];
            $item = new $itemtype();
            $item->getFromDB($pmWeathermapnode->fields['items_id']);
            $name2 = $pmWeathermapnode->fields['name'];
            if ($name2 == '') {
               $name2 = $item->getName();
            }

            $elements[$data['id']] = $name1." - ".$name2;
         }
         $rand = Dropdown::showFromArray('id_update', $elements);

         $params = array('items_id'        => '__VALUE__',
                         'rand'            => $rand);

         Ajax::updateItemOnSelectEvent("dropdown_id_update$rand", "show_updatelink$rand",
                                     $CFG_GLPI["root_doc"]."/plugins/monitoring/ajax/dropdownWlink.php",
                                     $params, TRUE);
         echo "<span id='show_updatelink$rand'></span>\n";
         echo "</td>";
         echo "</tr>";


         // * Delete link
         echo "<tr>";
         echo "<th colspan='2'>";
         echo __('Delete a link', 'monitoring');
         echo "</th>";
         echo "</tr>";

         echo "<tr>";
         echo "<td>";
         echo __('Link', 'monitoring')." :";
         echo "</td>";
         echo "<td>";
         Dropdown::showFromArray('id', $elements);
         echo "</td>";
         echo "</tr>";

         echo "<tr>";
         echo "<td align='center' colspan='2'>";
         echo "<input type='submit' name='purge' value=\"".__('Delete permanently')."\" class='submit'>";
         echo "</td>";
         echo "</tr>";

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

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

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

      echo "</table>";
   }
   /**
    * Display graphs of services associated with host
    *
    * @param $itemtype value type of item
    * @param $items_id integer id of the object
    *
    **/
   function showGraphsByHost($itemtype, $items_id) {
      global $CFG_GLPI,$DB;

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

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

      echo '<center><input type="text" id="custom_date" value="'.date('m/d/Y').'"> '
              . ' <input type="text" id="custom_time" value="'.date('H:i').'"></center>';

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

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

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

   }
 /**
  * Actions done before the DELETE of the item in the database /
  * Maybe used to add another check for deletion
  *
  * @return bool : true if item need to be deleted else false
  **/
 function pre_deleteItem()
 {
     PluginMonitoringToolbox::logIfExtradebug('pm-ack', "acknowledge, pre_deleteItem : " . $this->fields['id'] . "\n");
     $user = new User();
     $user->getFromDB($this->fields['users_id']);
     $item = new $this->fields['itemtype']();
     $item->getFromDB($this->fields['items_id']);
     $host_id = -1;
     $service_id = -1;
     if ($this->fields['itemtype'] == 'PluginMonitoringHost') {
         $host_id = $this->fields['items_id'];
     } else {
         $service_id = $this->fields['items_id'];
     }
     if ($host_id != -1) {
         // Acknowledge is to be deleted ...
         // ... send information to shinken via webservice
         $pmShinkenwebservice = new PluginMonitoringShinkenwebservice();
         if ($pmShinkenwebservice->sendAcknowledge($host_id, -1, $user->getName(1), '', '', '', '', 'delete')) {
             // Set host as acknowledged
             // $pmHost = new PluginMonitoringHost();
             // $pmHost->getFromDB($this->fields['plugin_monitoring_hosts_id']);
             // $item->setAcknowledged($this->fields['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), '', '', '', '', 'delete')) {
                         // Set service as acknowledged
                         // $pmService = new PluginMonitoringService();
                         // $pmService->getFromDB($service_id);
                         // $pmService->setAcknowledged($this->fields['comment']);
                     }
                 }
             }
             Session::addMessageAfterRedirect(__('Acknowledge deletion notified to the monitoring application:', 'monitoring'));
             $this->fields['notified'] = 1;
         } else {
             Session::addMessageAfterRedirect(__('Acknowledge deletion has not been accepted by the monitoring application:', '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), '', '', '', '', 'delete')) {
             // Set service as acknowledged
             // $pmService = new PluginMonitoringService();
             // $pmService->getFromDB($service_id);
             // $pmService->setAcknowledged($this->fields['comment']);
             Session::addMessageAfterRedirect(__('Acknowledge deletion notified to the monitoring application:', 'monitoring'));
             $this->fields['notified'] = 1;
         } else {
             Session::addMessageAfterRedirect(__('Acknowledge deletion has not been accepted by the monitoring application:', 'monitoring'), false, ERROR);
             // return false;
         }
     }
     return true;
 }
        $item = new $itemtype();
        $item->getFromDB($items_id);
        $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
        $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$pmComponent->fields['id']] = array();
        $_POST['perfnameinvert'] = explode("####", $_POST['perfnameinvert']);
        foreach ($_POST["perfnameinvert"] as $perfname) {
            $_SESSION['glpi_plugin_monitoring']['perfnameinvert'][$pmComponent->fields['id']][$perfname] = "checked";
        }
    }
    if (isset($_POST["perfnamecolor"])) {
        $itemtype = $_GET['itemtype'];
        $items_id = $_GET['items_id'];
        $item = new $itemtype();
        $item->getFromDB($items_id);
        $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
        $_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$pmComponent->fields['id']] = array();
        foreach ($_POST["perfnamecolor"] as $perfname => $color) {
            if ($color != '') {
                $_SESSION['glpi_plugin_monitoring']['perfnamecolor'][$pmComponent->fields['id']][$perfname] = $color;
            }
        }
    }
    Html::back();
}
$pMonitoringDisplay = new PluginMonitoringDisplay();
if (isset($_GET['itemtype']) and isset($_GET['items_id'])) {
    PluginMonitoringToolbox::loadLib();
    $pmServicegraph = new PluginMonitoringServicegraph();
    $pMonitoringDisplay->displayGraphs($_GET['itemtype'], $_GET['items_id']);
}
Html::footer();
   function generateTimeperiodsCfg($file=0) {

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateTimeperiodsCfg ...\n"
      );
      $calendar         = new Calendar();
      $calendarSegment  = new CalendarSegment();
      $calendar_Holiday = new Calendar_Holiday();
      $holiday          = new Holiday();

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

      $a_listcalendar = $calendar->find();
      foreach ($a_listcalendar as $datacalendar) {
         $a_timeperiods[$i]['timeperiod_name'] = $datacalendar['name'];
         $a_timeperiods[$i]['alias'] = $datacalendar['name'];
         $a_listsegment = $calendarSegment->find("`calendars_id`='".$datacalendar['id']."'");
         $a_cal = array();
         foreach ($a_listsegment as $datasegment) {
            $begin = preg_replace("/:00$/", "", $datasegment['begin']);
            $end = preg_replace("/:00$/", "", $datasegment['end']);
            $day = "";
            switch ($datasegment['day']) {

               case "0":
                  $day = "sunday";
                  break;

               case "1":
                  $day = "monday";
                  break;

               case "2":
                  $day = "tuesday";
                  break;

               case "3":
                  $day = "wednesday";
                  break;

               case "4":
                  $day = "thursday";
                  break;

               case "5":
                  $day = "friday";
                  break;

               case "6":
                  $day = "saturday";
                  break;

            }
            $a_cal[$day][] = $begin."-".$end;
         }
         foreach ($a_cal as $day=>$a_times) {
            $a_timeperiods[$i][$day] = implode(',', $a_times);
         }
         $a_cholidays = $calendar_Holiday->find("`calendars_id`='".$datacalendar['id']."'");
         foreach ($a_cholidays as $a_choliday) {
            $holiday->getFromDB($a_choliday['holidays_id']);
            if ($holiday->fields['is_perpetual'] == 1
                    && $holiday->fields['begin_date'] == $holiday->fields['end_date']) {
               $datetime = strtotime($holiday->fields['begin_date']);
               $a_timeperiods[$i][strtolower(date('F', $datetime)).
                   ' '.date('j', $datetime)] = '00:00-00:00';
            }
         }
         $i++;
      }

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "End generateTimeperiodsCfg\n"
      );

      if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on ".date("Y-m-d H:i:s")."\n\n";

         foreach ($a_timeperiods as $data) {
            $config .= $this->writeFile("timeperiod", $data);
         }
         return array('timeperiods.cfg', $config);

      } else {
         return $a_timeperiods;
      }
   }
 function generateTimeperiodsCfg($file = 0, $tag = '')
 {
     global $DB;
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Starting generateTimeperiodsCfg ...\n");
     $calendar = new Calendar();
     $calendarSegment = new CalendarSegment();
     $calendar_Holiday = new Calendar_Holiday();
     $holiday = new Holiday();
     $hostconfig = new PluginMonitoringHostconfig();
     $pmEntity = new PluginMonitoringEntity();
     // Get list of entities
     $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
     $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_entities", '', $a_entities_list);
     }
     foreach ($a_entities_list as $entities_id) {
         $jetlag = $hostconfig->getValueAncestor('jetlag', $entities_id);
         $a_entities_list[$entities_id] = $jetlag;
     }
     // Get all calendars of components
     $cals_entities = array();
     $query = "SELECT `entities_id`, `calendars_id`\n         FROM `glpi_plugin_monitoring_services`\n         LEFT JOIN `glpi_plugin_monitoring_components`\n            ON `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id` ";
     if ($where == '') {
         $query .= "WHERE `glpi_plugin_monitoring_components`.`id` IS NOT NULL";
     } else {
         $query .= $where . " AND `glpi_plugin_monitoring_components`.`id` IS NOT NULL";
     }
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (!isset($cals_entities[$data['entities_id']])) {
             $cals_entities[$data['entities_id']] = array();
         }
         $cals_entities[$data['entities_id']][$data['calendars_id']] = $data['calendars_id'];
     }
     // get all calendars of servciescatalog
     $query = "SELECT `entities_id`, `calendars_id`\n         FROM `glpi_plugin_monitoring_servicescatalogs` " . $where;
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (!isset($cals_entities[$data['entities_id']])) {
             $cals_entities[$data['entities_id']] = array();
         }
         $cals_entities[$data['entities_id']][$data['calendars_id']] = $data['calendars_id'];
     }
     // Get all calendars of contacts TODO
     $calendars_added = array();
     $a_timeperiods = array();
     $i = 0;
     foreach ($cals_entities as $entities_id => $calendars) {
         foreach ($calendars as $calendars_id) {
             $jetlag = $a_entities_list[$entities_id];
             if (!isset($calendars_added[$calendars_id . "-" . $jetlag])) {
                 $calendars_added[$calendars_id . "-" . $jetlag] = 1;
                 $calendar->getFromDB($calendars_id);
                 $tmp = array();
                 $tmp['timeperiod_name'] = $calendar->fields['name'];
                 $tmp['alias'] = $calendar->fields['name'];
                 $a_listsegment = $calendarSegment->find("`calendars_id`='" . $calendar->fields['id'] . "'");
                 $a_cal = array();
                 foreach ($a_listsegment as $datasegment) {
                     $begin = preg_replace("/:00\$/", "", $datasegment['begin']);
                     $end = preg_replace("/:00\$/", "", $datasegment['end']);
                     $day = "";
                     switch ($datasegment['day']) {
                         case "0":
                             $day = "sunday";
                             break;
                         case "1":
                             $day = "monday";
                             break;
                         case "2":
                             $day = "tuesday";
                             break;
                         case "3":
                             $day = "wednesday";
                             break;
                         case "4":
                             $day = "thursday";
                             break;
                         case "5":
                             $day = "friday";
                             break;
                         case "6":
                             $day = "saturday";
                             break;
                     }
                     $a_cal[$day][] = $begin . "-" . $end;
                 }
                 foreach ($a_cal as $day => $a_times) {
                     $tmp[$day] = implode(',', $a_times);
                 }
                 $a_cholidays = $calendar_Holiday->find("`calendars_id`='" . $calendar->fields['id'] . "'");
                 foreach ($a_cholidays as $a_choliday) {
                     $holiday->getFromDB($a_choliday['holidays_id']);
                     if ($holiday->fields['is_perpetual'] == 1 && $holiday->fields['begin_date'] == $holiday->fields['end_date']) {
                         $datetime = strtotime($holiday->fields['begin_date']);
                         $tmp[strtolower(date('F', $datetime)) . ' ' . date('j', $datetime)] = '00:00-00:00';
                     }
                 }
                 if ($jetlag == 0) {
                     $tmp['timeperiod_name'] = $tmp['timeperiod_name'];
                     $tmp['alias'] = $tmp['alias'];
                 } else {
                     $tmp['timeperiod_name'] = $tmp['timeperiod_name'] . "-" . $jetlag;
                     $tmp['alias'] = $tmp['alias'] . "-" . $jetlag;
                 }
                 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
                 $saturday = '';
                 $reportHours = 0;
                 $beforeday = 'saturday';
                 foreach ($days as $numday => $day) {
                     if (isset($tmp[$day])) {
                         $splitDay = explode(',', $tmp[$day]);
                         $toAdd = '';
                         if ($reportHours > 0) {
                             $toAdd = '00:00-' . sprintf("%02s", $reportHours) . ':00';
                             $reportHours = 0;
                         }
                         foreach ($splitDay as $num => $hourMinute) {
                             $previous_begin = 0;
                             $beginEnd = explode('-', $hourMinute);
                             // ** Begin **
                             $split = explode(':', $beginEnd[0]);
                             $split[0] += $jetlag;
                             if ($split[0] > 24) {
                                 //$reportHours = $split[0] - 24;
                                 unset($splitDay[$num]);
                             } else {
                                 if ($split[0] < 0) {
                                     $reportHours = $split[0];
                                     $previous_begin = 24 + $split[0];
                                     $split[0] = '00';
                                 }
                                 $beginEnd[0] = sprintf("%02s", $split[0]) . ':' . $split[1];
                                 // ** End **
                                 $split = explode(':', $beginEnd[1]);
                                 $split[0] += $jetlag;
                                 if ($split[0] < 0) {
                                     if ($numday - 1 == -1) {
                                         $saturday .= "," . sprintf("%02s", $previous_begin) . ":00-" . sprintf("%02s", 24 + $split[0]) . ":00";
                                     } else {
                                         $tmp[$days[$numday - 1]] .= "," . sprintf("%02s", $previous_begin) . ":00-" . sprintf("%02s", 24 + $split[0]) . ":00";
                                     }
                                     unset($splitDay[$num]);
                                 } else {
                                     if ($split[0] > 24) {
                                         $reportHours = $split[0] - 24;
                                         $split[0] = 24;
                                     }
                                     $beginEnd[1] = sprintf("%02s", $split[0]) . ':' . $split[1];
                                     $hourMinute = implode('-', $beginEnd);
                                     $splitDay[$num] = $hourMinute;
                                 }
                             }
                         }
                         if ($reportHours < 0) {
                             //                     if (!isset($tmp[$beforeday])) {
                             //                        $tmp[$beforeday] = array();
                             //                     }
                             //                     $splitBeforeDay = explode(',', $tmp[$beforeday]);
                             //                     $splitBeforeDay[] = sprintf("%02s", (24 + $reportHours)).':00-24:00';
                             //                     $tmp[$beforeday] = implode(',', $splitBeforeDay);
                             $reportHours = 0;
                         }
                         if (!empty($toAdd)) {
                             array_unshift($splitDay, $toAdd);
                         }
                         $tmp[$day] = implode(',', $splitDay);
                     } else {
                         if ($reportHours > 0) {
                             //$tmp[$day] = '00:00-'.$reportHours.':00';
                             $reportHours = 0;
                         }
                     }
                     $beforeday = $day;
                 }
                 // Manage for report hours from saturday to sunday
                 if ($reportHours > 0) {
                     $splitDay = explode(',', $tmp['sunday']);
                     array_unshift($splitDay, '00:00-' . sprintf("%02s", $reportHours) . ':00');
                     $tmp['sunday'] = implode(',', $splitDay);
                 }
                 if ($saturday != '') {
                     if (isset($tmp['saturday'])) {
                         $tmp['saturday'] .= $saturday;
                     } else {
                         $tmp['saturday'] = $saturday;
                     }
                 }
                 // concatain if need
                 foreach ($days as $day) {
                     if (isset($tmp[$day])) {
                         $splitDay = explode(',', $tmp[$day]);
                         $beforeHour = '';
                         $beforeNum = 0;
                         foreach ($splitDay as $num => $data) {
                             if (substr($data, 0, 2) == $beforeHour) {
                                 $splitDay[$beforeNum] = substr($splitDay[$beforeNum], 0, 6) . substr($data, 6, 5);
                                 $beforeHour = substr($data, 6, 2);
                                 unset($splitDay[$num]);
                             } else {
                                 $beforeHour = substr($data, 6, 2);
                                 $beforeNum = $num;
                             }
                         }
                         $tmp[$day] = implode(',', $splitDay);
                     }
                 }
                 $a_timeperiods[$i] = $tmp;
                 $i++;
             }
         }
     }
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateTimeperiodsCfg\n");
     if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on " . date("Y-m-d H:i:s") . "\n\n";
         foreach ($a_timeperiods as $data) {
             $config .= $this->writeFile("timeperiod", $data);
         }
         return array('timeperiods.cfg', $config);
     } else {
         return $a_timeperiods;
     }
 }