コード例 #1
0
 function getAllDatas($params)
 {
     global $DB;
     $tasks_id = $params['tasks_id'];
     $sql = " SELECT *\n               FROM `" . $this->getTable() . "`\n               WHERE `plugin_fusioninventory_deploytasks_id` = '{$tasks_id}'\n               AND (method = 'deployinstall' OR method = 'deployuninstall')";
     $res = $DB->query($sql);
     $json = array();
     $temp_tasks = array();
     while ($row = $DB->fetch_assoc($res)) {
         $row['packages'] = importArrayFromDB($row['definition']);
         $row['actions'] = importArrayFromDB($row['action']);
         $temp_tasks[] = $row;
     }
     $i = 0;
     foreach ($temp_tasks as $task) {
         foreach ($task['actions'] as $action) {
             foreach ($task['packages'] as $package) {
                 $tmp = array_keys($action);
                 $action_type = $tmp[0];
                 $json['tasks'][$i]['package_id'] = $package['PluginFusioninventoryDeployPackage'];
                 $json['tasks'][$i]['method'] = $task['method'];
                 $json['tasks'][$i]['comment'] = $task['comment'];
                 $json['tasks'][$i]['retry_nb'] = $task['retry_nb'];
                 $json['tasks'][$i]['retry_time'] = $task['retry_time'];
                 $json['tasks'][$i]['action_type'] = $action_type;
                 $json['tasks'][$i]['action_selection'] = $action[$action_type];
                 $obj_action = new $action_type();
                 $obj_action->getFromDB($action[$action_type]);
                 $json['tasks'][$i]['action_name'] = $obj_action->getField('name');
                 $i++;
             }
         }
     }
     return json_encode($json);
 }
コード例 #2
0
 static function preClone(Profile $srce, array $input)
 {
     // decode array
     if (isset($input['helpdesk_item_type']) && !is_array($input['helpdesk_item_type'])) {
         $input['helpdesk_item_type'] = importArrayFromDB($input['helpdesk_item_type']);
     }
     // Empty/NULL case
     if (!isset($input['helpdesk_item_type']) || !is_array($input['helpdesk_item_type'])) {
         $input['helpdesk_item_type'] = array();
     }
     return $input;
 }
コード例 #3
0
 static function isThisItemCheckRuleNetworkport($parm)
 {
     global $DB;
     $pmComponentscatalog_rule = new self();
     $pmService = new PluginMonitoringService();
     $pmSearch = new PluginMonitoringSearch();
     $a_networkports_id = array();
     if (get_class($parm) == 'PluginMonitoringNetworkport') {
         $a_networkports_id[$parm->fields['networkports_id']] = $parm->fields['items_id'];
     } else {
         if (get_class($parm) == 'NetworkEquipment') {
             $query = "SELECT * FROM `glpi_plugin_monitoring_networkports`\n            WHERE `items_id`='" . $parm->fields['id'] . "'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_array($result)) {
                 $a_networkports_id[$data['networkports_id']] = $parm->fields['id'];
             }
         }
     }
     foreach ($a_networkports_id as $networkports_id => $networkequipments_id) {
         $a_find = array();
         $query = "SELECT * FROM `" . $pmComponentscatalog_rule->getTable() . "`\n            WHERE `itemtype`='PluginMonitoringNetworkport'";
         $result = $DB->query($query);
         $get_tmp = array();
         if (isset($_GET)) {
             $get_tmp = $_GET;
         }
         while ($data = $DB->fetch_array($result)) {
             if (isset($_SESSION["glpisearchcount"][$data['itemtype']])) {
                 unset($_SESSION["glpisearchcount"][$data['itemtype']]);
             }
             if (isset($_SESSION["glpisearchcount2"][$data['itemtype']])) {
                 unset($_SESSION["glpisearchcount2"][$data['itemtype']]);
             }
             $_GET = importArrayFromDB($data['condition']);
             $_GET["glpisearchcount"] = count($_GET['field']);
             if (isset($_GET['field2'])) {
                 $_GET["glpisearchcount2"] = count($_GET['field2']);
             }
             if (!isset($_SESSION['glpiactiveentities_string'])) {
                 $_SESSION['glpiactiveentities_string'] = $parm->fields['entities_id'];
             }
             Search::manageGetValues($data['itemtype']);
             $resultr = $pmSearch->constructSQL("PluginMonitoringNetworkport", $_GET, $networkports_id);
             if ($DB->numrows($resultr) > 0) {
                 $a_find[$data['plugin_monitoring_componentscalalog_id']][$networkports_id] = 1;
             } else {
                 if (!isset($a_find[$data['plugin_monitoring_componentscalalog_id']][$networkports_id])) {
                     $a_find[$data['plugin_monitoring_componentscalalog_id']][$networkports_id] = 0;
                 }
             }
         }
         if (count($get_tmp) > 0) {
             $_GET = $get_tmp;
         }
         $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
         foreach ($a_find as $componentscalalog_id => $datan) {
             foreach ($datan as $networkports_id => $is_present) {
                 // Get all networports in this rule
                 if ($is_present == '0') {
                     // * Remove from dynamic if present
                     $query = "SELECT `glpi_plugin_monitoring_services`.`id`,\n                        `glpi_plugin_monitoring_componentscatalogs_hosts`.`id` as hid\n                        FROM `glpi_plugin_monitoring_services`\n                     LEFT JOIN `glpi_plugin_monitoring_componentscatalogs_hosts` ON\n                        `plugin_monitoring_componentscatalogs_hosts_id` = `glpi_plugin_monitoring_componentscatalogs_hosts`.`id`\n                     WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                        AND `itemtype`='NetworkEquipment'\n                        AND `items_id`='" . $networkequipments_id . "'\n                        AND `is_static`='0'\n                        AND `networkports_id`='" . $networkports_id . "'";
                     $result = $DB->query($query);
                     while ($data = $DB->fetch_array($result)) {
                         $pmComponentscatalog_Host->getFromDB($data['hid']);
                         $_SESSION['plugin_monitoring_hosts'] = $pmComponentscatalog_Host->fields;
                         $pmService->delete(array('id' => $data['id']));
                     }
                 } else {
                     //  add if not present
                     // * Add componentscatalogs_hosts if not exist
                     $componentscatalogs_hosts_id = 0;
                     $query = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n                     WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscalalog_id . "'\n                        AND `itemtype`='NetworkEquipment'\n                        AND `items_id`='" . $networkequipments_id . "'\n                           LIMIT 1";
                     $result = $DB->query($query);
                     if ($DB->numrows($result) == '0') {
                         $input = array();
                         $input['plugin_monitoring_componentscalalog_id'] = $componentscalalog_id;
                         $input['is_static'] = '0';
                         $input['itemtype'] = "NetworkEquipment";
                         $input['items_id'] = $networkequipments_id;
                         $componentscatalogs_hosts_id = $pmComponentscatalog_Host->add($input);
                     } else {
                         $a_componentscatalogs_hosts = $DB->fetch_assoc($result);
                         $componentscatalogs_hosts_id = $a_componentscatalogs_hosts['id'];
                     }
                     // * Add service if not exist
                     $pmComponentscatalog_Host->linkComponentsToItem($componentscalalog_id, $componentscatalogs_hosts_id, $networkports_id);
                 }
             }
         }
     }
 }
コード例 #4
0
    glpi_header($_SERVER['HTTP_REFERER']);
} else {
    if (isset($_POST['timezones_add'])) {
        $input = array();
        $pmConfig->getFromDB($_POST['id']);
        $input['id'] = $_POST['id'];
        $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
        foreach ($_POST['timezones_to_add'] as $timezone) {
            $a_timezones[] = $timezone;
        }
        $input['timezones'] = exportArrayToDB($a_timezones);
        $pmConfig->update($input);
        glpi_header($_SERVER['HTTP_REFERER']);
    } else {
        if (isset($_POST['timezones_delete'])) {
            $input = array();
            $pmConfig->getFromDB($_POST['id']);
            $input['id'] = $_POST['id'];
            $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
            foreach ($_POST['timezones_to_delete'] as $timezone) {
                $key = array_search($timezone, $a_timezones);
                unset($a_timezones[$key]);
            }
            $input['timezones'] = exportArrayToDB($a_timezones);
            $pmConfig->update($input);
            glpi_header($_SERVER['HTTP_REFERER']);
        }
    }
}
$pmConfig->showForm(0);
commonFooter();
 /**
  * @see NetworkPortInstantiation::getInstantiationHTMLTable()
  **/
 function getInstantiationHTMLTable(NetworkPort $netport, HTMLTableRow $row, HTMLTableCell $father = NULL, array $options = array())
 {
     if (isset($this->fields['networkports_id_list']) && is_string($this->fields['networkports_id_list'])) {
         $this->fields['networkports_id_list'] = importArrayFromDB($this->fields['networkports_id_list']);
     }
     $row->addCell($row->getHeaderByName('Instantiation', 'Origin'), $this->getInstantiationNetworkPortHTMLTable());
     parent::getInstantiationHTMLTable($netport, $row, $father, $options);
     return NULL;
 }
コード例 #6
0
   function generateServicesCfg($file=0, $tag='') {
      global $DB;

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateServicesCfg services ($tag) ...\n"
      );
      $pMonitoringCommand      = new PluginMonitoringCommand();
      $pmEventhandler          = new PluginMonitoringEventhandler();
      $pMonitoringCheck        = new PluginMonitoringCheck();
      $pmComponent             = new PluginMonitoringComponent();
      $pmEntity                = new PluginMonitoringEntity();
      $pmContact_Item          = new PluginMonitoringContact_Item();
      $networkPort             = new NetworkPort();
      $pmService               = new PluginMonitoringService();
      $pmComponentscatalog     = new PluginMonitoringComponentscatalog();
      $pmHostconfig            = new PluginMonitoringHostconfig();
      $calendar                = new Calendar();
      $user                    = new User();
      $profile_User = new Profile_User();

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

      // TODO: only contacts in allowed entities ...
      // Prepare individual contacts
      $a_contacts_entities = array();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
         AND `users_id`>0");
      foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
            $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
      }
      // Prepare groups contacts
      $group = new Group();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
         AND `groups_id`>0");
      foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
            $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
            $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $queryg = "SELECT * FROM `glpi_groups_users`
            WHERE `groups_id`='".$data['groups_id']."'";
         $resultg = $DB->query($queryg);
         while ($datag=$DB->fetch_array($resultg)) {
            if (isset($a_contacts_entities[$data['items_id']][$datag['users_id']])) {
               $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
            }
            $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
      }



      $a_entities_allowed = $pmEntity->getEntitiesByTag($tag);
      // Toolbox::logInFile("pm-shinken", " Allowed entities:\n");
      $a_entities_list = array();
      foreach ($a_entities_allowed as $entity) {
         $a_entities_list = getSonsOf("glpi_entities", $entity);
      }
      $where = '';
      if (! isset($a_entities_allowed['-1'])) {
         $where = getEntitiesRestrictRequest("WHERE", "glpi_plugin_monitoring_services", '', $a_entities_list);
      }

      // --------------------------------------------------
      // "Normal" services ....
      $query = "SELECT * FROM `glpi_plugin_monitoring_services` $where";
      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Services: $query\n"
      );
      $result = $DB->query($query);
      while ($data=$DB->fetch_array($result)) {
         // Toolbox::logInFile("pm-shinken", " - fetch service ".$data['id']."\n");

         // if (isset($a_entities_allowed['-1'])
                 // OR isset($a_entities_allowed[$item->fields['entities_id']])) {
            $notadd = 0;
            $notadddescription = '';
            $a_component = current($pmComponent->find("`id`='".$data['plugin_monitoring_components_id']."'", "", 1));
            if (empty($a_component)) {
               continue;
            }
            $a_hostname = array();
            $a_hostname_type = array();
            $a_hostname_id = array();
            $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`
               WHERE `id` = '".$data['plugin_monitoring_componentscatalogs_hosts_id']."'
               LIMIT 1";
            $resulth = $DB->query($queryh);
            $hostname = '';
            $plugin_monitoring_componentscatalogs_id = 0;
            while ($datah=$DB->fetch_array($resulth)) {
               $itemtype = $datah['itemtype'];
               $item = new $itemtype();
               if ($item->getFromDB($datah['items_id'])) {
                  // if (isset($a_entities_allowed['-1'])
                          // OR isset($a_entities_allowed[$item->fields['entities_id']])) {

                     // Fix if hostname is not defined ...
                     if (! empty($item->fields['name'])) {
                        $a_hostname[] = preg_replace("/[^A-Za-z0-9\-_]/","",$item->fields['name']);
                        $a_hostname_type[] = $datah['itemtype'];
                        $a_hostname_id[] = $datah['items_id'];
                        $hostname = $item->fields['name'];
                        $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_id'];
                     }
                  // }
               }
            }
            if (count($a_hostname) > 0) {
               if (isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                  $a_services[$i]['use'] = $_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']];
               }
               $a_services[$i]['host_name'] = implode(",", array_unique($a_hostname));
               $a_services[$i]['_HOSTITEMSID'] = implode(",", array_unique($a_hostname_id));
               $a_services[$i]['_HOSTITEMTYPE'] = implode(",", array_unique($a_hostname_type));

               // Define display_name / service_description
               $a_services[$i]['service_description'] = (! empty($a_component['description'])) ? $a_component['description'] : preg_replace("/[^A-Za-z0-9\-_]/","",$a_component['name']);
               // In case have multiple networkt port, may have description different, else be dropped by shinken
               if ($data['networkports_id'] > 0) {
                  $networkPort->getFromDB($data['networkports_id']);
                  $a_services[$i]['service_description'] .= '-'.preg_replace("/[^A-Za-z0-9\-_]/", "", $networkPort->fields['name']);
               }
               $a_services[$i]['display_name'] = $a_component['name'];
               // $a_services[$i]['_ENTITIESID'] = $item->fields['entities_id'];
               // $a_services[$i]['_ITEMSID'] = $data['id'];
               // $a_services[$i]['_ITEMTYPE'] = 'Service';
               PluginMonitoringToolbox::logIfExtradebug(
                  'pm-shinken',
                  " - add service ".$a_services[$i]['service_description']." on ".$a_services[$i]['host_name']."\n"
               );

               if (isset(self::$shinkenParameters['glpi']['entityId'])) {
                  $a_services[$i][self::$shinkenParameters['glpi']['entityId']] =
                     $item->fields['entities_id'];
               }
               if (isset(self::$shinkenParameters['glpi']['itemType'])) {
                  $a_services[$i][self::$shinkenParameters['glpi']['itemType']] =
                     'Service';
               }
               if (isset(self::$shinkenParameters['glpi']['itemId'])) {
                  $a_services[$i][self::$shinkenParameters['glpi']['itemId']] =
                     $data['id'];
               }

               // Manage freshness
               if ($a_component['freshness_count'] == 0) {
                  $a_services[$i]['check_freshness'] = '0';
                  $a_services[$i]['freshness_threshold'] = '3600';
               } else {
                  $multiple = 1;
                  if ($a_component['freshness_type'] == 'seconds') {
                     $multiple = 1;
                  } else if ($a_component['freshness_type'] == 'minutes') {
                     $multiple = 60;
                  } else if ($a_component['freshness_type'] == 'hours') {
                     $multiple = 3600;
                  } else if ($a_component['freshness_type'] == 'days') {
                     $multiple = 86400;
                  }
                  $a_services[$i]['check_freshness'] = '1';
                  $a_services[$i]['freshness_threshold'] = (string)($a_component['freshness_count'] * $multiple);
               }

               $pMonitoringCommand->getFromDB($a_component['plugin_monitoring_commands_id']);
               // Manage arguments
               $array = array();
               preg_match_all("/\\$(ARG\d+)\\$/", $pMonitoringCommand->fields['command_line'], $array);
               sort($array[0]);
               $a_arguments = importArrayFromDB($a_component['arguments']);
               $a_argumentscustom = importArrayFromDB($data['arguments']);
               foreach ($a_argumentscustom as $key=>$value) {
                  $a_arguments[$key] = $value;
               }
               foreach ($a_arguments as $key=>$value) {
                  $a_arguments[$key] = str_replace('!', '\!', html_entity_decode($value));
               }
               $args = '';
               foreach ($array[0] as $arg) {
                  if ($arg != '$PLUGINSDIR$'
                          AND $arg != '$NAGIOSPLUGINSDIR$'
                          AND $arg != '$HOSTADDRESS$'
                          AND $arg != '$MYSQLUSER$'
                          AND $arg != '$MYSQLPASSWORD$') {
                     $arg = str_replace('$', '', $arg);
                     if (!isset($a_arguments[$arg])) {
                        $args .= '!';
                     } else {
                        if (strstr($a_arguments[$arg], "[[HOSTNAME]]")) {
                           $a_arguments[$arg] = str_replace("[[HOSTNAME]]", $hostname, $a_arguments[$arg]);
                        } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTDESCR]]")){
                           if (class_exists("PluginFusioninventoryNetworkPort")) {
                              $pfNetworkPort = new PluginFusioninventoryNetworkPort();
                              $pfNetworkPort->loadNetworkport($data['networkports_id']);
                              $descr = $pfNetworkPort->getValue("ifdescr");
                              $a_arguments[$arg] = str_replace("[[NETWORKPORTDESCR]]", $descr, $a_arguments[$arg]);
                           }
                        } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNUM]]")){
                           $networkPort = new NetworkPort();
                           $networkPort->getFromDB($data['networkports_id']);
                           $logicalnum = $pfNetworkPort->fields['logical_number'];
                           $a_arguments[$arg] = str_replace("[[NETWORKPORTNUM]]", $logicalnum, $a_arguments[$arg]);
                        } elseif (strstr($a_arguments[$arg], "[[NETWORKPORTNAME]]")){
                           if (isset($data['networkports_id'])
                                   && $data['networkports_id'] > 0) {
                              $networkPort = new NetworkPort();
                              $networkPort->getFromDB($data['networkports_id']);
                              $portname = $pfNetworkPort->fields['name'];
                              $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $portname, $a_arguments[$arg]);
                           } else if ($a_services[$i]['_HOSTITEMTYPE'] == 'Computer') {
                              // Get networkportname of networkcard defined
                              $pmHostaddress = new PluginMonitoringHostaddress();
                              $a_hostaddresses = $pmHostaddress->find("`itemtype`='Computer'"
                                      . " AND  `items_id`='".$a_services[$i]['_HOSTITEMSID']."'", '', 1);
                              if (count($a_hostaddresses) == 1) {
                                 $a_hostaddress = current($a_hostaddresses);
                                 if ($a_hostaddress['networkports_id'] > 0) {
                                    $networkPort = new NetworkPort();
                                    $networkPort->getFromDB($a_hostaddress['networkports_id']);
                                    $a_arguments[$arg] = str_replace("[[NETWORKPORTNAME]]", $networkPort->fields['name'], $a_arguments[$arg]);
                                 }
                              }
                           }
                        } else if (strstr($a_arguments[$arg], "[")) {
                           $a_arguments[$arg] = PluginMonitoringService::convertArgument($data['id'], $a_arguments[$arg]);
                        }
                        if ($a_arguments == '') {
                           $notadd = 1;
                           if ($notadddescription != '') {
                              $notadddescription .= ", ";
                           }
                           $notadddescription .= "Argument ".$a_arguments[$arg]." do not have value";
                        }
                        $args .= '!'.$a_arguments[$arg];
                        if ($a_arguments[$arg] == ''
                                AND $a_component['alias_command'] != '') {
                           $args .= $a_component['alias_command'];
                        }
                     }
                  }
               }
               // End manage arguments
               if ($a_component['remotesystem'] == 'nrpe') {
                  if ($a_component['alias_command'] != '') {
                     $alias_command = $a_component['alias_command'];
                     if (strstr($alias_command, '[[IP]]')) {
                        $split = explode('-', current($a_hostname));
                        $ip = PluginMonitoringHostaddress::getIp($split[1], $split[0], '');
                        $alias_command = str_replace("[[IP]]", $ip, $alias_command);
                     }
                     $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . "check_nrpe!".$alias_command;
                  } else {
                     $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . "check_nrpe!".$pMonitoringCommand->fields['command_name'];
                  }
               } else {
                  $a_services[$i]['check_command'] = PluginMonitoringCommand::$command_prefix . $pMonitoringCommand->fields['command_name'].$args;
               }

               // * Manage event handler
               if ($a_component['plugin_monitoring_eventhandlers_id'] > 0) {
                  if ($pmEventhandler->getFromDB($a_component['plugin_monitoring_eventhandlers_id'])) {
                     $a_services[$i]['event_handler'] = $pmEventhandler->fields['command_name'];
                  }
               }

               if (! empty(self::$shinkenParameters['shinken']['services']['process_perf_data'])) $a_services[$i]['process_perf_data'] = self::$shinkenParameters['shinken']['services']['process_perf_data'];

               if (! empty(self::$shinkenParameters['shinken']['services']['notes'])) $a_services[$i]['notes'] = self::$shinkenParameters['shinken']['services']['notes'];
               if (! empty(self::$shinkenParameters['shinken']['services']['notes_url'])) $a_services[$i]['notes_url'] = self::$shinkenParameters['shinken']['services']['notes_url'];
               if (! empty(self::$shinkenParameters['shinken']['services']['action_url'])) $a_services[$i]['action_url'] = self::$shinkenParameters['shinken']['services']['action_url'];
               if (! empty(self::$shinkenParameters['shinken']['services']['icon_image'])) $a_services[$i]['icon_image'] = self::$shinkenParameters['shinken']['services']['icon_image'];
               if (! empty(self::$shinkenParameters['shinken']['services']['icon_image_alt'])) $a_services[$i]['icon_image_alt'] = self::$shinkenParameters['shinken']['services']['icon_image_alt'];

               // * Contacts
               $a_contacts = array();
               $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'
                  AND `items_id`='".$plugin_monitoring_componentscatalogs_id."'");
               foreach ($a_list_contact as $data_contact) {
                  if ($data_contact['users_id'] > 0) {
                     if (isset($a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$data_contact['users_id']])) {
                           $user->getFromDB($data_contact['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  } else if ($data_contact['groups_id'] > 0) {
                     $queryg = "SELECT * FROM `glpi_groups_users`
                        WHERE `groups_id`='".$data_contact['groups_id']."'";
                     $resultg = $DB->query($queryg);
                     while ($datag=$DB->fetch_array($resultg)) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$plugin_monitoring_componentscatalogs_id][$datag['users_id']])) {
                           $user->getFromDB($datag['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  }
               }

               $a_contacts_unique = array_unique($a_contacts);
               $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);

               // ** If shinken not use templates or template not defined :
               if (!isset($_SESSION['plugin_monitoring']['servicetemplates'][$a_component['id']])) {
                  $pMonitoringCheck->getFromDB($a_component['plugin_monitoring_checks_id']);
                  $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                  $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                  $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                  if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
                  $a_services[$i]['notification_interval'] = '30';
                  $a_services[$i]['notification_period'] = "24x7";
                  $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                  $a_services[$i]['process_perf_data'] = '1';
                  $a_services[$i]['active_checks_enabled'] = '1';
                  $a_services[$i]['passive_checks_enabled'] = '1';
                  $a_services[$i]['parallelize_check'] = '1';
                  $a_services[$i]['obsess_over_service'] = '1';
                  $a_services[$i]['check_freshness'] = '1';
                  $a_services[$i]['freshness_threshold'] = '3600';
                  $a_services[$i]['notifications_enabled'] = '1';

                  if (isset($a_services[$i]['event_handler'])) {
                     $a_services[$i]['event_handler_enabled'] = '1';
                  } else {
                     $a_services[$i]['event_handler_enabled'] = '0';
                     // $a_services[$i]['event_handler_enabled'] = '';
                  }
                  $a_services[$i]['flap_detection_enabled'] = '1';
                  $a_services[$i]['failure_prediction_enabled'] = '1';
                  $a_services[$i]['retain_status_information'] = '1';
                  $a_services[$i]['retain_nonstatus_information'] = '1';
                  $a_services[$i]['is_volatile'] = '0';
                  // $a_services[$i]['_httpstink'] = 'NO';
               } else {
                  // Notification options
                  $a_services[$i]['notification_interval'] = '30';
                  $pmComponentscatalog->getFromDB($plugin_monitoring_componentscatalogs_id);
                  if ($pmComponentscatalog->fields['notification_interval'] != '30') {
                     $a_services[$i]['notification_interval'] = $pmComponentscatalog->fields['notification_interval'];
                  }
                  $a_services[$i]['notification_period'] = '24x7';
                  $a_services[$i]['check_period'] = '24x7';
                  if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
               }

               // WebUI user interface ...
               if (isset(self::$shinkenParameters['webui']['serviceIcons']['name'])) {
                  $a_services[$i][self::$shinkenParameters['webui']['serviceIcons']['name']] =
                     self::$shinkenParameters['webui']['serviceIcons']['value'];
               }

               if ($notadd == '1') {
                  unset($a_services[$i]);
                  $input = array();
                  $input['id'] = $data['id'];
                  $input['event'] = $notadddescription;
                  $input['state'] = "CRITICAL";
                  $input['state_type'] = "HARD";
                  $pmService->update($input);
               } else {
                  $i++;
               }
            }
         // }
      }

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

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

      // --------------------------------------------------
      // Business rules services ...
      $pmService = new PluginMonitoringService();
      $pmServicescatalog = new PluginMonitoringServicescatalog();
      $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup();
      $pmBusinessrule = new PluginMonitoringBusinessrule();
      $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
      $pmBusinessrule_component = new PluginMonitoringBusinessrule_component();
      // Prepare individual contacts
      $a_contacts_entities = array();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
         AND `users_id`>0");
      foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
            $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
      }
      // Prepare groups contacts
      $group = new Group();
      $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
         AND `groups_id`>0");
      foreach ($a_list_contact as $data) {
         $group->getFromDB($data['groups_id']);
         if ($group->fields['is_recursive'] == 1) {
            $contactentities = getSonsOf('glpi_entities', $group->fields['entities_id']);
         } else {
            $contactentities = array($group->fields['entities_id'] => $group->fields['entities_id']);
         }
         $queryg = "SELECT * FROM `glpi_groups_users`
            WHERE `groups_id`='".$data['groups_id']."'";
         $resultg = $DB->query($queryg);
         while ($datag=$DB->fetch_array($resultg)) {
            if (isset($a_contacts_entities[$data['items_id']][$datag['users_id']])) {
               $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$datag['users_id']]);
            }
            $a_contacts_entities[$data['items_id']][$datag['users_id']] = $contactentities;
         }
      }

      // Services catalogs
      $a_listBA = $pmServicescatalog->find("`is_generic`='0'");
      foreach ($a_listBA as $dataBA) {

         if (isset($a_entities_allowed['-1'])
                 OR isset($a_entities_allowed[$dataBA['entities_id']])) {

            $a_grouplist = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$dataBA['id']."'");
            $a_group = array();
            foreach ($a_grouplist as $gdata) {

               $pmBusinessrule_component->replayDynamicServices($gdata['id']);
               $a_listBR = $pmBusinessrule->find(
                       "`plugin_monitoring_businessrulegroups_id`='".$gdata['id']."'");
               foreach ($a_listBR as $dataBR) {
                  if ($pmService->getFromDB($dataBR['plugin_monitoring_services_id'])) {
                     if ($pmService->getHostName() != '') {
                        $hostname = preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getHostName());

                        if ($gdata['operator'] == 'and'
                                OR $gdata['operator'] == 'or'
                                OR strstr($gdata['operator'], ' of:')) {

                           $operator = '|';
                           if ($gdata['operator'] == 'and') {
                              $operator = '&';
                           }
                           if (!isset($a_group[$gdata['id']])) {
                              $a_group[$gdata['id']] = '';
                              if (strstr($gdata['operator'], ' of:')) {
                                 $a_group[$gdata['id']] = $gdata['operator'];
                              }
                              $a_group[$gdata['id']] .= $hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           } else {
                              $a_group[$gdata['id']] .= $operator.$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           }
                        } else {
                           $a_group[$gdata['id']] = $gdata['operator']." ".$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$item->getName());
                        }
                     }
                  }
                  PluginMonitoringToolbox::logIfExtradebug(
                     'pm-shinken',
                     "   - SC group : ".$a_group[$gdata['id']]."\n"
                  );
               }
            }
            if (count($a_group) > 0) {
               $pMonitoringCheck->getFromDB($dataBA['plugin_monitoring_checks_id']);
               $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
               $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
               $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
               if ($calendar->getFromDB($dataBA['calendars_id'])) {
                  $a_services[$i]['check_period'] = $calendar->fields['name'];
               }
               $a_services[$i]['host_name'] = self::$shinkenParameters['shinken']['fake_hosts']['name_prefix'] . self::$shinkenParameters['shinken']['fake_hosts']['bp_host'];
               $a_services[$i]['business_impact'] = $dataBA['business_priority'];
               $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9\-_]/","",$dataBA['name']);
               $a_services[$i]['_ENTITIESID'] = $dataBA['id'];
               $a_services[$i]['_ITEMSID'] = $dataBA['id'];
               $a_services[$i]['_ITEMTYPE'] = 'ServiceCatalog';
               $command = "bp_rule!";

               foreach ($a_group as $key=>$value) {
                  if (!strstr($value, "&")
                          AND !strstr($value, "|")) {
                     $a_group[$key] = trim($value);
                  } else {
                     $a_group[$key] = "(".trim($value).")";
                  }
               }
               $a_services[$i]['check_command'] = $command.implode("&", $a_group);
               if ($dataBA['notification_interval'] != '30') {
                  $a_services[$i]['notification_interval'] = $dataBA['notification_interval'];
               } else {
                  $a_services[$i]['notification_interval'] = '30';
               }
               $a_services[$i]['notification_period'] = "24x7";
               $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
               $a_services[$i]['active_checks_enabled'] = '1';
               $a_services[$i]['process_perf_data'] = '1';
               $a_services[$i]['active_checks_enabled'] = '1';
               $a_services[$i]['passive_checks_enabled'] = '1';
               $a_services[$i]['parallelize_check'] = '1';
               $a_services[$i]['obsess_over_service'] = '1';
               $a_services[$i]['check_freshness'] = '1';
               $a_services[$i]['freshness_threshold'] = '3600';
               $a_services[$i]['notifications_enabled'] = '1';
               $a_services[$i]['event_handler_enabled'] = '0';
               //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
               $a_services[$i]['flap_detection_enabled'] = '1';
               $a_services[$i]['failure_prediction_enabled'] = '1';
               $a_services[$i]['retain_status_information'] = '1';
               $a_services[$i]['retain_nonstatus_information'] = '1';
               $a_services[$i]['is_volatile'] = '0';
               // $a_services[$i]['_httpstink'] = 'NO';

               // * Contacts
               $a_contacts = array();
               $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
                  AND `items_id`='".$dataBA['id']."'");
               foreach ($a_list_contact as $data_contact) {
                  if ($data_contact['users_id'] > 0) {
                     if (isset($a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                           $user->getFromDB($data_contact['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  } else if ($data_contact['groups_id'] > 0) {
                     $queryg = "SELECT * FROM `glpi_groups_users`
                        WHERE `groups_id`='".$data_contact['groups_id']."'";
                     $resultg = $DB->query($queryg);
                     while ($datag=$DB->fetch_array($resultg)) {
                        if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                           $user->getFromDB($datag['users_id']);
                           $a_contacts[] = $user->fields['name'];
                        }
                     }
                  }
               }

               $a_contacts_unique = array_unique($a_contacts);
               $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
               $i++;
            }
         }
      }

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "End generateServicesCfg business rules\n"
      );

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "Starting generateServicesCfg business rules templates ...\n"
      );

      // Services catalogs templates
      // TODO : correctly test and improve it !
      $a_listBA = $pmServicescatalog->find("`is_generic`='1'");
      foreach ($a_listBA as $dataBA) {
         PluginMonitoringToolbox::logIfExtradebug(
            'pm-shinken',
            "   - SC : ".$dataBA['id']."\n"
         );

         if (isset($a_entities_allowed['-1'])
                 OR isset($a_entities_allowed[$dataBA['entities_id']])) {

            $pmServicescatalog->getFromDB($dataBA['id']);

            $a_entitiesServices = $pmServicescatalog->getGenericServicesEntities();
            foreach ($a_entitiesServices as $idEntity=>$a_entityServices) {
               // New entity ... so new business rule !
               PluginMonitoringToolbox::logIfExtradebug(
                  'pm-shinken',
                  "   - SC templated services for an entity : ".$idEntity."\n"
               );

               $pmDerivatedSC = new PluginMonitoringServicescatalog();
               $a_derivatedSC = $pmDerivatedSC->find("`entities_id`='$idEntity' AND `name` LIKE '".$dataBA['name']."%'");
               foreach ($a_derivatedSC as $a_derivated) {
                  PluginMonitoringToolbox::logIfExtradebug(
                     'pm-shinken',
                     "   - a_derivated : ".$a_derivated['name']."\n"
                  );
                  $a_derivatedSC = $a_derivated;
               }

               $a_group = array();
               foreach ($a_entityServices as $services) {
                  if ($pmService->getFromDB($services['serviceId'])) {
                     // Toolbox::logInFile("pm-shinken", "   - SC templated service entity : ".$services['entityId'].", service :  ".$pmService->getName(true)." on ".$pmService->getHostName()."\n");
                     if ($pmService->getHostName() != '') {
                        $hostname = preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getHostName());

                        $serviceFakeId = $services['entityId'];

                        $pmBusinessrulegroup->getFromDB($services['BRgroupId']);
                        $BRoperator = $pmBusinessrulegroup->getField('operator');
                        if ($BRoperator == 'and'
                                OR $BRoperator == 'or'
                                OR strstr($BRoperator, ' of:')) {

                           $operator = '|';
                           if ($BRoperator == 'and') {
                              $operator = '&';
                           }
                           if (!isset($a_group[$serviceFakeId])) {
                              $a_group[$serviceFakeId] = '';
                              if (strstr($BRoperator, ' of:')) {
                                 $a_group[$serviceFakeId] = $BRoperator;
                              }
                              $a_group[$serviceFakeId] .= $hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           } else {
                              $a_group[$serviceFakeId] .= $operator.$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getName(array('shinken'=>true)));
                           }
                        } else {
                           $a_group[$serviceFakeId] = $BRoperator." ".$hostname.",".preg_replace("/[^A-Za-z0-9\-_]/","",$pmService->getHostName());
                        }
                        // Toolbox::logInFile("pm-shinken", "   - SCT group : ".$a_group[$serviceFakeId]."\n");
                     }
                  }
               }
               if (count($a_group) > 0) {
                  $pMonitoringCheck->getFromDB($a_derivatedSC['plugin_monitoring_checks_id']);
                  $a_services[$i]['check_interval'] = $pMonitoringCheck->fields['check_interval'];
                  $a_services[$i]['retry_interval'] = $pMonitoringCheck->fields['retry_interval'];
                  $a_services[$i]['max_check_attempts'] = $pMonitoringCheck->fields['max_check_attempts'];
                  if ($calendar->getFromDB($a_derivatedSC['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'];
                  }
                  $a_services[$i]['host_name'] = preg_replace("/[^A-Za-z0-9\-_]/","",$a_derivatedSC['name']);
                  $a_services[$i]['host_name'] = self::$shinkenParameters['shinken']['fake_hosts']['name_prefix'] . self::$shinkenParameters['shinken']['fake_hosts']['bp_host'];
                  $a_services[$i]['business_impact'] = $a_derivatedSC['business_priority'];
                  $a_services[$i]['service_description'] = preg_replace("/[^A-Za-z0-9\-_]/","",$a_derivatedSC['name']);
                  $a_services[$i]['_ENTITIESID'] = $a_derivatedSC['entities_id'];
                  $a_services[$i]['_ITEMSID'] = $a_derivatedSC['id'];
                  $a_services[$i]['_ITEMTYPE'] = 'ServiceCatalog';
                  $command = "bp_rule!";

                  foreach ($a_group as $key=>$value) {
                     if (!strstr($value, "&")
                             AND !strstr($value, "|")) {
                        $a_group[$key] = trim($value);
                     } else {
                        $a_group[$key] = "(".trim($value).")";
                     }
                  }
                  $a_services[$i]['check_command'] = $command.implode("&", $a_group);
                  if ($a_derivatedSC['notification_interval'] != '30') {
                     $a_services[$i]['notification_interval'] = $a_derivatedSC['notification_interval'];
                  } else {
                     $a_services[$i]['notification_interval'] = '30';
                  }
                  $a_services[$i]['notification_period'] = "24x7";
                  $a_services[$i]['notification_options'] = 'w,u,c,r,f,s';
                  $a_services[$i]['active_checks_enabled'] = '1';
                  $a_services[$i]['process_perf_data'] = '1';
                  $a_services[$i]['active_checks_enabled'] = '1';
                  $a_services[$i]['passive_checks_enabled'] = '1';
                  $a_services[$i]['parallelize_check'] = '1';
                  $a_services[$i]['obsess_over_service'] = '1';
                  $a_services[$i]['check_freshness'] = '1';
                  $a_services[$i]['freshness_threshold'] = '3600';
                  $a_services[$i]['notifications_enabled'] = '1';
                  $a_services[$i]['event_handler_enabled'] = '0';
                  //$a_services[$i]['event_handler'] = 'super_event_kill_everyone!DIE';
                  $a_services[$i]['flap_detection_enabled'] = '1';
                  $a_services[$i]['failure_prediction_enabled'] = '1';
                  $a_services[$i]['retain_status_information'] = '1';
                  $a_services[$i]['retain_nonstatus_information'] = '1';
                  $a_services[$i]['is_volatile'] = '0';
                  // $a_services[$i]['_httpstink'] = 'NO';

                  // * Contacts
                  $a_contacts = array();
                  $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'
                     AND `items_id`='".$dataBA['id']."'");
                  foreach ($a_list_contact as $data_contact) {
                     if ($data_contact['users_id'] > 0) {
                        if (isset($a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                           if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$data_contact['users_id']])) {
                              $user->getFromDB($data_contact['users_id']);
                              $a_contacts[] = $user->fields['name'];
                           }
                        }
                     } else if ($data_contact['groups_id'] > 0) {
                        $queryg = "SELECT * FROM `glpi_groups_users`
                           WHERE `groups_id`='".$data_contact['groups_id']."'";
                        $resultg = $DB->query($queryg);
                        while ($datag=$DB->fetch_array($resultg)) {
                           if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                              $user->getFromDB($datag['users_id']);
                              $a_contacts[] = $user->fields['name'];
                           }
                        }
                     }
                  }

                  $a_contacts_unique = array_unique($a_contacts);
                  $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
                  $i++;
               }
            }
         }
      }

      PluginMonitoringToolbox::logIfExtradebug(
         'pm-shinken',
         "End generateServicesCfg business rules templates\n"
      );

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

         foreach ($a_services as $data) {
            $config .= $this->writeFile("service", $data);
         }
         return array('services.cfg', $config);

      } else {
         return $a_services;
      }
   }
コード例 #7
0
     $a_agentList = importArrayFromDB($agentmodule->fields['exceptions']);
     foreach ($a_agentList as $key => $value) {
         if ($value == $_POST['agent_to_delete'][0]) {
             unset($a_agentList[$key]);
         }
     }
     $input = array();
     $input['exceptions'] = exportArrayToDB($a_agentList);
     $input['id'] = $_POST['id'];
     $agentmodule->update($input);
     Html::back();
 } else {
     if (isset($_POST["updateexceptions"])) {
         $a_modules = $agentmodule->find();
         foreach ($a_modules as $data) {
             $a_agentList = importArrayFromDB($data['exceptions']);
             $agentModule = 0;
             if (isset($_POST['activation-' . $data['modulename']])) {
                 $agentModule = 1;
             }
             $agentModuleBase = 0;
             if (in_array($_POST['id'], $a_agentList)) {
                 $agentModuleBase = 1;
             }
             if ($data['is_active'] == 0) {
                 if ($agentModule == 1 and $agentModuleBase == 1) {
                     // OK
                 } else {
                     if ($agentModule == 1 and $agentModuleBase == 0) {
                         $a_agentList[] = $_POST['id'];
                     } else {
コード例 #8
0
ファイル: rule.class.php プロジェクト: Etiennef/configmanager
 /**
  * Construit le code HTML pour un champ de saisie via dropdown
  *
  * @param integer/string $id
  *           id de la règle dont fait partie le dropdown (integer ou tag de nouvel id)
  * @param string $param
  *           nom du paramètre à afficher (champ name du select)
  * @param array $desc
  *           description du paramètre à afficher
  * @param string $values
  *           valeur(s) à pré-sélectionner (sous forme de tableau json si la sélection multiple est possible)
  * @param boolean $can_write
  *           vrai ssi on doit afficher un menu sélectionnable, sinon on affiche juste le texte.
  * @return string code html à afficher
  */
 private static final function makeDropdown($id, $param, $desc, $values, $can_write)
 {
     $options = array('multiple' => isset($desc['multiple']) && $desc['multiple'], 'width' => isset($desc['width']) ? $desc['width'] : '100%');
     $result = '';
     $options['display'] = false;
     if ($options['multiple']) {
         $options['values'] = importArrayFromDB($values);
     } else {
         $options['values'] = array($values);
     }
     if ($can_write) {
         $result .= Dropdown::showFromArray("rules[{$id}][{$param}]", $desc['values'], $options);
     } else {
         foreach ($options['values'] as $value) {
             if (isset($desc['values'][$value])) {
                 // test certes contre-intuitif, mais nécessaire pour gérer le fait que la liste de choix puisse être variable selon les droits de l'utilisateur.
                 $result .= $desc['values'][$value] . '</br>';
             }
         }
     }
     return $result;
 }
コード例 #9
0
ファイル: update_0831_084.php プロジェクト: jose-martins/glpi
/**
 * Update from 0.83.1 to 0.84
 *
 * @return bool for success (will die for most error)
**/
function update0831to084()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.84'));
    $migration->setVersion('0.84');
    // Add the internet field and copy rights from networking
    $migration->addField('glpi_profiles', 'internet', 'char', array('after' => 'networking', 'update' => '`networking`'));
    $backup_tables = false;
    $newtables = array('glpi_contractcosts', 'glpi_entities_rssfeeds', 'glpi_groups_rssfeeds', 'glpi_problems_suppliers', 'glpi_profiles_rssfeeds', 'glpi_rssfeeds_users', 'glpi_rssfeeds', 'glpi_suppliers_tickets', 'glpi_ticketcosts');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    updateNetworkFramework($ADDTODISPLAYPREF);
    $migration->addField('glpi_mailcollectors', 'accepted', 'string');
    $migration->addField('glpi_mailcollectors', 'refused', 'string');
    $migration->addField('glpi_mailcollectors', 'use_kerberos', 'bool', array('value' => 0));
    $migration->addField("glpi_mailcollectors", 'errors', "integer");
    $migration->addField("glpi_mailcollectors", 'use_mail_date', "bool", array('value' => 0));
    // Password security
    $migration->addField('glpi_configs', 'use_password_security', 'bool');
    $migration->addField('glpi_configs', 'password_min_length', 'integer', array('value' => 8));
    $migration->addField('glpi_configs', 'password_need_number', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'password_need_letter', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'password_need_caps', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'password_need_symbol', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'use_check_pref', 'bool');
    // Ajax buffer time
    $migration->addField('glpi_configs', 'ajax_buffertime_load', 'integer', array('value' => 0, 'after' => 'ajax_min_textsearch_load'));
    // Clean display prefs
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 160\n             WHERE `itemtype` = 'Software'\n                   AND `num` = 7";
    $DB->query($query);
    // Update bookmarks from States to AllAssets
    foreach ($DB->request("glpi_bookmarks", "`itemtype` = 'States'") as $data) {
        $query = str_replace('itemtype=States', 'itemtype=AllAssets', $data['query']);
        $query = "UPDATE `glpi_bookmarks`\n                SET query = '" . addslashes($query) . "'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->query($query);
    }
    $query = "UPDATE `glpi_bookmarks`\n             SET `itemtype` = 'AllAssets', `path` = 'front/allassets.php'\n             WHERE `itemtype` = 'States'";
    $DB->query($query);
    $query = "UPDATE `glpi_displaypreferences`\n             SET `itemtype` = 'AllAssets'\n             WHERE `itemtype` = 'States'";
    $DB->query($query);
    if (TableExists('glpi_networkportmigrations')) {
        $migration->displayWarning("You should have a look at the \"migration cleaner\" tool !", true);
        $migration->displayWarning("With it, you should re-create the networks topologies and the links between the networks and the addresses", true);
    }
    $lang_to_update = array('ca_CA' => 'ca_ES', 'dk_DK' => 'da_DK', 'ee_ET' => 'et_EE', 'el_EL' => 'el_GR', 'he_HE' => 'he_IL', 'no_NB' => 'nb_NO', 'no_NN' => 'nn_NO', 'ua_UA' => 'uk_UA');
    foreach ($lang_to_update as $old => $new) {
        $query = "UPDATE `glpi_configs`\n               SET `language` = '{$new}'\n               WHERE `language` = '{$old}';";
        $DB->queryOrDie($query, "0.84 language in config {$old} to {$new}");
        $query = "UPDATE `glpi_users`\n               SET `language` = '{$new}'\n               WHERE `language` = '{$old}';";
        $DB->queryOrDie($query, "0.84 language in users {$old} to {$new}");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and problems status'));
    $status = array('new' => CommonITILObject::INCOMING, 'assign' => CommonITILObject::ASSIGNED, 'plan' => CommonITILObject::PLANNED, 'waiting' => CommonITILObject::WAITING, 'solved' => CommonITILObject::SOLVED, 'closed' => CommonITILObject::CLOSED, 'accepted' => CommonITILObject::ACCEPTED, 'observe' => CommonITILObject::OBSERVED, 'evaluation' => CommonITILObject::EVALUATION, 'approbation' => CommonITILObject::APPROVAL, 'test' => CommonITILObject::TEST, 'qualification' => CommonITILObject::QUALIFICATION);
    foreach (array('glpi_tickets', 'glpi_problems') as $table) {
        // Migrate datas
        foreach ($status as $old => $new) {
            $query = "UPDATE `{$table}`\n                   SET `status` = '{$new}'\n                   WHERE `status` = '{$old}'";
            $DB->queryOrDie($query, "0.84 status in {$table} {$old} to {$new}");
        }
        $migration->changeField($table, 'status', 'status', 'integer', array('value' => CommonITILObject::INCOMING));
    }
    // Migrate templates
    $query = "SELECT `glpi_notificationtemplatetranslations`.*\n             FROM `glpi_notificationtemplatetranslations`\n             INNER JOIN `glpi_notificationtemplates`\n                  ON (`glpi_notificationtemplates`.`id`\n                        = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n             WHERE `glpi_notificationtemplatetranslations`.`content_text` LIKE '%storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%storestatus=%'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result)) {
            while ($data = $DB->fetch_assoc($result)) {
                $subject = $data['subject'];
                $text = $data['content_text'];
                $html = $data['content_html'];
                foreach ($status as $old => $new) {
                    $subject = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $subject);
                    $text = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $text);
                    $html = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $html);
                    $subject = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $subject);
                    $text = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $text);
                    $html = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $html);
                }
                $query = "UPDATE `glpi_notificationtemplatetranslations`\n                      SET `subject` = '" . addslashes($subject) . "',\n                          `content_text` = '" . addslashes($text) . "',\n                          `content_html` = '" . addslashes($html) . "'\n                      WHERE `id` = " . $data['id'] . "";
                $DB->queryOrDie($query, "0.84 fix tags usage for storestatus");
            }
        }
    }
    // Update Rules
    $changes = array();
    $changes['RuleTicket'] = 'status';
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    foreach ($changes as $ruletype => $field) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = '" . $ruletype . "'\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($status as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `value` = '{$new}'\n                         WHERE `field` = '{$field}'\n                               AND `value` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.84 update datas for rules actions");
                }
            }
        }
    }
    // Update glpi_profiles : ticket_status
    foreach ($DB->request('glpi_profiles') as $data) {
        $fields_to_decode = array('ticket_status', 'problem_status');
        foreach ($fields_to_decode as $field) {
            $tab = importArrayFromDB($data[$field]);
            if (is_array($tab)) {
                $newtab = array();
                foreach ($tab as $key => $values) {
                    foreach ($values as $key2 => $val2) {
                        $newtab[$status[$key]][$status[$key2]] = $val2;
                    }
                }
                $query = "UPDATE `glpi_profiles`\n                       SET `{$field}` = '" . addslashes(exportArrayToDB($newtab)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query, "0.84 migrate {$field} of glpi_profiles");
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Merge entity and entitydatas'));
    if (TableExists('glpi_entitydatas')) {
        $migration->changeField('glpi_entities', 'id', 'id', 'integer');
        $migration->migrationOneTable('glpi_entities');
        // pour que la procedure soit re-entrante
        if (countElementsInTable("glpi_entities", "id=0") < 1) {
            // Create root entity
            $query = "INSERT INTO `glpi_entities`\n                          (`id`, `name`, `completename`, `entities_id`, `level`)\n                   VALUES (0,'" . addslashes(__('Root entity')) . "',\n                           '" . addslashes(__('Root entity')) . "', '-1', '1');";
            $DB->queryOrDie($query, '0.84 insert root entity into glpi_entities');
        }
        //       $newID = $DB->insert_id();
        //       $query = "UPDATE `glpi_entities`
        //                 SET `id` = '0'
        //                 WHERE `id` = '$newID'";
        //       $DB->queryOrDie($query, '0.84 be sure that id of the root entity if 0 in glpi_entities');
        $migration->addField("glpi_entities", 'address', "text");
        $migration->addField("glpi_entities", 'postcode', "string");
        $migration->addField("glpi_entities", 'town', "string");
        $migration->addField("glpi_entities", 'state', "string");
        $migration->addField("glpi_entities", 'country', "string");
        $migration->addField("glpi_entities", 'website', "string");
        $migration->addField("glpi_entities", 'phonenumber', "string");
        $migration->addField("glpi_entities", 'fax', "string");
        $migration->addField("glpi_entities", 'email', "string");
        $migration->addField("glpi_entities", 'admin_email', "string");
        $migration->addField("glpi_entities", 'admin_email_name', "string");
        $migration->addField("glpi_entities", 'admin_reply', "string");
        $migration->addField("glpi_entities", 'admin_reply_name', "string");
        $migration->addField("glpi_entities", 'notification_subject_tag', "string");
        $migration->addField("glpi_entities", 'notepad', "longtext");
        $migration->addField("glpi_entities", 'ldap_dn', "string");
        $migration->addField("glpi_entities", 'tag', "string");
        $migration->addField("glpi_entities", 'authldaps_id', "integer");
        $migration->addField("glpi_entities", 'mail_domain', "string");
        $migration->addField("glpi_entities", 'entity_ldapfilter', "text");
        $migration->addField("glpi_entities", 'mailing_signature', "text");
        $migration->addField("glpi_entities", 'cartridges_alert_repeat', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'consumables_alert_repeat', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_licenses_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_contracts_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_infocoms_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_reservations_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'autoclose_delay', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'notclosed_delay', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'calendars_id', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'auto_assign_mode', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'tickettype', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'max_closedate', "datetime");
        $migration->addField("glpi_entities", 'inquest_config', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'inquest_rate', "integer");
        $migration->addField("glpi_entities", 'inquest_delay', "integer", array('value' => -10));
        $migration->addField("glpi_entities", 'inquest_URL', "string");
        $migration->addField("glpi_entities", 'autofill_warranty_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_use_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_buy_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_delivery_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_order_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'tickettemplates_id', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'entities_id_software', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'default_contract_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'default_infocom_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'default_alarm_threshold', "integer", array('value' => -2));
        $migration->migrationOneTable('glpi_entities');
        $fields = array('address', 'postcode', 'town', 'state', 'country', 'website', 'phonenumber', 'fax', 'email', 'admin_email', 'admin_email_name', 'admin_reply', 'admin_reply_name', 'notification_subject_tag', 'notepad', 'ldap_dn', 'tag', 'authldaps_id', 'mail_domain', 'entity_ldapfilter', 'mailing_signature', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'use_licenses_alert', 'use_contracts_alert', 'use_infocoms_alert', 'use_reservations_alert', 'autoclose_delay', 'notclosed_delay', 'calendars_id', 'auto_assign_mode', 'tickettype', 'max_closedate', 'inquest_config', 'inquest_rate', 'inquest_delay', 'inquest_URL', 'autofill_warranty_date', 'autofill_use_date', 'autofill_buy_date', 'autofill_delivery_date', 'autofill_order_date', 'tickettemplates_id', 'entities_id_software', 'default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold');
        $entity = new Entity();
        foreach ($DB->request('glpi_entitydatas') as $data) {
            if ($entity->getFromDB($data['entities_id'])) {
                $update_fields = array();
                foreach ($fields as $field) {
                    if (is_null($data[$field])) {
                        $update_fields[] = "`{$field}` = NULL";
                    } else {
                        $update_fields[] = "`{$field}` = '" . addslashes($data[$field]) . "'";
                    }
                }
                $query = "UPDATE `glpi_entities`\n                       SET " . implode(',', $update_fields) . "\n                       WHERE `id` = '" . $data['entities_id'] . "'";
                $DB->queryOrDie($query, "0.84 transfer datas from glpi_entitydatas to glpi_entities");
            } else {
                $migration->displayMessage('Entity ID ' . $data['entities_id'] . ' does not exist');
            }
        }
        $migration->dropTable('glpi_entitydatas');
    }
    regenerateTreeCompleteName("glpi_entities");
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'copy entity information to computers_softwareversions'));
    if ($migration->addField("glpi_computers_softwareversions", "entities_id", "integer")) {
        $migration->migrationOneTable('glpi_computers_softwareversions');
        $query3 = "UPDATE `glpi_computers_softwareversions`\n                 LEFT JOIN `glpi_computers`\n                    ON `computers_id`=`glpi_computers`.`id`\n                 SET `glpi_computers_softwareversions`.`entities_id` = `glpi_computers`.`entities_id`";
        $DB->queryOrDie($query3, "0.84 update entities_id in glpi_computers_softwareversions");
        /// create index for search count on tab
        $migration->addKey("glpi_computers_softwareversions", array('entities_id', 'is_template', 'is_deleted'), 'computers_info');
        $migration->addKey("glpi_computers_softwareversions", 'is_template');
        $migration->addKey("glpi_computers_softwareversions", 'is_deleted');
    }
    /// create new index for search
    $migration->addKey("glpi_softwarelicenses", array('softwares_id', 'expire'), 'softwares_id_expire');
    $migration->dropKey("glpi_softwarelicenses", 'softwares_id');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'create validation_answer notification'));
    // Check if notifications already exists
    if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n                              AND `event` = 'validation_answer'") == 0) {
        // No notifications duplicate all
        $query = "SELECT *\n                FROM `glpi_notifications`\n                WHERE `itemtype` = 'Ticket'\n                      AND `event` = 'validation'";
        foreach ($DB->request($query) as $notif) {
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                          `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                          `date_mod`)\n                   VALUES ('" . addslashes($notif['name']) . " Answer',\n                           '" . $notif['entities_id'] . "', 'Ticket',\n                           'validation_answer', '" . $notif['mode'] . "',\n                           '" . $notif['notificationtemplates_id'] . "',\n                           '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                           '" . $notif['is_active'] . "', NOW());";
            $DB->queryOrDie($query, "0.84 insert validation_answer notification");
            $newID = $DB->insert_id();
            $query2 = "SELECT *\n                    FROM `glpi_notificationtargets`\n                    WHERE `notifications_id` = '" . $notif['id'] . "'";
            foreach ($DB->request($query2) as $target) {
                $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')";
                $DB->queryOrDie($query, "0.84 insert targets for validation_answer notification");
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'create contracts notification'));
    $from_to = array('end' => 'periodicity', 'notice' => 'periodicitynotice');
    foreach ($from_to as $from => $to) {
        // Check if notifications already exists
        if (countElementsInTable('glpi_notifications', "`itemtype` = 'Contract' AND `event` = '{$to}'") == 0) {
            // No notifications duplicate all
            $query = "SELECT *\n                   FROM `glpi_notifications`\n                   WHERE `itemtype` = 'Contract'\n                         AND `event` = '{$from}'";
            foreach ($DB->request($query) as $notif) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . addslashes($notif['name']) . " Periodicity',\n                              '" . $notif['entities_id'] . "', 'Contract', '{$to}', '" . $notif['mode'] . "',\n                              '" . $notif['notificationtemplates_id'] . "',\n                              '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                              '" . $notif['is_active'] . "', NOW());";
                $DB->queryOrDie($query, "0.84 insert contract " . $to . " notification");
                $newID = $DB->insert_id();
                $query2 = "SELECT *\n                       FROM `glpi_notificationtargets`\n                       WHERE `notifications_id` = '" . $notif['id'] . "'";
                foreach ($DB->request($query2) as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`notifications_id`, `type`, `items_id`)\n                         VALUES ('" . $newID . "', '" . $target['type'] . "', '" . $target['items_id'] . "')";
                    $DB->queryOrDie($query, "0.84 insert targets for ĉontract " . $to . " notification");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'contract and ticket costs'));
    if (!TableExists('glpi_contractcosts')) {
        $query = "CREATE TABLE `glpi_contractcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `contracts_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `begin_date` date DEFAULT NULL,\n                  `end_date` date DEFAULT NULL,\n                  `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `budgets_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `contracts_id` (`contracts_id`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `end_date` (`end_date`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `budgets_id` (`budgets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_contractcosts");
        $migration->migrationOneTable('glpi_contractcosts');
        foreach ($DB->request('glpi_contracts', "`cost` > 0") as $data) {
            $begin_to_add = "NULL";
            $end_to_add = "NULL";
            if (!is_null($data['begin_date'])) {
                $begin_to_add = "'" . $data['begin_date'] . "'";
                if ($data['duration']) {
                    $end_to_add = "'" . date("Y-m-d", strtotime($data['begin_date'] . "+" . $data['duration'] . " month")) . "'";
                } else {
                    $end_to_add = "'" . $data['begin_date'] . "'";
                }
            }
            $query = "INSERT INTO `glpi_contractcosts`\n                          (`contracts_id`, `name`, `begin_date`, `end_date`,\n                           `cost`,  `entities_id`,\n                           `is_recursive`)\n                   VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n                           '" . $data['cost'] . "', '" . $data['entities_id'] . "',\n                           '" . $data['is_recursive'] . "')";
            $DB->queryOrDie($query, '0.84 move contracts costs');
        }
        $migration->dropField('glpi_contracts', 'cost');
    }
    if (!TableExists('glpi_ticketcosts')) {
        $query = "CREATE TABLE `glpi_ticketcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `begin_date` date DEFAULT NULL,\n                  `end_date` date DEFAULT NULL,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `budgets_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `tickets_id` (`tickets_id`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `end_date` (`end_date`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `budgets_id` (`budgets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_ticketcosts");
        $migration->migrationOneTable('glpi_ticketcosts');
        foreach ($DB->request('glpi_tickets', "`cost_time` > 0\n                            OR `cost_fixed` > 0\n                            OR `cost_material` > 0") as $data) {
            $begin_to_add = "NULL";
            $end_to_add = "NULL";
            if (!is_null($data['date'])) {
                $begin_to_add = "'" . $data['date'] . "'";
                if (!is_null($data['solvedate'])) {
                    $end_to_add = "'" . $data['solvedate'] . "'";
                } else {
                    $end_to_add = "'" . $data['date'] . "'";
                }
            }
            $query = "INSERT INTO `glpi_ticketcosts`\n                          (`tickets_id`, `name`, `begin_date`, `end_date`,\n                           `cost_time`,`cost_fixed`,\n                           `cost_material`, `entities_id`,\n                           `actiontime`)\n                   VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n                           '" . $data['cost_time'] . "','" . $data['cost_fixed'] . "',\n                           '" . $data['cost_material'] . "', '" . $data['entities_id'] . "',\n                           '" . $data['actiontime'] . "')";
            $DB->queryOrDie($query, '0.84 move tickets costs');
        }
        $migration->dropField('glpi_tickets', 'cost_time');
        $migration->dropField('glpi_tickets', 'cost_fixed');
        $migration->dropField('glpi_tickets', 'cost_material');
    }
    $migration->addField("glpi_profiles", "ticketcost", "char", array('update' => "'w'", 'condition' => " WHERE `update_ticket` = 1"));
    // Set default to r as before
    $query = "UPDATE `glpi_profiles`\n             SET `ticketcost` = 'r'\n             WHERE `ticketcost` IS NULL";
    $DB->queryOrDie($query, "0.84 set ticketcost in glpi_profiles");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'rss flows'));
    if (!TableExists('glpi_rssfeeds')) {
        $query = "CREATE TABLE `glpi_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `url` text COLLATE utf8_unicode_ci,\n                  `refresh_rate` int(11) NOT NULL DEFAULT '86400',\n                  `max_items` int(11) NOT NULL DEFAULT '20',\n                  `have_error` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `users_id` (`users_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `have_error` (`have_error`),\n                  KEY `is_active` (`is_active`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds");
        $ADDTODISPLAYPREF['RSSFeed'] = array(2, 4, 5, 19, 6, 7);
    }
    if (!TableExists('glpi_rssfeeds_users')) {
        $query = "CREATE TABLE `glpi_rssfeeds_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds_users");
    }
    if (!TableExists('glpi_groups_rssfeeds')) {
        $query = "CREATE TABLE `glpi_groups_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_groups_rssfeeds");
    }
    if (!TableExists('glpi_profiles_rssfeeds')) {
        $query = "CREATE TABLE `glpi_profiles_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `profiles_id` (`profiles_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_profiles_rssfeeds");
    }
    if (!TableExists('glpi_entities_rssfeeds')) {
        $query = "CREATE TABLE `glpi_entities_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_entities_rssfeeds");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'planning recalls'));
    if (!TableExists('glpi_planningrecalls')) {
        $query = "CREATE TABLE `glpi_planningrecalls` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `before_time` int(11) NOT NULL DEFAULT '-10',\n                  `when` datetime DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `before_time` (`before_time`),\n                  KEY `when` (`when`),\n                  UNIQUE KEY `unicity` (`itemtype`,`items_id`, `users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_planningrecalls");
    }
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'PlanningRecall'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Planning recall', 'PlanningRecall', NOW())";
            $DB->queryOrDie($query, "0.84 add planning recall notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##recall.action##: ##recall.item.name##',\n                           '##recall.action##: ##recall.item.name##\n\n##recall.item.content##\n\n##lang.recall.planning.begin##: ##recall.planning.begin##\n##lang.recall.planning.end##: ##recall.planning.end##\n##lang.recall.planning.state##: ##recall.planning.state##\n##lang.recall.item.private##: ##recall.item.private##',\n'&lt;p&gt;##recall.action##: &lt;a href=\"##recall.item.url##\"&gt;##recall.item.name##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;##recall.item.content##&lt;/p&gt;\n&lt;p&gt;##lang.recall.planning.begin##: ##recall.planning.begin##&lt;br /&gt;##lang.recall.planning.end##: ##recall.planning.end##&lt;br /&gt;##lang.recall.planning.state##: ##recall.planning.state##&lt;br /&gt;##lang.recall.item.private##: ##recall.item.private##&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;\n&lt;p&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.84 add planning recall notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                           `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                           `date_mod`)\n                   VALUES ('Planning recall', 0, 'PlanningRecall', 'planningrecall', 'mail',\n                             {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "0.84 add planning recall notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                   VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::AUTHOR . ");";
            $DB->queryOrDie($query, "0.84 add planning recall notification target");
        }
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='PlanningRecall' AND `name`='planningrecall'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('PlanningRecall', 'planningrecall', 300, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.84 populate glpi_crontasks for planningrecall");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various fields'));
    $migration->changeField('glpi_entities', 'default_alarm_threshold', 'default_cartridges_alarm_threshold', 'integer', array('value' => -2));
    $migration->migrationOneTable('glpi_entities');
    $migration->addField("glpi_entities", 'default_consumables_alarm_threshold', "integer", array('value' => -2, 'update' => 'default_cartridges_alarm_threshold'));
    $migration->migrationOneTable('glpi_entities');
    // move -1 to Entity::CONFIG_NEVER
    $query = 'UPDATE `glpi_entities`
             SET `default_consumables_alarm_threshold` = -10
             WHERE `default_consumables_alarm_threshold` = -1';
    $DB->query($query);
    $query = 'UPDATE `glpi_entities`
             SET `default_cartridges_alarm_threshold` = -10
             WHERE `default_cartridges_alarm_threshold` = -1';
    $DB->query($query);
    $migration->addField("glpi_entities", 'send_contracts_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_contracts_alert', 'update' => '0', 'condition' => 'WHERE `id`=0'));
    $migration->addField("glpi_entities", 'send_infocoms_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_infocoms_alert', 'update' => '0', 'condition' => 'WHERE `id`=0'));
    $migration->addField("glpi_entities", 'send_licenses_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_licenses_alert', 'update' => '0', 'condition' => 'WHERE `id`=0'));
    $migration->addField("glpi_configs", "notification_to_myself", "bool", array('value' => 1));
    $migration->addField("glpi_configs", 'duedateok_color', "string", array('value' => '#06ff00'));
    $migration->addField("glpi_configs", 'duedatewarning_color', "string", array('value' => '#ffb800'));
    $migration->addField("glpi_configs", 'duedatecritical_color', "string", array('value' => '#ff0000'));
    $migration->addField("glpi_configs", 'duedatewarning_less', "integer", array('value' => 20));
    $migration->addField("glpi_configs", 'duedatecritical_less', "integer", array('value' => 5));
    $migration->addField("glpi_configs", 'duedatewarning_unit', "string", array('value' => '%'));
    $migration->addField("glpi_configs", 'duedatecritical_unit', "string", array('value' => '%'));
    $migration->addField("glpi_configs", "realname_ssofield", "string");
    $migration->addField("glpi_configs", "firstname_ssofield", "string");
    $migration->addField("glpi_configs", "email1_ssofield", "string");
    $migration->addField("glpi_configs", "email2_ssofield", "string");
    $migration->addField("glpi_configs", "email3_ssofield", "string");
    $migration->addField("glpi_configs", "email4_ssofield", "string");
    $migration->addField("glpi_configs", "phone_ssofield", "string");
    $migration->addField("glpi_configs", "phone2_ssofield", "string");
    $migration->addField("glpi_configs", "mobile_ssofield", "string");
    $migration->addField("glpi_configs", "comment_ssofield", "string");
    $migration->addField("glpi_configs", "title_ssofield", "string");
    $migration->addField("glpi_configs", "category_ssofield", "string");
    $migration->addField("glpi_configs", "language_ssofield", "string");
    $migration->addField("glpi_configs", "entity_ssofield", "string");
    $migration->addField("glpi_configs", "registration_number_ssofield", "string");
    $migration->addField("glpi_users", "notification_to_myself", "tinyint(1) DEFAULT NULL");
    $migration->addField("glpi_users", 'duedateok_color', "string");
    $migration->addField("glpi_users", 'duedatewarning_color', "string");
    $migration->addField("glpi_users", 'duedatecritical_color', "string");
    $migration->addField("glpi_users", 'duedatewarning_less', "int(11) DEFAULT NULL");
    $migration->addField("glpi_users", 'duedatecritical_less', "int(11) DEFAULT NULL");
    $migration->addField("glpi_users", 'duedatewarning_unit', "string");
    $migration->addField("glpi_users", 'duedatecritical_unit', "string");
    $migration->addField("glpi_users", 'display_options', "text");
    $migration->addField("glpi_reservationitems", "is_deleted", "bool");
    $migration->addKey("glpi_reservationitems", "is_deleted");
    $migration->addField("glpi_documentcategories", 'documentcategories_id', "integer");
    $migration->addField("glpi_documentcategories", 'completename', "text");
    $migration->addField("glpi_documentcategories", 'level', "integer");
    $migration->addField("glpi_documentcategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_documentcategories", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_documentcategories');
    $migration->addKey("glpi_documentcategories", array('documentcategories_id', 'name'), 'unicity');
    regenerateTreeCompleteName("glpi_documentcategories");
    $migration->addField("glpi_contacts", 'usertitles_id', "integer");
    $migration->addKey("glpi_contacts", 'usertitles_id');
    $migration->addField("glpi_contacts", 'address', "text");
    $migration->addField("glpi_contacts", 'postcode', "string");
    $migration->addField("glpi_contacts", 'town', "string");
    $migration->addField("glpi_contacts", 'state', "string");
    $migration->addField("glpi_contacts", 'country', "string");
    $migration->addField("glpi_configs", 'x509_ou_restrict', "string", array('after' => 'x509_email_field'));
    $migration->addField("glpi_configs", 'x509_o_restrict', "string", array('after' => 'x509_email_field'));
    $migration->addField("glpi_configs", 'x509_cn_restrict', "string", array('after' => 'x509_email_field'));
    if (!TableExists('glpi_slalevelcriterias')) {
        $query = "CREATE TABLE `glpi_slalevelcriterias` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `slalevels_id` int(11) NOT NULL DEFAULT '0',\n                  `criteria` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `condition` int(11) NOT NULL DEFAULT '0'\n                              COMMENT 'see define.php PATTERN_* and REGEX_* constant',\n                  `pattern` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `slalevels_id` (`slalevels_id`),\n                  KEY `condition` (`condition`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_slalevelcriterias");
    }
    $migration->addField("glpi_slalevels", 'match', "CHAR(10) DEFAULT NULL COMMENT 'see define.php *_MATCHING constant'");
    $query = "UPDATE `glpi_slalevelactions`\n             SET `action_type` = 'append'\n             WHERE `action_type` = 'assign'\n                   AND `field` IN ('_users_id_requester',  '_groups_id_requester',\n                                   '_users_id_assign',     '_groups_id_assign',\n                                   '_suppliers_id_assign', '_users_id_observer',\n                                   '_groups_id_observer');";
    $DB->queryOrDie($query, "0.84 update data for SLA actors add");
    // Clean observer as recipient of satisfaction survey
    $query = "DELETE FROM `glpi_notificationtargets`\n             WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n                   AND `glpi_notificationtargets`.`items_id` = '" . Notification::OBSERVER . "'\n                   AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n                                              FROM `glpi_notifications`\n                                              WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                                                    AND `glpi_notifications`.`event` = 'satisfaction')";
    $DB->queryOrDie($query, "0.84 clean targets for satisfaction notification");
    // Clean user as recipient of item not unique
    $query = "DELETE FROM `glpi_notificationtargets`\n             WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n                   AND `glpi_notificationtargets`.`items_id` = '" . Notification::USER . "'\n                   AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n                                              FROM `glpi_notifications`\n                                              WHERE `glpi_notifications`.`itemtype` = 'FieldUnicity'\n                                                    AND `glpi_notifications`.`event` = 'refuse')";
    $DB->queryOrDie($query, "0.84 clean targets for fieldunicity notification");
    if (!TableExists('glpi_blacklists')) {
        $query = "CREATE TABLE `glpi_blacklists` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `type` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `type` (`type`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_blacklists");
        $ADDTODISPLAYPREF['Blacklist'] = array(12, 11);
        $toinsert = array(Blacklist::IP => array('empty IP' => '', 'localhost' => '127.0.0.1', 'zero IP' => '0.0.0.0'), Blacklist::MAC => array('empty MAC' => ''));
        foreach ($toinsert as $type => $datas) {
            if (count($datas)) {
                foreach ($datas as $name => $value) {
                    $query = "INSERT INTO `glpi_blacklists`\n                                (`type`,`name`,`value`)\n                         VALUES ('{$type}','" . addslashes($name) . "','" . addslashes($value) . "')";
                    $DB->queryOrDie($query, "0.84 insert datas to glpi_blacklists");
                }
            }
        }
    }
    $query = "SELECT `id`\n              FROM `glpi_rulerightparameters`\n              WHERE `name` = '(LDAP) MemberOf'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $query = "INSERT INTO `glpi_rulerightparameters`\n                VALUES (NULL, '(LDAP) MemberOf', 'memberof', '')";
        $DB->queryOrDie($query, "0.84 insert (LDAP) MemberOf in glpi_rulerightparameters");
    }
    if (!TableExists('glpi_ssovariables')) {
        $query = "CREATE TABLE `glpi_ssovariables` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci NOT NULL,\n                  PRIMARY KEY (`id`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_ssovariables");
        $query = "INSERT INTO `glpi_ssovariables`\n                       (`id`, `name`, `comment`)\n                VALUES (1, 'HTTP_AUTH_USER', ''),\n                       (2, 'REMOTE_USER', ''),\n                       (3, 'PHP_AUTH_USER', ''),\n                       (4, 'USERNAME', ''),\n                       (5, 'REDIRECT_REMOTE_USER', ''),\n                       (6, 'HTTP_REMOTE_USER', '')";
        $DB->queryOrDie($query, "0.84 add values from  glpi_ssovariables");
    }
    if ($migration->addField('glpi_configs', 'ssovariables_id', 'integer')) {
        $migration->migrationOneTable('glpi_configs');
        //Get configuration
        $query = "SELECT `existing_auth_server_field`\n                FROM `glpi_configs`";
        $result = $DB->query($query);
        $existing_auth_server_field = $DB->result($result, 0, "existing_auth_server_field");
        if ($existing_auth_server_field) {
            //Get dropdown value for existing_auth_server_field
            $query = "SELECT `id`\n                   FROM `glpi_ssovariables`\n                   WHERE `name` = '{$existing_auth_server_field}'";
            $result = $DB->query($query);
            //Update config
            if ($DB->numrows($result) > 0) {
                $query = "UPDATE `glpi_configs`\n                      SET `ssovariables_id` = '" . $DB->result($result, 0, "id") . "'";
                $DB->queryOrDie($query, "0.84 update glpi_configs");
            }
            //Drop old field
        }
    }
    $migration->dropField('glpi_configs', 'existing_auth_server_field');
    //Remove field to specify an ldap server for SSO users : don't need it anymore
    $migration->dropField('glpi_configs', 'authldaps_id_extra');
    // Clean uneeded logs
    $cleancondition = array();
    $cleancondition['reminder_kb'] = "`itemtype` IN ('Entity', 'User', 'Profile', 'Group')\n                                       AND `itemtype_link` IN ('Reminder', 'Knowbase')";
    foreach ($cleancondition as $name => $condition) {
        $query = "DELETE\n                FROM `glpi_logs`\n                WHERE {$condition}";
        $DB->queryOrDie($query, "0.84 clean logs for {$name}");
    }
    //Remove OCS tables from GLPI's core
    $migration->renameTable('glpi_ocsadmininfoslinks', 'ocs_glpi_ocsadmininfoslinks');
    $migration->renameTable('glpi_ocslinks', 'ocs_glpi_ocslinks');
    $migration->renameTable('glpi_ocsservers', 'ocs_glpi_ocsservers');
    $migration->renameTable('glpi_registrykeys', 'ocs_glpi_registrykeys');
    // Migrate RuleOcs to RuleImportEntity
    $query = "UPDATE `glpi_rules`\n             SET `sub_type` = 'RuleImportEntity'\n             WHERE `sub_type` = 'RuleOcs'";
    $DB->queryOrDie($query, "0.84 update datas for old OCS rules");
    $migration->copyTable('glpi_rules', 'ocs_glpi_rules');
    $migration->copyTable('glpi_ruleactions', 'ocs_glpi_ruleactions');
    $migration->copyTable('glpi_rulecriterias', 'ocs_glpi_rulecriterias');
    // Delete OCS rules
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    $query = "SELECT GROUP_CONCAT(`id`)\n             FROM `glpi_rules`\n             WHERE `sub_type` = 'RuleImportEntity'\n             GROUP BY `sub_type`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            // Get rule string
            $rules = $DB->result($result, 0, 0);
            $query = "DELETE\n                   FROM `glpi_ruleactions`\n                   WHERE `rules_id` IN ({$rules})";
            $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas");
            $query = "DELETE\n                   FROM `glpi_rulecriterias`\n                   WHERE `rules_id` IN ({$rules})";
            $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas");
            $query = "DELETE\n                   FROM `glpi_rules`\n                   WHERE `id` IN ({$rules})";
            $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas");
        }
    }
    // copy table to keep value of fields deleted after
    $migration->copyTable('glpi_profiles', 'ocs_glpi_profiles');
    $migration->dropField('glpi_profiles', 'ocsng');
    $migration->dropField('glpi_profiles', 'sync_ocsng');
    $migration->dropField('glpi_profiles', 'view_ocsng');
    $migration->dropField('glpi_profiles', 'clean_ocsng');
    $migration->changeField('glpi_profiles', 'rule_ocs', 'rule_import', 'char');
    $migration->changeField('glpi_rulecacheprinters', 'ignore_ocs_import', 'ignore_import', 'char');
    $migration->changeField('glpi_rulecachesoftwares', 'ignore_ocs_import', 'ignore_import', 'char');
    $migration->dropField('glpi_configs', 'use_ocs_mode');
    // clean crontask
    $migration->copyTable('glpi_crontasks', 'ocs_glpi_crontasks');
    $query = "DELETE\n             FROM `glpi_crontasks`\n             WHERE `itemtype` = 'OcsServer'";
    $DB->queryOrDie($query, "0.84 delete OcsServer in crontasks");
    // clean displaypreferences
    $migration->copyTable('glpi_displaypreferences', 'ocs_glpi_displaypreferences');
    $query = "DELETE\n             FROM `glpi_displaypreferences`\n             WHERE `itemtype` = 'OcsServer'";
    $DB->queryOrDie($query, "0.84 delete OcsServer in displaypreferences");
    // Give history entries to plugin
    $query = "UPDATE `glpi_logs`\n             SET `linked_action` = `linked_action`+1000,\n                 `itemtype_link` = 'PluginOcsinventoryngOcslink'\n             WHERE `linked_action` IN (8,9,10,11)";
    $DB->queryOrDie($query, "0.84 update OCS links in history");
    $migration->displayWarning("You can delete ocs_* tables if you use OCS mode ONLY AFTER ocsinventoryng plugin installation.", true);
    $migration->displayWarning("You can delete ocs_* tables if you do not use OCS synchronisation.", true);
    $migration->addField('glpi_authldaps', 'pagesize', 'integer');
    $migration->addField('glpi_authldaps', 'ldap_maxlimit', 'integer');
    $migration->addField('glpi_authldaps', 'can_support_pagesize', 'bool');
    // Add delete ticket notification
    if (countElementsInTable("glpi_notifications", "`itemtype` = 'Ticket' AND `event` = 'delete'") == 0) {
        // Get first template for tickets :
        $notid = 0;
        $query = "SELECT MIN(id) AS id\n                FROM `glpi_notificationtemplates`\n                WHERE `itemtype` = 'Ticket'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) == 1) {
                $notid = $DB->result($result, 0, 0);
            }
        }
        if ($notid > 0) {
            $notifications = array('delete' => array(Notification::GLOBAL_ADMINISTRATOR));
            $notif_names = array('delete' => 'Delete Ticket');
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                              (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                               `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                               `date_mod`)\n                       VALUES ('" . $notif_names[$type] . "', 0, 'Ticket', '{$type}', 'mail',\n                               {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.83 add problem {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.83 add problem {$type} notification target");
                }
            }
        }
    }
    // Add multiple suppliers for itil objects
    if (!TableExists('glpi_problems_suppliers')) {
        $query = "CREATE TABLE `glpi_problems_suppliers` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `suppliers_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`problems_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_problems_suppliers");
        $migration->migrationOneTable('glpi_problems_suppliers');
        foreach ($DB->request('glpi_problems', "`suppliers_id_assign` > 0") as $data) {
            $query = "INSERT INTO `glpi_problems_suppliers`\n                          (`suppliers_id`, `type`, `problems_id`)\n                   VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n                           '" . $data['id'] . "')";
            $DB->query($query);
        }
        $migration->dropField('glpi_problems', 'suppliers_id_assign');
    }
    if (!TableExists('glpi_suppliers_tickets')) {
        $query = "CREATE TABLE `glpi_suppliers_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  `suppliers_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`tickets_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_suppliers_tickets");
        $migration->migrationOneTable('glpi_suppliers_tickets');
        foreach ($DB->request('glpi_tickets', "`suppliers_id_assign` > 0") as $data) {
            $query = "INSERT INTO `glpi_suppliers_tickets`\n                          (`suppliers_id`, `type`, `tickets_id`)\n                   VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n                           '" . $data['id'] . "')";
            $DB->query($query);
        }
        $migration->dropField('glpi_tickets', 'suppliers_id_assign');
    }
    $migration->addField('glpi_tickets', 'locations_id', 'integer');
    $migration->addKey('glpi_tickets', 'locations_id');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket'));
    $changes = array();
    $changes['RuleTicket'] = array('suppliers_id_assign' => '_suppliers_id_assign');
    $changes['RuleDictionnarySoftware'] = array('_ignore_ocs_import' => '_ignore_import');
    $changes['RuleImportEntity'] = array('_ignore_ocs_import' => '_ignore_import');
    $changes['RuleDictionnaryPrinter'] = array('_ignore_ocs_import' => '_ignore_import');
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    foreach ($changes as $ruletype => $tab) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = '" . $ruletype . "'\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `field` = '{$new}'\n                         WHERE `field` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.84 update datas for rules actions");
                }
                // Update criterias
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_rulecriterias`\n                         SET `criteria` = '{$new}'\n                         WHERE `criteria` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.84 update datas for rules criterias");
                }
            }
        }
    }
    // change ruleaction for manufacturer (id to name)
    $query = "SELECT  `glpi_ruleactions` .`id` AS id,\n                     `sub_type`,\n                     `glpi_manufacturers`.`name` AS newvalue\n             FROM `glpi_rules`\n             INNER JOIN `glpi_ruleactions`\n                  ON (`glpi_rules`.`id` = `glpi_ruleactions`.`rules_id`\n                      AND `field` = 'Manufacturer')\n             LEFT JOIN `glpi_manufacturers`\n                  ON `glpi_manufacturers`.`id` = `glpi_ruleactions`.`value`\n             WHERE `sub_type` = 'RuleDictionnarySoftware'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                // Update manufacturer
                $query = "UPDATE `glpi_ruleactions`\n                      SET `value` = '" . $data['newvalue'] . "'\n                      WHERE `id` = " . $data['id'];
                $DB->queryOrDie($query, "0.84 update value of manufacturer for rules actions");
            }
        }
    }
    // Move ticketrecurrent values to correct ones
    $migration->changeField('glpi_ticketrecurrents', 'periodicity', 'periodicity', 'string');
    $migration->addField('glpi_ticketrecurrents', 'calendars_id', 'integer');
    $migration->addField('glpi_ticketrecurrents', 'end_date', 'datetime');
    $migration->migrationOneTable('glpi_ticketrecurrents');
    foreach ($DB->request('glpi_ticketrecurrents', "`periodicity` >= " . MONTH_TIMESTAMP) as $data) {
        $periodicity = $data['periodicity'];
        if (is_numeric($periodicity)) {
            if ($periodicity >= 365 * DAY_TIMESTAMP) {
                $periodicity = round($periodicity / (365 * DAY_TIMESTAMP)) . 'YEAR';
            } else {
                $periodicity = round($periodicity / MONTH_TIMESTAMP) . 'MONTH';
            }
            $query = "UPDATE `glpi_ticketrecurrents`\n                   SET `periodicity` = '{$periodicity}'\n                   WHERE `id` = '" . $data['id'] . "'";
            $DB->query($query);
        }
    }
    $query = "UPDATE `glpi_notifications`\n             SET   `itemtype` = 'CartridgeItem'\n             WHERE `itemtype` = 'Cartridge'";
    $DB->queryOrDie($query, "0.83 update glpi_notifications for Cartridge");
    $query = "UPDATE `glpi_notificationtemplates`\n             SET   `itemtype` = 'CartridgeItem'\n             WHERE `itemtype` = 'Cartridge'";
    $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Cartridge");
    $query = "UPDATE `glpi_notifications`\n             SET   `itemtype` = 'ConsumableItem'\n             WHERE `itemtype` = 'Consumable'";
    $DB->queryOrDie($query, "0.83 update glpi_notifications for Consumable");
    $query = "UPDATE `glpi_notificationtemplates`\n             SET   `itemtype` = 'ConsumableItem'\n             WHERE `itemtype` = 'Consumable'";
    $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Consumable");
    $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from item'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'items_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromitem', 'value' => 1)));
    $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from user'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'users_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromuser', 'value' => 1)));
    // Change begin_date id for budget
    $query = "UPDATE `glpi_displaypreferences`\n              SET `num` = '5'\n              WHERE `itemtype` = 'Budget'\n                    AND `num` = '2'";
    $DB->query($query);
    migrateComputerDevice('DeviceProcessor', 'frequency', 'integer', array('serial' => 'string'));
    migrateComputerDevice('DeviceMemory', 'size', 'integer', array('serial' => 'string'));
    migrateComputerDevice('DeviceHardDrive', 'capacity', 'integer', array('serial' => 'string'));
    migrateComputerDevice('DeviceGraphicCard', 'memory', 'integer');
    migrateComputerDevice('DeviceNetworkCard', 'mac', 'string');
    migrateComputerDevice('DeviceSoundCard');
    migrateComputerDevice('DeviceMotherBoard');
    migrateComputerDevice('DeviceDrive');
    migrateComputerDevice('DeviceControl');
    migrateComputerDevice('DevicePci');
    migrateComputerDevice('DeviceCase');
    migrateComputerDevice('DevicePowerSupply');
    $migration->migrationOneTable('glpi_computers_softwareversions');
    //Rename fields in glpi_computers_softwareversions with inaproprious signification
    $migration->changeField('glpi_computers_softwareversions', 'is_deleted', 'is_deleted_computer', 'bool');
    $migration->changeField('glpi_computers_softwareversions', 'is_template', 'is_template_computer', 'bool');
    $migration->migrationOneTable('glpi_computers_softwareversions');
    $types = array('glpi_computers_items', 'glpi_computervirtualmachines', 'glpi_computers_softwareversions', 'glpi_computerdisks', 'glpi_networkports', 'glpi_computers_softwarelicenses', 'glpi_networknames', 'glpi_ipaddresses');
    foreach (Item_Devices::getDeviceTypes() as $id => $type) {
        $types[] = getTableForItemType($type);
    }
    //Add is_deleted for relations
    foreach ($types as $table) {
        if ($migration->addField($table, 'is_deleted', 'bool', array('value' => 0))) {
            $migration->migrationOneTable($table);
            $migration->addKey($table, 'is_deleted');
        }
    }
    ///For computers, rename is is_ocs_import to is_dynamic
    $migration->changeField('glpi_computers', 'is_ocs_import', 'is_dynamic', 'bool');
    $migration->migrationOneTable('glpi_computers');
    $migration->dropKey("glpi_computers", 'is_ocs_import');
    $migration->addKey("glpi_computers", 'is_dynamic');
    //Add field is_dynamic
    $types = array_merge($types, array('glpi_printers', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_networkports', 'glpi_monitors', 'glpi_networknames', 'glpi_ipaddresses'));
    foreach ($types as $table) {
        if ($migration->addField($table, 'is_dynamic', 'bool')) {
            $migration->migrationOneTable($table);
            $migration->addKey($table, 'is_dynamic');
        }
    }
    $ADDTODISPLAYPREF['ReservationItem'] = array(5);
    // split validation rights in both
    $migration->changeField('glpi_profiles', 'validate_ticket', 'validate_request', 'char');
    $migration->changeField('glpi_profiles', 'create_validation', 'create_request_validation', 'char');
    $migration->migrationOneTable('glpi_profiles');
    $migration->addField('glpi_profiles', 'validate_incident', 'char', array('update' => 'validate_request'));
    $migration->addField('glpi_profiles', 'create_incident_validation', 'char', array('update' => 'create_request_validation'));
    // add rights to delete all validation
    $migration->addField('glpi_profiles', 'delete_validations', 'char', array('update' => 'delete_ticket'));
    // add rights to manage public rssfeed
    $migration->addField('glpi_profiles', 'rssfeed_public', 'char', array('update' => 'reminder_public', 'after' => 'reminder_public'));
    // add ticket templates
    $migration->addField('glpi_profiles', 'tickettemplates_id', 'integer');
    // Drop not needed fields
    $migration->dropField('glpi_tickettemplatepredefinedfields', 'entities_id');
    $migration->dropField('glpi_tickettemplatepredefinedfields', 'is_recursive');
    $migration->dropField('glpi_tickettemplatemandatoryfields', 'entities_id');
    $migration->dropField('glpi_tickettemplatemandatoryfields', 'is_recursive');
    $migration->dropField('glpi_tickettemplatehiddenfields', 'entities_id');
    $migration->dropField('glpi_tickettemplatehiddenfields', 'is_recursive');
    // Clean unlinked calendar segments and holidays
    $query = "DELETE\n             FROM `glpi_calendars_holidays`\n             WHERE `glpi_calendars_holidays`.`calendars_id`\n                     NOT IN (SELECT `glpi_calendars`.`id`\n                             FROM `glpi_calendars`)";
    $DB->queryOrDie($query, "0.84 clean glpi_calendars_holidays");
    $query = "DELETE\n             FROM `glpi_calendarsegments`\n             WHERE `glpi_calendarsegments`.`calendars_id`\n                     NOT IN (SELECT `glpi_calendars`.`id`\n                             FROM `glpi_calendars`)";
    $DB->queryOrDie($query, "0.84 clean glpi_calendarsegments");
    // Add keys for serial, otherserial and uuid
    $newindexes = array('serial' => array('glpi_computers', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_deviceprocessors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'otherserial' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'uuid' => array('glpi_computers', 'glpi_computervirtualmachines'));
    foreach ($newindexes as $field => $tables) {
        foreach ($tables as $table) {
            $migration->addKey($table, $field);
        }
    }
    // Clean unlinked ticket_problem
    $query = "DELETE\n             FROM `glpi_problems_tickets`\n             WHERE `glpi_problems_tickets`.`tickets_id`\n                     NOT IN (SELECT `glpi_tickets`.`id`\n                             FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets");
    $query = "DELETE\n             FROM `glpi_problems_tickets`\n             WHERE `glpi_problems_tickets`.`problems_id`\n                     NOT IN (SELECT `glpi_problems`.`id`\n                             FROM `glpi_problems`)";
    $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets");
    // Clean unlinked softwarelicense_computer
    $query = "DELETE\n             FROM `glpi_computers_softwarelicenses`\n             WHERE `glpi_computers_softwarelicenses`.`softwarelicenses_id`\n                     NOT IN (SELECT `glpi_softwarelicenses`.`id`\n                             FROM `glpi_softwarelicenses`)";
    $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses");
    $query = "DELETE\n             FROM `glpi_computers_softwarelicenses`\n             WHERE `glpi_computers_softwarelicenses`.`computers_id`\n                     NOT IN (SELECT `glpi_computers`.`id`\n                             FROM `glpi_computers`)";
    $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses");
    // Clean unlinked items_problems
    $query = "DELETE\n             FROM `glpi_items_problems`\n             WHERE `glpi_items_problems`.`problems_id`\n                     NOT IN (SELECT `glpi_problems`.`id`\n                             FROM `glpi_problems`)";
    $DB->queryOrDie($query, "0.84 clean glpi_items_problems");
    $toclean = array('Computer', 'Monitor', 'NetworkEquipment', 'Peripheral', 'Phone', 'Printer', 'Software');
    foreach ($toclean as $type) {
        $query = "DELETE\n               FROM `glpi_items_problems`\n               WHERE `glpi_items_problems`.`itemtype` = '{$type}'\n                     AND `glpi_items_problems`.`items_id`\n                        NOT IN (SELECT `" . getTableForItemType($type) . "`.`id`\n                              FROM `" . getTableForItemType($type) . "`)";
        $DB->queryOrDie($query, "0.84 clean glpi_items_problems");
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
コード例 #10
0
 static function addToOcsArray($computers_id, $toadd, $field)
 {
     global $DB;
     $query = "SELECT `{$field}`\n                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                WHERE `computers_id` = '{$computers_id}'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result)) {
             $tab = importArrayFromDB($DB->result($result, 0, 0));
             // Stripslashes because importArray get clean array
             foreach ($toadd as $key => $val) {
                 $tab[$key] = stripslashes($val);
             }
             $query = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`\n                      SET `{$field}` = '" . addslashes(exportArrayToDB($tab)) . "'\n                      WHERE `computers_id` = '{$computers_id}'";
             $DB->query($query);
         }
     }
 }
コード例 #11
0
 /**
  * Get if agent allowed to do this TASK
  *
  * @param $module_name value Name of the module
  * @param $items_id integer id of the agent
  *
  * @return bool
  *
  **/
 function isAgentCanDo($module_name, $items_id)
 {
     $agentModule = $this->getActivationExceptions($module_name);
     if ($agentModule['is_active'] == 0) {
         $a_agentList = importArrayFromDB($agentModule['exceptions']);
         if (in_array($items_id, $a_agentList)) {
             return TRUE;
         } else {
             return FALSE;
         }
     } else {
         $a_agentList = importArrayFromDB($agentModule['exceptions']);
         if (in_array($items_id, $a_agentList)) {
             return FALSE;
         } else {
             return TRUE;
         }
     }
 }
コード例 #12
0
   $_POST = $_GET;
   $pmComponentscatalog_rule->delete($_POST);
   Html::redirect($CFG_GLPI['root_doc']."/plugins/monitoring/front/componentscatalog.form.php?id=".$_POST['plugin_monitoring_componentscalalog_id']);
} else if (isset($_GET['contains'])
        OR isset($_GET['reset'])) {
//   if (isset($_SESSION['plugin_monitoring_rules'])) {
//      unset($_SESSION['plugin_monitoring_rules']);
//   }
//   $_SESSION['plugin_monitoring_rules'] = $_POST;
//   $_SESSION['plugin_monitoring_rules_REQUEST_URI'] = $_SERVER['REQUEST_URI'];
   //Html::back();
} else if (isset($_GET['id'])
        AND !isset($_GET['itemtype'])) {
   $pmComponentscatalog_rule->getFromDB($_GET['id']);

   $val = importArrayFromDB($pmComponentscatalog_rule->fields['condition']);
   $nbfields = 1;
   $nbfields = count($val['field']);
   foreach ($val as $name=>$data) {
      if (is_array($data)) {
         $i =0;
         foreach ($data as $key => $value) {
            $val[$name."[".$key."]"] = $value;
         }
         unset($val[$name]);
      }
   }
   $_POST = $val;
   $_POST["glpisearchcount"] = $nbfields;
   $_POST['id'] = $_GET['id'];
   $_POST['name'] = $pmComponentscatalog_rule->fields['name'];
コード例 #13
0
 function deleteGaugeItems($array)
 {
     $this->getFromDB($array['id']);
     $aggregate_items = importArrayFromDB($this->fields['aggregate_items']);
     $split = explode('|', $array['delete_item']);
     if (count($split) == 5) {
         unset($aggregate_items[$split[0]][$split[1]][$split[2]][$split[3]][$split[4]]);
         if (count($aggregate_items[$split[0]][$split[1]][$split[2]][$split[3]]) == 0) {
             unset($aggregate_items[$split[0]][$split[1]][$split[2]][$split[3]]);
             if (count($aggregate_items[$split[0]][$split[1]][$split[2]]) == 0) {
                 unset($aggregate_items[$split[0]][$split[1]][$split[2]]);
                 if (count($aggregate_items[$split[0]][$split[1]]) == 0) {
                     unset($aggregate_items[$split[0]][$split[1]]);
                     if (count($aggregate_items[$split[0]]) == 0) {
                         unset($aggregate_items[$split[0]]);
                     }
                 }
             }
         }
     }
     $input = array('id' => $array['id'], 'aggregate_items' => exportArrayToDB($aggregate_items));
     $this->update($input);
 }
コード例 #14
0
ファイル: config.php プロジェクト: ryukansent/Thesis-SideB
     }
 } else {
     // Normal load process : use normal config table. If problem try old one
     if ($config_object->getFromDB(1)) {
         $config_ok = true;
     } else {
         // Manage glpi_config table before 0.80
         $config_object->forceTable('glpi_config');
         if ($config_object->getFromDB(1)) {
             $config_ok = true;
         }
     }
 }
 if ($config_ok) {
     $CFG_GLPI = array_merge($CFG_GLPI, $config_object->fields);
     $CFG_GLPI['priority_matrix'] = importArrayFromDB($config_object->fields['priority_matrix'], true);
     Config::detectRootDoc();
     // Path for icon of document type
     $CFG_GLPI["typedoc_icon_dir"] = $CFG_GLPI["root_doc"] . "/pics/icones";
 } else {
     echo "Error accessing config table";
     exit;
 }
 // If debug mode activated : display some informations
 if ($_SESSION['glpi_use_mode'] == DEBUG_MODE) {
     // display_errors only need for for E_ERROR, E_PARSE, ... which cannot be catched
     ini_set('display_errors', 'On');
     // Recommended development settings
     error_reporting(E_ALL | E_STRICT);
     set_error_handler('userErrorHandlerDebug');
 } else {
コード例 #15
0
ファイル: bookmark.class.php プロジェクト: pvasener/glpi
 /**
  * Move a bookmark in an ordered collection
  *
  * @since version 0.85
  *
  * @param $items    array      of the rules ID to move
  * @param $ref_ID   integer    of the rule position  (0 means all, so before all or after all)
  * @param $action   string     of move : after or before ( default 'after')
  *
  * @return true if all ok
  **/
 function moveBookmark($items = array(), $ref_ID, $action = 'after')
 {
     global $DB;
     if (count($items)) {
         // Clean IDS : drop ref_ID
         if (isset($items[$ref_ID])) {
             unset($items[$ref_ID]);
         }
         $user = new User();
         $personalorderfield = 'privatebookmarkorder';
         if ($user->getFromDB(Session::getLoginUserID())) {
             $personalorder = importArrayFromDB($user->fields[$personalorderfield]);
         }
         if (!is_array($personalorder)) {
             return false;
         }
         $newpersonalorder = array();
         foreach ($personalorder as $val) {
             // Found item
             if ($val == $ref_ID) {
                 // Add after so add ref ID
                 if ($action == 'after') {
                     $newpersonalorder[] = $ref_ID;
                 }
                 foreach ($items as $val2) {
                     $newpersonalorder[] = $val2;
                 }
                 if ($action == 'before') {
                     $newpersonalorder[] = $ref_ID;
                 }
             } else {
                 if (!isset($items[$val])) {
                     $newpersonalorder[] = $val;
                 }
             }
         }
         $user->update(array('id' => Session::getLoginUserID(), $personalorderfield => exportArrayToDB($newpersonalorder)));
         return true;
     }
     return false;
 }
コード例 #16
0
 function prepareRun($taskjobs_id)
 {
     global $DB;
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfAgent = new PluginFusioninventoryAgent();
     $a_specificity = array();
     $a_specificity['DEVICE'] = array();
     $uniqid = uniqid();
     $pfTaskjob->getFromDB($taskjobs_id);
     $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
     $NetworkEquipment = new NetworkEquipment();
     $NetworkPort = new NetworkPort();
     /*
      * * Different possibilities  :
      * IP RANGE
      * NetworkEquipment
      * Printer
      *
      * We will count total number of devices to query
      */
     // get all snmpauth
     $a_snmpauth = getAllDatasFromTable("glpi_plugin_fusioninventory_configsecurities");
     // get items_id by type
     $a_iprange = array();
     $a_NetworkEquipment = array();
     $a_Printer = array();
     $communication = $pfTask->fields['communication'];
     $a_definition = importArrayFromDB($pfTaskjob->fields['definition']);
     foreach ($a_definition as $datas) {
         $itemtype = key($datas);
         $items_id = current($datas);
         switch ($itemtype) {
             case 'PluginFusioninventoryIPRange':
                 $a_iprange[] = $items_id;
                 break;
             case 'NetworkEquipment':
                 $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_networkequipments`\n                  LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                       ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                          AND `glpi_networkports`.`itemtype`='NetworkEquipment'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_networkequipments`.`is_deleted`='0'\n                       AND `plugin_fusioninventory_configsecurities_id`!='0'\n                       AND `glpi_networkequipments`.`id` = '" . $items_id . "'\n                       AND `glpi_ipaddresses`.`name`!=''\n                  LIMIT 1";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                         $input = array();
                         $input['TYPE'] = 'NETWORKING';
                         $input['ID'] = $data['gID'];
                         $input['IP'] = $data['gnifaddr'];
                         $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                         $a_specificity['DEVICE']['NetworkEquipment' . $data['gID']] = $input;
                         $a_NetworkEquipment[] = $items_id;
                     }
                 }
                 break;
             case 'Printer':
                 $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_printers`\n                  LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                          ON `printers_id`=`glpi_printers`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                          AND `glpi_networkports`.`itemtype`='Printer'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_printers`.`is_deleted`=0\n                        AND `plugin_fusioninventory_configsecurities_id`!='0'\n                        AND `glpi_printers`.`id` = '" . $items_id . "'\n                        AND `glpi_ipaddresses`.`name`!=''\n                  LIMIT 1";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                         $input = array();
                         $input['TYPE'] = 'PRINTER';
                         $input['ID'] = $data['gID'];
                         $input['IP'] = $data['gnifaddr'];
                         $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                         $a_specificity['DEVICE']['Printer' . $data['gID']] = $input;
                         $a_Printer[] = $items_id;
                     }
                 }
                 break;
         }
     }
     // Get all devices on each iprange
     foreach ($a_iprange as $items_id) {
         $pfIPRange->getFromDB($items_id);
         // Search NetworkEquipment
         $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                            `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                            `plugin_fusioninventory_configsecurities_id`,\n                     FROM `glpi_networkequipments`\n                     LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                          ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                     LEFT JOIN `glpi_networkports`\n                          ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                             AND `glpi_networkports`.`itemtype`='NetworkEquipment'\n                     LEFT JOIN `glpi_networknames`\n                          ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                             AND `glpi_networknames`.`itemtype`='NetworkPort'\n                     LEFT JOIN `glpi_ipaddresses`\n                          ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                             AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                     WHERE `glpi_networkequipments`.`is_deleted`='0'\n                          AND `plugin_fusioninventory_configsecurities_id`!='0'";
         if ($pfIPRange->fields['entities_id'] != '-1') {
             $entities = "(" . $this->fields['entities_id'];
             foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
                 $entities .= ",{$parent}";
             }
             $entities .= ")";
             $query .= " AND `glpi_networkequipments`.`entities_id` IN " . $entities . " ";
         }
         $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                         BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                         AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
         $query .= " GROUP BY `glpi_networkequipments`.`id`";
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                 $input = array();
                 $input['TYPE'] = 'NETWORKING';
                 $input['ID'] = $data['gID'];
                 $input['IP'] = $data['gnifaddr'];
                 $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                 $a_specificity['DEVICE']['NetworkEquipment' . $data['gID']] = $input;
                 $a_NetworkEquipment[] = $data['gID'];
             }
         }
         // Search Printer
         $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_printers`\n                  LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                          ON `printers_id`=`glpi_printers`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                          AND `glpi_networkports`.`itemtype`='Printer'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_printers`.`is_deleted`=0\n                        AND `plugin_fusioninventory_configsecurities_id`!='0'";
         if ($pfIPRange->fields['entities_id'] != '-1') {
             $entities = "(" . $this->fields['entities_id'];
             foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
                 $entities .= ",{$parent}";
             }
             $entities .= ")";
             $query .= "AND `glpi_printers`.`entities_id` IN " . $entities . " ";
         }
         $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                      BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                      AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
         $query .= " GROUP BY `glpi_printers`.`id`";
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                 $input = array();
                 $input['TYPE'] = 'PRINTER';
                 $input['ID'] = $data['gID'];
                 $input['IP'] = $data['gnifaddr'];
                 $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                 $a_specificity['DEVICE']['Printer' . $data['gID']] = $input;
                 $a_Printer[] = $data['gID'];
             }
         }
     }
     $count_device = count($a_NetworkEquipment) + count($a_Printer);
     $a_actions = importArrayFromDB($pfTaskjob->fields['action']);
     // *** For dynamic agent same subnet, it's an another management ***
     if (strstr($pfTaskjob->fields['action'], '".2"')) {
         $a_subnet = array();
         $a_agentList = array();
         $a_devicesubnet = array();
         foreach ($a_NetworkEquipment as $items_id) {
             $NetworkEquipment->getFromDB($items_id);
             $a_ip = explode(".", $NetworkEquipment->fields['ip']);
             $ip_subnet = $a_ip[0] . "." . $a_ip[1] . "." . $a_ip[2] . ".";
             if (!isset($a_subnet[$ip_subnet])) {
                 $a_subnet[$ip_subnet] = 0;
             }
             $a_subnet[$ip_subnet]++;
             $a_devicesubnet[$ip_subnet]['NetworkEquipment'][$items_id] = 1;
         }
         foreach ($a_Printer as $items_id) {
             $a_ports = $NetworkPort->find("`itemtype`='Printer'\n                                          AND `items_id`='" . $items_id . "'\n                                          AND `ip`!='127.0.0.1'");
             foreach ($a_ports as $a_port) {
                 $a_ip = explode(".", $a_port['ip']);
                 $ip_subnet = $a_ip[0] . "." . $a_ip[1] . "." . $a_ip[2] . ".";
                 if (!isset($a_subnet[$ip_subnet])) {
                     $a_subnet[$ip_subnet] = 0;
                 }
                 $a_subnet[$ip_subnet]++;
                 $a_devicesubnet[$ip_subnet]['Printer'][$items_id] = 1;
             }
         }
         $a_agentsubnet = array();
         foreach ($a_subnet as $subnet => $num) {
             $a_agentList = $this->getAgentsSubnet($num, $communication, $subnet);
             if (!isset($a_agentList)) {
                 $a_agentsubnet[$subnet] = '';
             } else {
                 $a_agentsubnet[$subnet] = $a_agentList;
             }
         }
         $a_input = array();
         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
         $a_input['state'] = 1;
         $a_input['plugin_fusioninventory_agents_id'] = 0;
         $a_input['itemtype'] = '';
         $a_input['items_id'] = 0;
         $a_input['uniqid'] = $uniqid;
         $a_input['execution_id'] = $task->fields['execution_id'];
         $taskvalid = 0;
         foreach ($a_agentsubnet as $subnet => $a_agentList) {
             if (!isset($a_agentList) or isset($a_agentList) && is_array($a_agentList) && count($a_agentList) == '0' or isset($a_agentList) && !is_array($a_agentList) && $a_agentList == '') {
                 // No agent available for this subnet
                 for ($i = 0; $i < 2; $i++) {
                     $itemtype = 'Printer';
                     if ($i == '0') {
                         $itemtype = 'NetworkEquipment';
                     }
                     if (isset($a_devicesubnet[$subnet][$itemtype])) {
                         foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id => $num) {
                             $a_input['itemtype'] = $itemtype;
                             $a_input['items_id'] = $items_id;
                             $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE'][$itemtype . $items_id]);
                             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                             //Add log of taskjob
                             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                             $a_input['state'] = 7;
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $pfTaskjoblog->add($a_input);
                             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 1, "Unable to find agent to inventory " . "this " . $itemtype, 0, 0);
                             $a_input['state'] = 1;
                         }
                     }
                 }
             } else {
                 // add taskjobstate
                 $count_device_subnet = 0;
                 if (isset($a_devicesubnet[$subnet]['NetworkEquipment'])) {
                     $count_device_subnet += count($a_devicesubnet[$subnet]['NetworkEquipment']);
                 }
                 if (isset($a_devicesubnet[$subnet]['Printer'])) {
                     $count_device_subnet += count($a_devicesubnet[$subnet]['Printer']);
                 }
                 $nb_devicebyagent = ceil($count_device_subnet / count($a_agentList));
                 $nbagent = 0;
                 $agent_id = array_pop($a_agentList);
                 $a_input['state'] = 0;
                 for ($i = 0; $i < 2; $i++) {
                     $itemtype = 'Printer';
                     if ($i == '0') {
                         $itemtype = 'NetworkEquipment';
                     }
                     if (isset($a_devicesubnet[$subnet][$itemtype])) {
                         foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id => $num) {
                             $a_input['itemtype'] = $itemtype;
                             $a_input['items_id'] = $items_id;
                             $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE'][$itemtype . $items_id]);
                             if ($nbagent == $nb_devicebyagent) {
                                 $agent_id = array_pop($a_agentList);
                                 $nbagent = 0;
                             }
                             $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                             $nbagent++;
                             $taskvalid++;
                             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                             //Add log of taskjob
                             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                             $a_input['state'] = 7;
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $pfTaskjoblog->add($a_input);
                             unset($a_input['state']);
                             $a_input['plugin_fusioninventory_agents_id'] = 0;
                             $a_input['state'] = 0;
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                             }
                         }
                     }
                 }
             }
         }
         if ($taskvalid == "0") {
             $pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
         }
     } else {
         $a_agentList = array();
         // *** Only agents not dynamic ***
         if (!strstr($pfTaskjob->fields['action'], '".1"') and !strstr($pfTaskjob->fields['action'], '".2"')) {
             $agent_require_model = 0;
             foreach ($a_actions as $a_action) {
                 if (!in_array('.1', $a_action) and !in_array('.2', $a_action)) {
                     $agent_id = current($a_action);
                     if ($pfAgent->getFromDB($agent_id)) {
                         $agent_version = $pfAgent->getAgentVersion($agent_id);
                         if (strnatcmp($agent_version, '2.3.4') < 0) {
                             $agent_require_model = 1;
                         }
                         if ($communication == 'pull') {
                             $a_agentList[] = $agent_id;
                         } else {
                             if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
                                 $a_agentList[] = $agent_id;
                             }
                         }
                     }
                 }
             }
         } else {
             if (strstr($pfTaskjob->fields['action'], '".1"')) {
                 $a_agentList = $this->getAgentsSubnet($count_device, $communication);
             }
         }
         /*
          * Manage agents
          */
         if (count($a_agentList) == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = '';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $a_input['execution_id'] = $task->fields['execution_id'];
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 1, "Unable to find agent to run this job");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 0;
             $pfTaskjob->update($input_taskjob);
         } elseif ($count_device == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = '';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 0, "No suitable devices to inventory");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         } else {
             foreach ($a_agentList as $agent_id) {
                 //Add jobstate and put status (waiting on server = 0)
                 $a_input = array();
                 $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                 $a_input['state'] = 0;
                 $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                 $a_input['uniqid'] = $uniqid;
                 $a_input['execution_id'] = $task->fields['execution_id'];
                 $alternate = 0;
                 for ($d = 0; $d < ceil($count_device / count($a_agentList)); $d++) {
                     if (count($a_NetworkEquipment) + count($a_Printer) > 0) {
                         $getdevice = "NetworkEquipment";
                         if ($alternate == "1") {
                             $getdevice = "Printer";
                             $alternate = 0;
                         } else {
                             $getdevice = "NetworkEquipment";
                             $alternate++;
                         }
                         if (count($a_NetworkEquipment) == '0') {
                             $getdevice = "Printer";
                         } else {
                             if (count($a_Printer) == '0') {
                                 $getdevice = "NetworkEquipment";
                             }
                         }
                         $a_input['itemtype'] = $getdevice;
                         switch ($getdevice) {
                             case 'NetworkEquipment':
                                 $a_input['items_id'] = array_pop($a_NetworkEquipment);
                                 $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE']['NetworkEquipment' . $a_input['items_id']]);
                                 break;
                             case 'Printer':
                                 $a_input['items_id'] = array_pop($a_Printer);
                                 $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE']['Printer' . $a_input['items_id']]);
                                 break;
                         }
                         $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                         //Add log of taskjob
                         $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                         $a_input['state'] = 7;
                         $a_input['date'] = date("Y-m-d H:i:s");
                         $pfTaskjoblog->add($a_input);
                         unset($a_input['state']);
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                         }
                     }
                 }
             }
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             $input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         }
     }
     return $uniqid;
 }
コード例 #17
0
 /**
  * Get days durations including all segments of the current calendar
  *
  * @return end date
  **/
 function getDurationsCache()
 {
     if (!isset($this->fields['id'])) {
         return false;
     }
     $cache_duration = importArrayFromDB($this->fields['cache_duration']);
     // Invalid cache duration : recompute it
     if (!isset($cache_duration[0])) {
         $this->updateDurationCache($this->fields['id']);
         $cache_duration = importArrayFromDB($this->fields['cache_duration']);
     }
     return $cache_duration;
 }
コード例 #18
0
 /**
  * Check if security key in ajax page is same than kay of DB
  */
 function isSecure()
 {
     return;
     if (isset($_POST['sess_id'])) {
         $a_data = $this->find("`users_id`='" . $_SESSION['glpiID'] . "'" . " AND `session_id`='" . $_POST['sess_id'] . "'", '', 1);
         if (count($a_data) == 1) {
             $data = current($a_data);
             if (isset($_SESSION['plugin_monitoring_securekey']) && $_SESSION['plugin_monitoring_securekey'] == $data['key']) {
                 $checktime = 0;
                 if (isset($_SESSION['plugin_monitoring_checktime'])) {
                     $checktime = $_SESSION['plugin_monitoring_checktime'];
                 }
                 $_SESSION = importArrayFromDB($data['session']);
                 if ($checktime != 0) {
                     $_SESSION['plugin_monitoring_checktime'] = $checktime;
                 }
                 $this->updateSecurity();
                 // It's ok
                 return;
             }
         }
     }
     echo "Error, security key not valid!";
     exit;
 }
コード例 #19
0
ファイル: commonglpi.class.php プロジェクト: korial29/glpi
 /**
  * Load display options to $_SESSION
  *
  * @since version 0.84
  *
  * @param $sub_itemtype  string   sub itemtype if needed (default '')
  *
  * @return nothing
  **/
 static function getDisplayOptions($sub_itemtype = '')
 {
     if (!isset($_SESSION['glpi_display_options'])) {
         // Load display_options from user table
         $_SESSION['glpi_display_options'] = array();
         if ($uid = Session::getLoginUserID()) {
             $user = new User();
             if ($user->getFromDB($uid)) {
                 $_SESSION['glpi_display_options'] = importArrayFromDB($user->fields['display_options']);
             }
         }
     }
     if (!isset($_SESSION['glpi_display_options'][self::getType()])) {
         $_SESSION['glpi_display_options'][self::getType()] = array();
     }
     if (!empty($sub_itemtype)) {
         if (!isset($_SESSION['glpi_display_options'][self::getType()][$sub_itemtype])) {
             $_SESSION['glpi_display_options'][self::getType()][$sub_itemtype] = array();
         }
         $display_options =& $_SESSION['glpi_display_options'][self::getType()][$sub_itemtype];
     } else {
         $display_options =& $_SESSION['glpi_display_options'][self::getType()];
     }
     // Load default values if not set
     $options = static::getAvailableDisplayOptions();
     if (count($options)) {
         foreach ($options as $option_group_name => $option_group) {
             foreach ($option_group as $option_name => $attributs) {
                 if (!isset($display_options[$option_name])) {
                     $display_options[$option_name] = $attributs['default'];
                 }
             }
         }
     }
     return $display_options;
 }
コード例 #20
0
 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>";
 }
コード例 #21
0
 function run($jobstate)
 {
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
     $pfToolbox = new PluginFusioninventoryToolbox();
     $pfAgent->getFromDB($jobstate->fields['plugin_fusioninventory_agents_id']);
     $sxml_option = $this->message->addChild('OPTION');
     $sxml_option->addChild('NAME', 'NETDISCOVERY');
     $a_versions = importArrayFromDB($pfAgent->fields["version"]);
     // * Disabled by David Durieux, I think it's not required now * //
     //      if (((isset($a_versions["NETWORKDISCOVERY"])) AND ($a_versions["NETWORKDISCOVERY"] >= 1.3))
     //              OR !isset($a_versions["NETWORKDISCOVERY"])) {
     //         if (!file_exists(GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml")) {
     //            PluginFusioninventorySnmpmodelImportExport::exportDictionnaryFile(FALSE);
     //         }
     //         $sxml_option->addChild('DICOHASH',
     //                                md5_file(GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml"));
     //      }
     //      if (($pfAgent->fields["senddico"] == "1")) {
     //
     //         if (((isset($a_versions["NETWORKDISCOVERY"]))
     //                 AND ($a_versions["NETWORKDISCOVERY"] >= 1.3))) {
     //
     //            $sxml_option->addChild('DICO',
     //                                   file_get_contents(
     //                                           GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml"));
     //         }
     //         $input = array();
     //         $input['id'] = $pfAgent->fields['id'];
     //         $input["senddico"] = "0";
     //         $pfAgent->update($input);
     //      }
     $sxml_param = $sxml_option->addChild('PARAM');
     $sxml_param->addAttribute('THREADS_DISCOVERY', $pfAgent->fields["threads_networkdiscovery"]);
     $sxml_param->addAttribute('TIMEOUT', $pfAgent->fields["timeout_networkdiscovery"]);
     $sxml_param->addAttribute('PID', $jobstate->fields['id']);
     $changestate = 0;
     //foreach ($a_Taskjobstates as $taskjobstate) {
     $taskjobstatedatas = $jobstate->fields;
     $sxml_rangeip = $sxml_option->addChild('RANGEIP');
     $pfTaskjob->getFromDB($taskjobstatedatas['plugin_fusioninventory_taskjobs_id']);
     $pfTaskjobstate->getFromDB($taskjobstatedatas['id']);
     $pfIPRange->getFromDB($taskjobstatedatas['items_id']);
     $sxml_rangeip->addAttribute('ID', $pfIPRange->fields['id']);
     if (!is_null($pfTaskjobstate->fields['specificity'])) {
         $a_split = explode("-", $pfTaskjobstate->fields['specificity']);
         $first_ip = $pfIPRange->getIp2long($pfIPRange->fields["ip_start"]);
         $last_ip = long2ip($first_ip + $a_split[1]);
         $first_ip = long2ip($first_ip + $a_split[0]);
         if ($first_ip != '0.0.0.0' && $last_ip != '0.0.0.0') {
             $sxml_rangeip->addAttribute('IPSTART', $first_ip);
             $sxml_rangeip->addAttribute('IPEND', $last_ip);
         }
     } else {
         $sxml_rangeip->addAttribute('IPSTART', $pfIPRange->fields["ip_start"]);
         $sxml_rangeip->addAttribute('IPEND', $pfIPRange->fields["ip_end"]);
     }
     $sxml_rangeip->addAttribute('ENTITY', $pfIPRange->fields["entities_id"]);
     if ($changestate == '0') {
         $pfTaskjobstate->changeStatus($pfTaskjobstate->fields['id'], 1);
         $pfTaskjoblog->addTaskjoblog($pfTaskjobstate->fields['id'], '0', 'PluginFusioninventoryAgent', '1', $pfAgent->fields["threads_networkdiscovery"] . ' threads', $pfAgent->fields["timeout_networkdiscovery"] . ' timeout');
         $changestate = $pfTaskjobstate->fields['id'];
     } else {
         $pfTaskjobstate->changeStatusFinish($pfTaskjobstate->fields['id'], $taskjobstatedatas['items_id'], $taskjobstatedatas['itemtype'], 0, "Merged with " . $changestate);
     }
     //}
     $pfIPRange_ConfigSecurity = new PluginFusioninventoryIPRange_ConfigSecurity();
     $a_auths = $pfIPRange_ConfigSecurity->find("`plugin_fusioninventory_ipranges_id`='" . $pfIPRange->fields['id'] . "'", "rank");
     foreach ($a_auths as $dataAuth) {
         $pfToolbox->addAuth($sxml_option, $dataAuth['plugin_fusioninventory_configsecurities_id']);
     }
     return $this->message;
 }
コード例 #22
0
 /**
  * Display form for agent configuration
  *
  * @param $items_id integer ID
  * @param $options array
  *
  *@return bool true if form is ok
  *
  **/
 function showForm($items_id, $options = array(), $copy = array())
 {
     global $DB, $CFG_GLPI;
     if (count($copy) > 0) {
         foreach ($copy as $key => $value) {
             $this->fields[$key] = stripslashes($value);
         }
     }
     $this->initForm($items_id, $options);
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Name') . " :</td>";
     echo "<td>";
     echo "<input type='text' name='name' value='" . $this->fields["name"] . "' size='30'/>";
     echo "</td>";
     echo "<td>" . __('Command name', 'monitoring') . "&nbsp;:</td>";
     echo "<td>";
     echo "<input type='text' name='command_name' value='" . $this->fields["command_name"] . "' size='30'/>";
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Active ?', 'monitoring') . "</td>";
     echo "<td>";
     if (self::canCreate()) {
         Dropdown::showYesNo('is_active', $this->fields['is_active']);
     } else {
         echo Dropdown::getYesNo($this->fields['is_active']);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Module type', 'monitoring') . " :</td>";
     echo "<td>";
     echo "<input type='text' name='module_type' value='" . $this->fields["module_type"] . "' size='30'/>";
     echo "</td>";
     echo "<td>" . __('Poller tag', 'monitoring') . "&nbsp;:</td>";
     echo "<td>";
     echo "<input type='text' name='poller_tag' value='" . $this->fields["poller_tag"] . "' size='30'/>";
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Command line', 'monitoring') . "&nbsp;:</td>";
     echo "<td colspan='3'>";
     echo '<input type="text" name="command_line" value="' . htmlspecialchars($this->fields["command_line"]) . '" size="97"/>';
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Arguments description', 'monitoring') . "&nbsp;:</td>";
     echo "<td colspan='3'>";
     $arguments = array();
     preg_match_all("/\\\$(ARG\\d+)\\\$/", $this->fields['command_line'], $arguments);
     $arrayargument = importArrayFromDB($this->fields["arguments"]);
     echo "<table>";
     foreach ($arguments[0] as $adata) {
         $adata = str_replace('$', '', $adata);
         echo "<tr>";
         echo "<td>";
         echo " " . $adata . " : ";
         echo "</td>";
         echo "<td>";
         if (!isset($arrayargument[$adata])) {
             $arrayargument[$adata] = '';
         }
         echo "<textarea cols='90' rows='2' name='argument_" . $adata . "' >" . $arrayargument[$adata] . "</textarea>";
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
     echo "</td>";
     echo "</tr>";
     $this->showFormButtons($options);
     // Add form for copy item
     if ($items_id != '' && Session::haveRight("config", UPDATE)) {
         $this->fields['id'] = 0;
         $this->showFormHeader($options);
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='4' class='center'>";
         foreach ($this->fields as $key => $value) {
             if ($key != 'id') {
                 echo "<input type='hidden' name='" . $key . "' value='" . $value . "'/>";
             }
         }
         echo "<input type='submit' name='copy' value=\"" . __('copy', 'monitoring') . "\" class='submit'>";
         echo "</td>";
         echo "</tr>";
         echo "</table>";
         Html::closeForm();
     }
     return true;
 }
コード例 #23
0
 /**
  * Display form for agent configuration
  *
  * @param $items_id integer ID 
  * @param $options array
  *
  *@return bool true if form is ok
  *
  **/
 function showForm($items_id, $options = array(), $copy = array())
 {
     global $DB, $CFG_GLPI, $LANG;
     if ($items_id != '') {
         $this->getFromDB($items_id);
     } else {
         $this->getEmpty();
     }
     if (count($copy) > 0) {
         foreach ($copy as $key => $value) {
             $this->fields[$key] = stripslashes($value);
         }
     }
     $this->showTabs($options);
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . $LANG['common'][16] . " :</td>";
     echo "<td>";
     echo "<input type='text' name='name' value='" . $this->fields["name"] . "' size='30'/>";
     echo "</td>";
     echo "<td>" . $LANG['plugin_monitoring']['command'][2] . "&nbsp;:</td>";
     echo "<td>";
     echo "<input type='text' name='command_name' value='" . $this->fields["command_name"] . "' size='30'/>";
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . $LANG['plugin_monitoring']['command'][3] . "&nbsp;:</td>";
     echo "<td colspan='3'>";
     echo "<input type='text' name='command_line' value='" . $this->fields["command_line"] . "' size='97'/>";
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . $LANG['plugin_monitoring']['command'][4] . "&nbsp;:</td>";
     echo "<td colspan='3'>";
     $arguments = array();
     preg_match_all("/\\\$(ARG\\d+)\\\$/", $this->fields['command_line'], $arguments);
     $arrayargument = importArrayFromDB($this->fields["arguments"]);
     echo "<table>";
     foreach ($arguments[0] as $adata) {
         $adata = str_replace('$', '', $adata);
         echo "<tr>";
         echo "<td>";
         echo " " . $adata . " : ";
         echo "</td>";
         echo "<td>";
         if (!isset($arrayargument[$adata])) {
             $arrayargument[$adata] = '';
         }
         echo "<textarea cols='90' rows='2' name='argument_" . $adata . "' >" . $arrayargument[$adata] . "</textarea>";
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
     echo "</td>";
     echo "</tr>";
     $this->showFormButtons($options);
     // Add form for copy item
     if ($items_id != '') {
         $this->fields['id'] = 0;
         $this->showFormHeader($options);
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='4' class='center'>";
         foreach ($this->fields as $key => $value) {
             if ($key != 'id') {
                 echo "<input type='hidden' name='" . $key . "' value='" . $value . "'/>";
             }
         }
         echo "<input type='submit' name='copy' value=\"" . $LANG['setup'][283] . "\" class='submit'>";
         echo "</td>";
         echo "</tr>";
         echo "</table>";
         echo "</form>";
     }
     return true;
 }
コード例 #24
0
ファイル: config.php プロジェクト: jose-martins/glpi
             $current_config = Config::getConfigurationValues('core');
         } else {
             $current_config = $config_object->fields;
         }
     } else {
         // Manage glpi_config table before 0.80
         $config_object->forceTable('glpi_config');
         if ($config_object->getFromDB(1)) {
             $current_config = $config_object->fields;
         }
     }
 }
 if (count($current_config) > 0) {
     $CFG_GLPI = array_merge($CFG_GLPI, $current_config);
     if (isset($CFG_GLPI['priority_matrix'])) {
         $CFG_GLPI['priority_matrix'] = importArrayFromDB($CFG_GLPI['priority_matrix'], true);
     }
     // Path for icon of document type (web mode only)
     if (isset($CFG_GLPI["root_doc"])) {
         $CFG_GLPI["typedoc_icon_dir"] = $CFG_GLPI["root_doc"] . "/pics/icones";
     }
 } else {
     echo "Error accessing config table";
     exit;
 }
 if (isCommandLine() && isset($_SERVER['argv'])) {
     $key = array_search('--debug', $_SERVER['argv']);
     if ($key) {
         $_SESSION['glpi_use_mode'] = Session::DEBUG_MODE;
         unset($_SERVER['argv'][$key]);
         $_SERVER['argv'] = array_values($_SERVER['argv']);
コード例 #25
0
ファイル: profile.class.php プロジェクト: glpi-project/glpi
 /**
  * Unset unused rights for helpdesk
  **/
 function cleanProfile()
 {
     if ($this->fields["interface"] == "helpdesk") {
         foreach ($this->fields as $key => $val) {
             if (!in_array($key, self::$common_fields) && !in_array($key, self::$helpdesk_rights)) {
                 unset($this->fields[$key]);
             }
         }
     }
     // decode array
     if (isset($this->fields["helpdesk_item_type"]) && !is_array($this->fields["helpdesk_item_type"])) {
         $this->fields["helpdesk_item_type"] = importArrayFromDB($this->fields["helpdesk_item_type"]);
     }
     // Empty/NULL case
     if (!isset($this->fields["helpdesk_item_type"]) || !is_array($this->fields["helpdesk_item_type"])) {
         $this->fields["helpdesk_item_type"] = array();
     }
     // Decode status array
     $fields_to_decode = array('ticket_status', 'problem_status', 'change_status');
     foreach ($fields_to_decode as $val) {
         if (isset($this->fields[$val]) && !is_array($this->fields[$val])) {
             $this->fields[$val] = importArrayFromDB($this->fields[$val]);
             // Need to be an array not a null value
             if (is_null($this->fields[$val])) {
                 $this->fields[$val] = array();
             }
         }
     }
 }
コード例 #26
0
   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>";
   }
コード例 #27
0
 /**
  * Get lock fields for a record.
  *
  * @param $p_itemtype Table id.
  * @param $p_items_id Line id.
  * TODO:  check rights
  *
  *@return array of locked fields
  **/
 static function getLockFields($p_itemtype, $p_items_id)
 {
     global $DB;
     $db_lock = $DB->fetch_assoc(PluginFusioninventoryLock::getLock($p_itemtype, $p_items_id));
     $lock_fields = $db_lock["fields"];
     $lock = importArrayFromDB($lock_fields);
     return $lock;
 }
コード例 #28
0
ファイル: display.class.php プロジェクト: geldarr/hack-space
 function displayGraphs($itemtype, $items_id)
 {
     global $CFG_GLPI;
     $pmComponent = new PluginMonitoringComponent();
     $pmConfig = new PluginMonitoringConfig();
     $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host();
     $item = new $itemtype();
     $item->getFromDB($items_id);
     $pmComponent->getFromDB($item->fields['plugin_monitoring_components_id']);
     if (!isset($_SESSION['glpi_plugin_monitoring']['perfname'][$pmComponent->fields['id']])) {
         PluginMonitoringServicegraph::loadPreferences($pmComponent->fields['id']);
     }
     $css_width = '950';
     if (isset($_GET['mobile'])) {
         $css_width = '300';
     }
     echo "<table class='tab_cadre' width='" . $css_width . "'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     $title = Dropdown::getDropdownName(getTableForItemType('PluginMonitoringComponent'), $item->fields['plugin_monitoring_components_id']);
     $title .= ' ' . __('on', 'monitoring') . ' ';
     $pmComponentscatalog_Host->getFromDB($item->fields["plugin_monitoring_componentscatalogs_hosts_id"]);
     if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') {
         $itemtype2 = $pmComponentscatalog_Host->fields['itemtype'];
         $item2 = new $itemtype2();
         $item2->getFromDB($pmComponentscatalog_Host->fields['items_id']);
         $title .= str_replace("'", "\"", $item2->getLink() . " (" . $item2->getTypeName() . ")");
     }
     echo $title;
     echo "</th>";
     echo "<th width='200'>";
     if (!isset($_GET['mobile'])) {
         echo "<form method='post'>";
         $a_timezones = PluginMonitoringConfig::getTimezones();
         if (!isset($_SESSION['plugin_monitoring_timezone'])) {
             $_SESSION['plugin_monitoring_timezone'] = '0';
         }
         $a_timezones_allowed = array();
         $pmConfig->getFromDB(1);
         $a_temp = importArrayFromDB($pmConfig->fields['timezones']);
         foreach ($a_temp as $key) {
             $a_timezones_allowed[$key] = $a_timezones[$key];
         }
         if (count($a_timezones_allowed) == '0') {
             $a_timezones_allowed['0'] = $a_timezones['0'];
         }
         Dropdown::showFromArray('plugin_monitoring_timezone', $a_timezones_allowed, array('value' => $_SESSION['plugin_monitoring_timezone']));
         echo "&nbsp;<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>";
         Html::closeForm();
     }
     echo "</th>";
     echo "</tr>";
     $timezone = '0';
     if (isset($_SESSION['plugin_monitoring_timezone'])) {
         $timezone = $_SESSION['plugin_monitoring_timezone'];
     }
     if (!isset($_GET['mobile'])) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo "<div id='legendlink'><a onClick='Ext.get(\"options\").toggle();'>[ Options ]</a></div>";
         echo "</th>";
         echo "</tr>";
         // * Display perfname
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         echo "<div id='options' style='display:none'>";
         PluginMonitoringServicegraph::preferences($pmComponent->fields['id'], 0);
         echo "</div>";
         echo "</td>";
         echo "</tr>";
         // * Display date slider
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo __('Select date (only last 2, 12 and 24 hours)', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         $end = time();
         $oldvalue = current(getAllDatasFromTable('glpi_plugin_monitoring_serviceevents', "`plugin_monitoring_services_id`='" . $items_id . "'", false, 'date ASC LIMIT 1'));
         $date = new DateTime($oldvalue['date']);
         $start = $date->getTimestamp();
         $pmServicegraph = new PluginMonitoringServicegraph();
         echo "\n<script type=\"text/javascript\">\n\nExt.onReady(function(){\n\n    var tip = new Ext.slider.Tip({\n        getText: function(thumb){\n            return String.format('<b> ' + new Date(thumb.value * 1000).format('Y-m-d') + '</b>');\n        }\n    });\n\n    new Ext.Slider({\n        renderTo: 'custom-tip-slider',\n        width: 940,\n        increment: 86400,\n        minValue: " . $start . ",\n        maxValue: " . $end . ",\n        value: " . $end . ",\n        plugins: tip,\n        listeners: {\n            dragend: function(slider, thumb, value){\n               document.getElementById('custom_date').textContent = slider.getValue();\n               mgr" . $items_id . "2h.stopAutoRefresh();\n               mgr" . $items_id . "12h.stopAutoRefresh();\n               mgr" . $items_id . "1d.stopAutoRefresh();\n                  ";
         $a_graphlist = array('2h', '12h', '1d');
         foreach ($a_graphlist as $time) {
             $pmServicegraph->startAutoRefresh($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $pmComponent->fields['id']);
         }
         echo "\n            }\n        }\n    });\n\n});\n</script>";
         echo '<center><div id="custom-tip-slider"></div></center>';
         echo '<div id="custom_date" style="display:none"></div>';
         echo "</td>";
         echo "</tr>";
         // * Display time slider
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo __('Select time (only last 2, 12 and 24 hours)', 'monitoring');
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2'>";
         $start = 0 + 86400 - 3600;
         $end = 86400 + 86400 - 3600 - 300;
         $current = mktime(date('H'), date('i'), 0, 1, 2, 1970);
         echo "\n<script type=\"text/javascript\">\n\nExt.onReady(function(){\n\n    var tiptime = new Ext.slider.Tip({\n        getText: function(thumb){\n            return String.format('<b> ' + new Date(thumb.value * 1000).format('H:i:s') + '</b>');\n        }\n    });\n\n    new Ext.Slider({\n        renderTo: 'custom-tip-slider-time',\n        width: 940,\n        increment: 300,\n        minValue: " . $start . ",\n        maxValue: " . $end . ",\n        value: " . $current . ",\n        plugins: tiptime,\n        listeners: {\n            dragend: function(slider, thumb, value){\n               document.getElementById('custom_time').textContent = slider.getValue();\n               mgr" . $items_id . "2h.stopAutoRefresh();\n               mgr" . $items_id . "12h.stopAutoRefresh();\n               mgr" . $items_id . "1d.stopAutoRefresh();\n                  ";
         $a_graphlist = array('2h', '12h', '1d');
         foreach ($a_graphlist as $time) {
             $pmServicegraph->startAutoRefresh($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $pmComponent->fields['id']);
         }
         echo "\n            }\n        }\n    });\n});\n</script>";
         echo '<center><div id="custom-tip-slider-time"></div></center>';
         echo '<div id="custom_time" style="display:none"></div>';
         echo "</td>";
         echo "</tr>";
     }
     $a_list = array();
     $a_list["2h"] = __("Last 2 hours", "monitoring");
     $a_list["12h"] = __("Last 12 hours", "monitoring");
     $a_list["1d"] = __("Last 24 hours", "monitoring");
     if (!isset($_GET['mobile'])) {
         $a_list["1w"] = __("Last 7 days (average)", "monitoring");
         $a_list["1m"] = __("Last month (average)", "monitoring");
         $a_list["0y6m"] = __("Last 6 months (average)", "monitoring");
         $a_list["1y"] = __("Last year (average)", "monitoring");
     }
     foreach ($a_list as $time => $name) {
         echo "<tr class='tab_bg_1'>";
         echo "<th colspan='2'>";
         echo $name;
         echo "</th>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center' colspan='2'>";
         $pmServicegraph = new PluginMonitoringServicegraph();
         $part = '';
         $width = '950';
         if (isset($_GET['mobile'])) {
             $width = '294';
         }
         $pmServicegraph->displayGraph($pmComponent->fields['graph_template'], $itemtype, $items_id, $timezone, $time, $part, $width);
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
コード例 #29
0
function pluginFusioninventoryUpdate($current_version, $migrationname = 'Migration')
{
    global $DB;
    ini_set("max_execution_time", "0");
    ini_set("memory_limit", "-1");
    foreach (glob(GLPI_ROOT . '/plugins/fusioninventory/inc/*.php') as $file) {
        require_once $file;
    }
    $migration = new $migrationname($current_version);
    $prepare_task = array();
    $prepare_rangeip = array();
    $prepare_Config = array();
    $a_plugin = plugin_version_fusioninventory();
    $plugins_id = PluginFusioninventoryModule::getModuleId($a_plugin['shortname']);
    $migration->displayMessage("Migration Classname : " . $migrationname);
    $migration->displayMessage("Update of plugin FusionInventory");
    /*
     * Check if folders are correctly created
     */
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels');
    }
    /*
     * Deploy folders
     */
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/files')) {
        rename(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/files', GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files');
    }
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/repository')) {
        rename(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/repository', GLPI_PLUGIN_DOC_DIR . '/fusioninventory/repository');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export');
    }
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/upload')) {
        rename(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/upload', GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload');
    }
    /*
     * Rename fileparts without .gz extension (cf #1999)
     */
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files')) {
        $gzfiles = pluginFusioninventoryFindFiles(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files', '/\\.gz$/');
        foreach ($gzfiles as $file) {
            $fileWithoutExt = pathinfo($file, PATHINFO_DIRNAME) . '/' . pathinfo($file, PATHINFO_FILENAME);
            rename($file, $fileWithoutExt);
        }
    }
    unset($gzfiles);
    /*
     *  Rename tables from old version of FuionInventory (2.2.1 for example)
     */
    $migration->renameTable("glpi_plugin_fusioninventory_rangeip", "glpi_plugin_fusioninventory_ipranges");
    $migration->renameTable("glpi_plugin_fusioninventory_lock", "glpi_plugin_fusioninventory_locks");
    $migration->renameTable("glpi_plugin_fusioninventory_unknown_device", "glpi_plugin_fusioninventory_unknowndevices");
    $migration->renameTable("glpi_plugin_fusioninventory_config", "glpi_plugin_fusioninventory_configs");
    $migration->renameTable("glpi_plugin_fusioninventory_networking_ports", "glpi_plugin_fusinvsnmp_networkports");
    $migration->renameTable("glpi_plugin_fusioninventory_construct_device", "glpi_plugin_fusinvsnmp_constructdevices");
    $migration->renameTable("glpi_plugin_fusioninventory_construct_mibs", "glpi_plugin_fusioninventory_snmpmodelconstructdevice_miboids");
    $migration->renameTable("glpi_plugin_fusioninventory_networking", "glpi_plugin_fusioninventory_networkequipments");
    $migration->renameTable("glpi_plugin_fusioninventory_networking_ifaddr", "glpi_plugin_fusinvsnmp_networkequipmentips");
    $migration->renameTable("glpi_plugin_fusioninventory_printers", "glpi_plugin_fusinvsnmp_printers");
    $migration->renameTable("glpi_plugin_fusioninventory_printers_cartridges", "glpi_plugin_fusinvsnmp_printercartridges");
    $migration->renameTable("glpi_plugin_fusioninventory_printers_history", "glpi_plugin_fusinvsnmp_printerlogs");
    $migration->renameTable("glpi_plugin_fusioninventory_model_infos", "glpi_plugin_fusioninventory_snmpmodels");
    $migration->renameTable("glpi_plugin_fusioninventory_mib_networking", "glpi_plugin_fusinvsnmp_modelmibs");
    $migration->renameTable("glpi_plugin_fusioninventory_snmp_connection", "glpi_plugin_fusinvsnmp_configsecurities");
    $migration->renameTable("glpi_plugin_fusioninventory_snmp_history", "glpi_plugin_fusinvsnmp_networkportlogs");
    $migration->renameTable("glpi_plugin_fusioninventory_snmp_history_connections", "glpi_plugin_fusinvsnmp_networkportconnectionlogs");
    $a_droptable = array('glpi_plugin_fusioninventory_agents_inventory_state', 'glpi_plugin_fusioninventory_config_modules', 'glpi_plugin_fusioninventory_connection_stats', 'glpi_plugin_fusioninventory_discovery', 'glpi_plugin_fusioninventory_errors', 'glpi_plugin_fusioninventory_lockable', 'glpi_plugin_fusioninventory_connection_history', 'glpi_plugin_fusioninventory_walks', 'glpi_plugin_fusioninventory_config_snmp_history', 'glpi_plugin_fusioninventory_config_snmp_networking', 'glpi_plugin_fusioninventory_task', 'glpi_plugin_fusinvinventory_pcidevices', 'glpi_plugin_fusinvinventory_pcivendors', 'glpi_plugin_fusinvinventory_usbdevices', 'glpi_plugin_fusinvinventory_usbvendors', 'glpi_plugin_fusinvsnmp_constructdevicewalks', 'glpi_plugin_fusioninventory_snmpmodelmiblabels', 'glpi_plugin_fusioninventory_snmpmodelmibobjects', 'glpi_plugin_fusioninventory_snmpmodelmiboids', 'glpi_plugin_fusioninventory_snmpmodelconstructdevices', 'glpi_plugin_fusioninventory_snmpmodelconstructdevicewalks' . 'glpi_plugin_fusioninventory_snmpmodelconstructdevices_users', 'glpi_plugin_fusioninventory_snmpmodelconstructdevice_miboids', 'glpi_plugin_fusioninventory_snmpmodelmibs', 'glpi_plugin_fusioninventory_snmpmodels', 'glpi_plugin_fusioninventory_snmpmodeldevices', 'glpi_plugin_fusinvsnmp_constructdevice_miboids', 'glpi_plugin_fusinvsnmp_constructdevices', 'glpi_plugin_fusinvsnmp_constructdevices_users', 'glpi_plugin_fusinvsnmp_miblabels', 'glpi_plugin_fusinvsnmp_mibobjects', 'glpi_plugin_fusinvsnmp_miboids', 'glpi_plugin_fusinvsnmp_modeldevices', 'glpi_plugin_fusinvsnmp_modelmibs', 'glpi_plugin_fusinvsnmp_models', 'glpi_plugin_fusioninventory_construct_walks');
    foreach ($a_droptable as $newTable) {
        $migration->dropTable($newTable);
    }
    /*
       $a_table = array();
    
       //table name
       $a_table['name'] = '';
       $a_table['oldname'] = array(
       );
    
       // fields : fields that are new, have changed type or just stay the same
       //    array(
       //        <fieldname> = array(
       //            'type' => <type>, 'value' => <value>)
       //    );
       $a_table['fields'] = array(
    
       );
    
       // oldfields = fields that need to be removed
       //    array( 'field0', 'field1', ...);
       $a_table['oldfields'] = array(
       );
    
       // renamefields = fields that need to be renamed
       //    array('oldname' = 'newname', ...)
       $a_table['renamefields'] = array(
       );
    
       // keys : new, changed or not
       //    array( 'field' => <fields>, 'name' => <keyname> , 'type' => <keytype>)
       // <fields> : fieldnames needed by the key
       //            ex : array('field0' , 'field1' ...)
       //            ex : 'fieldname'
       // <keyname> : the name of the key (if blank, the fieldname is used)
       // <type> : the type of key (ex: INDEX, ...)
       $a_table['keys'] = array(
       );
    
       // oldkeys : keys that need to be removed
       //    array( 'key0', 'key1', ... )
       $a_table['oldkeys'] = array(
       );
    */
    //Push task functionnality
    $migration->addField('glpi_plugin_fusioninventory_tasks', 'last_agent_wakeup', 'datetime');
    $migration->addField('glpi_plugin_fusioninventory_tasks', 'wakeup_agent_counter', "int(11) NOT NULL DEFAULT '0'");
    $migration->addField('glpi_plugin_fusioninventory_tasks', 'wakeup_agent_time', "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey('glpi_plugin_fusioninventory_tasks', 'wakeup_agent_counter');
    $migration->migrationOneTable('glpi_plugin_fusioninventory_tasks');
    /*
     *  Table glpi_plugin_fusioninventory_agents
     */
    $newTable = "glpi_plugin_fusioninventory_agents";
    $prepare_agentConfig = array();
    if (TableExists("glpi_plugin_tracker_agents") and FieldExists("glpi_plugin_tracker_agents", "ifaddr_start")) {
        $query = "SELECT * FROM `glpi_plugin_tracker_agents`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $prepare_rangeip[] = array("ip_start" => $data['ifaddr_start'], "ip_end" => $data['ifaddr_end'], "name" => $data['name']);
            $prepare_agentConfig[] = array("name" => $data["name"], "lock" => $data['lock'], "threads_networkinventory" => $data['nb_process_query'], "threads_networkdiscovery" => $data['nb_process_discovery']);
        }
    } else {
        if (TableExists("glpi_plugin_tracker_agents") and FieldExists("glpi_plugin_tracker_agents", "core_discovery")) {
            $query = "SELECT * FROM `glpi_plugin_tracker_agents`";
            $result = $DB->query($query);
            while ($data = $DB->fetch_array($result)) {
                $prepare_agentConfig[] = array("name" => $data["name"], "lock" => $data['lock'], "threads_networkinventory" => $data['threads_query'], "threads_networkdiscovery" => $data['threads_discovery']);
            }
        } else {
            if (TableExists("glpi_plugin_fusioninventory_agents")) {
                if (FieldExists($newTable, "module_snmpquery")) {
                    $query = "SELECT * FROM `glpi_plugin_fusioninventory_agents`";
                    $result = $DB->query($query);
                    while ($data = $DB->fetch_array($result)) {
                        $prepare_agentConfig[] = array("id" => $data["ID"], "threads_networkinventory" => $data['threads_query'], "threads_networkdiscovery" => $data['threads_discovery'], "NETORKINVENTORY" => $data['module_snmpquery'], "NETWORKDISCOVERY" => $data['module_netdiscovery'], "INVENTORY" => $data['module_inventory'], "WAKEONLAN" => $data['module_wakeonlan']);
                    }
                }
            }
        }
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_agents';
    $a_table['oldname'] = array('glpi_plugin_tracker_agents');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => '1');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['last_contact'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['version'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['lock'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['device_id'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['token'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['useragent'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['tag'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['threads_networkdiscovery'] = array('type' => "int(4) NOT NULL DEFAULT '1' COMMENT 'array(xmltag=>value)'", 'value' => NULL);
    $a_table['fields']['threads_networkinventory'] = array('type' => "int(4) NOT NULL DEFAULT '1' COMMENT 'array(xmltag=>value)'", 'value' => NULL);
    $a_table['fields']['senddico'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['timeout_networkdiscovery'] = array('type' => "int(4) NOT NULL DEFAULT '0' COMMENT 'Network Discovery task timeout'", 'value' => NULL);
    $a_table['fields']['timeout_networkinventory'] = array('type' => "int(4) NOT NULL DEFAULT '0' COMMENT 'Network Inventory task timeout'", 'value' => NULL);
    $a_table['fields']['agent_port'] = array('type' => 'varchar(6)', 'value' => NULL);
    $a_table['oldfields'] = array('module_snmpquery', 'module_netdiscovery', 'module_inventory', 'module_wakeonlan', 'core_discovery', 'threads_discovery', 'core_query', 'threads_query', 'tracker_agent_version', 'logs', 'fragment', 'itemtype', 'device_type');
    $a_table['renamefields'] = array();
    $a_table['renamefields']['ID'] = 'id';
    $a_table['renamefields']['last_agent_update'] = 'last_contact';
    $a_table['renamefields']['fusioninventory_agent_version'] = 'version';
    $a_table['renamefields']['key'] = 'device_id';
    $a_table['renamefields']['on_device'] = 'computers_id';
    $a_table['renamefields']['items_id'] = 'computers_id';
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'device_id', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'computers_id', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array('key');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_agentmodules
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_agentmodules';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['modulename'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['is_active'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['exceptions'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['oldfields'][] = 'plugins_id';
    $a_table['oldfields'][] = 'entities_id';
    $a_table['oldfields'][] = 'url';
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'modulename', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array('unicity', 'entities_id');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Add Deploy module
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='DEPLOY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $query_ins = "INSERT INTO `glpi_plugin_fusioninventory_agentmodules`\n            (`modulename`, `is_active`, `exceptions`)\n         VALUES ('DEPLOY', '0', '" . exportArrayToDB(array()) . "')";
        $DB->query($query_ins);
    }
    /*
     * Add WakeOnLan module appear in version 2.3.0
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='WAKEONLAN'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $query_ins = "INSERT INTO `glpi_plugin_fusioninventory_agentmodules`\n            (`modulename`, `is_active`, `exceptions`)\n         VALUES ('WAKEONLAN', '0', '" . exportArrayToDB(array()) . "')";
        $DB->query($query_ins);
    }
    /*
     * Add SNMPQUERY module if not present
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules`\n      SET `modulename`='NETWORKINVENTORY'\n      WHERE `modulename`='SNMPQUERY'";
    $DB->query($query);
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='NETWORKINVENTORY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['modulename'] = "NETWORKINVENTORY";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Add NETDISCOVERY module if not present
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules`\n      SET `modulename`='NETWORKDISCOVERY'\n      WHERE `modulename`='NETDISCOVERY'";
    $DB->query($query);
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='NETWORKDISCOVERY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['modulename'] = "NETWORKDISCOVERY";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Add INVENTORY module if not present
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='INVENTORY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['modulename'] = "INVENTORY";
        $input['is_active'] = 1;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Table glpi_plugin_fusioninventory_configs
     */
    $newTable = "glpi_plugin_fusioninventory_configs";
    if (TableExists('glpi_plugin_tracker_config')) {
        if (FieldExists('glpi_plugin_tracker_config', 'ssl_only')) {
            $query = "SELECT * FROM `glpi_plugin_tracker_config`\n               LIMIT 1";
            $result = $DB->query($query);
            if ($DB->numrows($result) > 0) {
                $data = $DB->fetch_assoc($result);
                $prepare_Config['ssl_only'] = $data['ssl_only'];
            }
        }
        //         $query = "SELECT *  FROM `glpi_plugin_tracker_config`
        //            WHERE `type`='version'
        //            LIMIT 1, 10";
        //         $result=$DB->query($query);
        //         while ($data=$DB->fetch_array($result)) {
        //            $DB->query("DELETE FROM `glpi_plugin_tracker_config`
        //               WHERE `ID`='".$data['ID']."'");
        //         }
    }
    if (TableExists('glpi_plugin_fusioninventory_configs')) {
        $id = 'id';
        if (FieldExists('glpi_plugin_fusioninventory_configs', 'ID')) {
            $id = 'ID';
        }
        $query = "SELECT *  FROM `glpi_plugin_fusioninventory_configs`\n            WHERE `type`='version'\n            LIMIT 1, 10";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $DB->query("DELETE FROM `glpi_plugin_fusioninventory_configs`\n               WHERE `" . $id . "`='" . $data[$id] . "'");
        }
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_configs';
    $a_table['oldname'] = array('glpi_plugin_tracker_config');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['type'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['oldfields'][] = 'version';
    $a_table['oldfields'][] = 'URL_agent_conf';
    $a_table['oldfields'][] = 'ssl_only';
    $a_table['oldfields'][] = 'authsnmp';
    $a_table['oldfields'][] = 'inventory_frequence';
    $a_table['oldfields'][] = 'criteria1_ip';
    $a_table['oldfields'][] = 'criteria1_name';
    $a_table['oldfields'][] = 'criteria1_serial';
    $a_table['oldfields'][] = 'criteria1_macaddr';
    $a_table['oldfields'][] = 'criteria2_ip';
    $a_table['oldfields'][] = 'criteria2_name';
    $a_table['oldfields'][] = 'criteria2_serial';
    $a_table['oldfields'][] = 'criteria2_macaddr';
    $a_table['oldfields'][] = 'delete_agent_process';
    $a_table['oldfields'][] = 'activation_history';
    $a_table['oldfields'][] = 'activation_connection';
    $a_table['oldfields'][] = 'activation_snmp_computer';
    $a_table['oldfields'][] = 'activation_snmp_networking';
    $a_table['oldfields'][] = 'activation_snmp_peripheral';
    $a_table['oldfields'][] = 'activation_snmp_phone';
    $a_table['oldfields'][] = 'activation_snmp_printer';
    $a_table['oldfields'][] = 'plugins_id';
    $a_table['oldfields'][] = 'module';
    $a_table['renamefields'] = array();
    $a_table['renamefields']['ID'] = 'id';
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => array("type"), 'name' => 'unicity', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_entities
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_entities';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['transfers_id_auto'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['agent_base_url'] = array('type' => 'string', 'value' => '');
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => array('entities_id', 'transfers_id_auto'), 'name' => 'entities_id', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    if (countElementsInTable($a_table['name']) == 0) {
        $a_configs = getAllDatasFromTable('glpi_plugin_fusioninventory_configs', "`type`='transfers_id_auto'");
        $transfers_id_auto = 0;
        if (count($a_configs) > 0) {
            $a_config = current($a_configs);
            $transfers_id_auto = $a_config['value'];
        }
        $a_configs = getAllDatasFromTable('glpi_plugin_fusioninventory_configs', "`type`='agent_base_url'");
        $agent_base_url = '';
        if (count($a_configs) > 0) {
            $a_config = current($a_configs);
            $agent_base_url = $a_config['value'];
        }
        $DB->query("INSERT INTO `glpi_plugin_fusioninventory_entities`\n               (`entities_id`, `transfers_id_auto`, `agent_base_url`)\n            VALUES ('0', '" . $transfers_id_auto . "', '" . $agent_base_url . "');");
    } else {
        if (countElementsInTable($a_table['name']) > 0) {
            $a_configs = getAllDatasFromTable('glpi_plugin_fusioninventory_configs', "`type`='agent_base_url'");
            $agent_base_url = '';
            if (count($a_configs) > 0) {
                $a_config = current($a_configs);
                $agent_base_url = $a_config['value'];
                $DB->query("UPDATE `glpi_plugin_fusioninventory_entities`\n                  SET `agent_base_url` = '" . $agent_base_url . "'\n                  ;");
            }
        }
    }
    /*
     * Table glpi_plugin_fusioninventory_credentials
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_credentials';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['username'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['password'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['itemtype'] = array('type' => 'string', 'value' => "");
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    // Fix itemtype changed in 0.84
    $DB->query("UPDATE `glpi_plugin_fusioninventory_credentials`\n         SET `itemtype`='PluginFusioninventoryInventoryComputerESX'\n         WHERE `itemtype`='PluginFusinvinventoryVmwareESX'");
    /*
     * Table glpi_plugin_fusioninventory_credentialips
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_credentialips';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_credentials_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['ip'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_ipranges
     */
    $newTable = "glpi_plugin_fusioninventory_ipranges";
    if (TableExists("glpi_plugin_tracker_rangeip")) {
        // Get all data to create task
        $query = "SELECT * FROM `glpi_plugin_tracker_rangeip`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            if ($data['discover'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_tracker_agents'], "ipranges_id" => $data['ID'], "netdiscovery" => "1");
            }
            if ($data['query'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_tracker_agents'], "ipranges_id" => $data['ID'], "snmpquery" => "1");
            }
        }
    }
    if (TableExists("glpi_plugin_fusioninventory_rangeip") and FieldExists("glpi_plugin_fusioninventory_rangeip", "FK_fusioninventory_agents_discover")) {
        // Get all data to create task
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_rangeip`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            if ($data['discover'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_fusioninventory_agents_discover'], "ipranges_id" => $data['ID'], "netdiscovery" => "1");
            }
            if ($data['query'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_fusioninventory_agents_query'], "ipranges_id" => $data['ID'], "snmpquery" => "1");
            }
        }
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_ipranges';
    $a_table['oldname'] = array('glpi_plugin_tracker_rangeip', 'glpi_plugin_fusinvsnmp_ipranges');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => ''), 'name' => array('type' => 'string', 'value' => NULL), 'entities_id' => array('type' => 'integer', 'value' => NULL), 'ip_start' => array('type' => 'string', 'value' => NULL), 'ip_end' => array('type' => 'string', 'value' => NULL));
    $a_table['oldfields'] = array('FK_tracker_agents', 'discover', 'query', 'FK_fusioninventory_agents_discover', 'FK_fusioninventory_agents_query', 'construct_device_id', 'log', 'comment');
    $a_table['renamefields'] = array('ID' => 'id', 'ifaddr_start' => 'ip_start', 'ifaddr_end' => 'ip_end', 'FK_entities' => 'entities_id');
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'INDEX'));
    $a_table['oldkeys'] = array('FK_tracker_agents', 'FK_tracker_agents_2');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_locks
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_locks';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['tablename'] = array('type' => "varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT ''", 'value' => NULL);
    $a_table['fields']['items_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['tablefields'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array('itemtype');
    $a_table['renamefields'] = array();
    $a_table['renamefields']['fields'] = 'tablefields';
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'tablename', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'items_id', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_ipranges_configsecurities
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_ipranges_configsecurities';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['plugin_fusioninventory_ipranges_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_configsecurities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['rank'] = array('type' => 'integer', 'value' => '1');
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_mappings
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_mappings';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['itemtype'] = array('type' => "varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL", 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['table'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['tablefield'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['locale'] = array('type' => "int(4) NOT NULL DEFAULT '0'", 'value' => NULL);
    $a_table['fields']['shortlocale'] = array('type' => 'int(4) DEFAULT NULL', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'itemtype', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'table', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'tablefield', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    pluginFusioninventoryUpdatemapping();
    if (TableExists('glpi_plugin_fusioninventory_profiles')) {
        /*
         * Table glpi_plugin_fusioninventory_profiles
         */
        $a_table = array();
        $a_table['name'] = 'glpi_plugin_fusioninventory_profiles';
        $a_table['oldname'] = array();
        $a_table['fields'] = array();
        $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
        $a_table['fields']['type'] = array('type' => 'string', 'value' => '');
        $a_table['fields']['right'] = array('type' => 'char', 'value' => NULL);
        $a_table['fields']['plugins_id'] = array('type' => 'integer', 'value' => NULL);
        $a_table['fields']['profiles_id'] = array('type' => 'integer', 'value' => NULL);
        $a_table['oldfields'] = array('name', 'interface', 'is_default', 'snmp_networking', 'snmp_printers', 'snmp_models', 'snmp_authentification', 'rangeip', 'agents', 'remotecontrol', 'agentsprocesses', 'unknowndevices', 'reports', 'deviceinventory', 'netdiscovery', 'snmp_query', 'wol', 'configuration');
        $a_table['renamefields'] = array();
        $a_table['renamefields']['ID'] = 'id';
        $a_table['keys'] = array();
        $a_table['oldkeys'] = array();
        migrateTablesFusionInventory($migration, $a_table);
        // Remove multiple lines can have problem with unicity
        $query = "SELECT * , count(`id`) AS cnt\n               FROM `glpi_plugin_fusioninventory_profiles`\n               GROUP BY `type`,`plugins_id`,`profiles_id`\n               HAVING cnt >1\n               ORDER BY cnt";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $queryd = "DELETE FROM `glpi_plugin_fusioninventory_profiles`\n                  WHERE `type`='" . $data['type'] . "'\n                     AND `plugins_id`='" . $data['plugins_id'] . "'\n                     AND `profiles_id`='" . $data['profiles_id'] . "'\n                  ORDER BY `id` DESC\n                  LIMIT " . ($data['cnt'] - 1) . " ";
            $DB->query($queryd);
        }
        $a_table = array();
        $a_table['name'] = 'glpi_plugin_fusioninventory_profiles';
        $a_table['oldname'] = array();
        $a_table['fields'] = array();
        $a_table['oldfields'] = array();
        $a_table['renamefields'] = array();
        $a_table['keys'] = array();
        $a_table['keys'][] = array('field' => array("type", "plugins_id", "profiles_id"), 'name' => 'unicity', 'type' => 'UNIQUE');
        $a_table['oldkeys'] = array();
        migrateTablesFusionInventory($migration, $a_table);
    }
    /*
     * Update tasks related database tables
     */
    pluginFusioninventoryUpdateTasks($migration, $plugins_id);
    /*
     * Table glpi_plugin_fusioninventory_timeslots
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_timeslots';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => '0');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_timeslotentries
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_timeslotentries';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['plugin_fusioninventory_timeslots_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => '0');
    $a_table['fields']['day'] = array('type' => 'bool', 'value' => 1);
    $a_table['fields']['begin'] = array('type' => 'int(11) DEFAULT NULL', 'value' => NULL);
    $a_table['fields']['end'] = array('type' => 'int(11) DEFAULT NULL', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_unmanageds
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_unmanageds';
    $a_table['oldname'] = array('glpi_plugin_fusioninventory_unknowndevices', 'glpi_plugin_tracker_unknown_device');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['locations_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_deleted'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['users_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['serial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['otherserial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['contact'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['domain'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['item_type'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['accepted'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_agents_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['ip'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['hub'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['states_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['sysdescr'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_configsecurities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_dynamic'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['serialized_inventory'] = array('type' => 'longblob', 'value' => NULL);
    $a_table['oldfields'] = array('dnsname', 'snmp', 'FK_model_infos', 'FK_snmp_connection', 'FK_agent', 'mac', 'ifmac', 'plugin_fusinvsnmp_models_id', 'plugin_fusioninventory_snmpmodels_id', 'is_template');
    $a_table['renamefields'] = array('ID' => 'id', 'comments' => 'comment', 'type' => 'item_type', 'ifaddr' => 'ip', 'FK_entities' => 'entities_id', 'location' => 'locations_id', 'deleted' => 'is_deleted', 'plugin_fusinvsnmp_configsecurities_id' => 'plugin_fusioninventory_configsecurities_id');
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'INDEX'), array('field' => 'plugin_fusioninventory_agents_id', 'name' => '', 'type' => 'INDEX'), array('field' => 'is_deleted', 'name' => '', 'type' => 'INDEX'), array('field' => 'date_mod', 'name' => '', 'type' => 'INDEX'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    if (TableExists('glpi_plugin_fusinvsnmp_unknowndevices')) {
        $query = "SELECT * FROM `glpi_plugin_fusinvsnmp_unknowndevices`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $DB->query("UPDATE `glpi_plugin_fusioninventory_unmanageds`\n               SET `sysdescr`='" . $data['sysdescr'] . "',\n                   `plugin_fusioninventory_configsecurities_id`='" . $data['plugin_fusinvsnmp_configsecurities_id'] . "'\n               WHERE `id`='" . $data['plugin_fusioninventory_unknowndevices_id'] . "'");
        }
        $migration->dropTable('glpi_plugin_fusinvsnmp_unknowndevices');
    }
    /*
     * Table glpi_plugin_fusioninventory_ignoredimportdevices
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_ignoredimportdevices';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['itemtype'] = array('type' => "varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL", 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['ip'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['mac'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['rules_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['method'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['serial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['uuid'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputercriterias
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputercriterias';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_criterias');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_rulematchedlogs
     */
    $newTable = "glpi_plugin_fusioninventory_rulematchedlogs";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "date", "datetime DEFAULT NULL");
    $migration->addField($newTable, "items_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "itemtype", "varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "rules_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_agents_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "method", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerblacklists
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputerblacklists';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_blacklists');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['plugin_fusioninventory_criterium_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'plugin_fusioninventory_criterium_id', 'name' => '', 'type' => 'KEY');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    $DB->list_fields($newTable, FALSE);
    pluginFusioninventorychangeDisplayPreference("5153", "PluginFusioninventoryUnknownDevice");
    pluginFusioninventorychangeDisplayPreference("5158", "PluginFusioninventoryAgent");
    /*
     *  Udpate criteria for blacklist
     */
    $a_criteria = array();
    $a_criteria['Serial number'] = 'ssn';
    $a_criteria['uuid'] = 'uuid';
    $a_criteria['Mac address'] = 'macAddress';
    $a_criteria['Windows product key'] = 'winProdKey';
    $a_criteria['Model'] = 'smodel';
    $a_criteria['storage serial'] = 'storagesSerial';
    $a_criteria['drives serial'] = 'drivesSerial';
    $a_criteria['Asset Tag'] = 'assetTag';
    $a_criteria['Computer name'] = 'name';
    $a_criteria['Manufacturer'] = 'manufacturer';
    foreach ($a_criteria as $name => $comment) {
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`\n            WHERE `name`='" . $name . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query_ins = "INSERT INTO `glpi_plugin_fusioninventory_inventorycomputercriterias`\n               (`name`, `comment`)\n               VALUES ('" . $name . "', '" . $comment . "')";
            $DB->query($query_ins);
        }
    }
    $a_criteria = array();
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_criteria[$data['comment']] = $data['id'];
    }
    /*
     * Update blacklist
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerblacklists";
    // * ssn
    $a_input = array('N/A', '(null string)', 'INVALID', 'SYS-1234567890', 'SYS-9876543210', 'SN-12345', 'SN-1234567890', '1111111111', '1111111', '1', '0123456789', '12345', '123456', '1234567', '12345678', '123456789', '1234567890', '123456789000', '12345678901234567', '0000000000', '000000000', '00000000', '0000000', '0000000', 'NNNNNNN', 'xxxxxxxxxxx', 'EVAL', 'IATPASS', 'none', 'To Be Filled By O.E.M.', 'Tulip Computers', 'Serial Number xxxxxx', 'SN-123456fvgv3i0b8o5n6n7k', 'Unknow', 'System Serial Number', 'MB-1234567890', '0', 'empty', 'Not Specified');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['ssn'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['ssn'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * uuid
    $a_input = array('FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF', '03000200-0400-0500-0006-000700080009', '6AB5B300-538D-1014-9FB5-B0684D007B53', '01010101-0101-0101-0101-010101010101');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['uuid'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['uuid'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * macAddress
    $a_input = array('20:41:53:59:4e:ff', '02:00:4e:43:50:49', 'e2:e6:16:20:0a:35', 'd2:0a:2d:a0:04:be', '00:a0:c6:00:00:00', 'd2:6b:25:2f:2c:e7', '33:50:6f:45:30:30', '0a:00:27:00:00:00', '00:50:56:C0:00:01', '00:50:56:C0:00:08', '02:80:37:EC:02:00', '50:50:54:50:30:30', '24:b6:20:52:41:53');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['macAddress'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['macAddress'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * smodel
    $a_input = array('Unknow', 'To Be Filled By O.E.M.', '*', 'System Product Name', 'Product Name', 'System Name');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['smodel'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['smodel'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * manufacturer
    $a_input = array('System manufacturer');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['manufacturer'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['manufacturer'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * ip
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`\n            WHERE `name`='IP'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == 0) {
        $DB->query("INSERT INTO `glpi_plugin_fusioninventory_inventorycomputercriterias`\n               (`id`, `name`, `comment`) VALUES\n               (11, 'IP', 'IP')");
    }
    $a_criteria = array();
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_criteria[$data['comment']] = $data['id'];
    }
    $a_input = array('0.0.0.0');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['IP'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['IP'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerantiviruses
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerantiviruses";
    $migration->renameTable("glpi_plugin_fusinvinventory_antivirus", $newTable);
    if (!TableExists($newTable)) {
        $DB->query("CREATE TABLE `" . $newTable . "` (\n                        `id` int(11) NOT NULL AUTO_INCREMENT,\n                        PRIMARY KEY (`id`)\n                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1");
    }
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "manufacturers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "version", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "is_active", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "uptodate", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, "name");
    $migration->addKey($newTable, "version");
    $migration->addKey($newTable, "is_active");
    $migration->addKey($newTable, "uptodate");
    $migration->addKey($newTable, "computers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerbatteries
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerbatteries";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "computers_id", "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "manufacturers_id", "manufacturers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "serial", "serial", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "capacity", "capacity", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "date", "date", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerchemistries_id", "plugin_fusioninventory_inventorycomputerchemistries_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "voltage", "voltage", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "manufacturers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "serial", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "capacity", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "date", "datetime DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerchemistries_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "voltage", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "computers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerchemistries
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerchemistries";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "name");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputercomputers
     */
    if (TableExists("glpi_plugin_fusinvinventory_computers") and FieldExists("glpi_plugin_fusinvinventory_computers", "uuid")) {
        $Computer = new Computer();
        $sql = "SELECT * FROM `glpi_plugin_fusinvinventory_computers`";
        $result = $DB->query($sql);
        while ($data = $DB->fetch_array($result)) {
            if ($Computer->getFromDB($data['items_id'])) {
                $input = array();
                $input['id'] = $data['items_id'];
                $input['uuid'] = $data['uuid'];
                $Computer->update($input);
            }
        }
        $sql = "DROP TABLE `glpi_plugin_fusinvinventory_computers`";
        $DB->query($sql);
    }
    if (TableExists("glpi_plugin_fusinvinventory_tmp_agents")) {
        $sql = "DROP TABLE `glpi_plugin_fusinvinventory_tmp_agents`";
        $DB->query($sql);
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_computers');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['bios_date'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['bios_version'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['bios_assettag'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['bios_manufacturers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['operatingsystem_installationdate'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['winowner'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['wincompany'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['last_fusioninventory_update'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['remote_addr'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_computerarchs_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['serialized_inventory'] = array('type' => 'longblob', 'value' => "");
    $a_table['fields']['is_entitylocked'] = array('type' => 'bool', 'value' => "0");
    $a_table['fields']['oscomment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'computers_id', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'last_fusioninventory_update', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    // Migrate libserialization
    require_once GLPI_ROOT . "/plugins/fusioninventory/inc/inventorycomputercomputer.class.php";
    $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
    if (TableExists('glpi_plugin_fusinvinventory_libserialization')) {
        $query = "SELECT * FROM `glpi_plugin_fusinvinventory_libserialization`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $a_pfcomputer = array();
            $a_pfcomputer = current($pfInventoryComputerComputer->find("`computers_id`='" . $data['computers_id'] . "'", "", 1));
            if (empty($a_pfcomputer)) {
                // Add
                if (countElementsInTable("glpi_computers", "`id`='" . $data['computers_id'] . "'") > 0) {
                    $input = array();
                    $input['computers_id'] = $data['computers_id'];
                    $input['last_fusioninventory_update'] = $data['last_fusioninventory_update'];
                    $pfInventoryComputerComputer->add($input);
                }
            } else {
                // Update
                $a_pfcomputer['last_fusioninventory_update'] = $data['last_fusioninventory_update'];
                $pfInventoryComputerComputer->update($a_pfcomputer);
            }
        }
    }
    $migration->dropTable('glpi_plugin_fusinvinventory_libserialization');
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstats
     */
    if (!TableExists("glpi_plugin_fusioninventory_inventorycomputerstats")) {
        $a_table = array();
        $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputerstats';
        $a_table['oldname'] = array();
        $a_table['fields'] = array();
        $a_table['fields']['id'] = array('type' => "smallint(3) NOT NULL AUTO_INCREMENT", 'value' => '');
        $a_table['fields']['day'] = array('type' => "smallint(3) NOT NULL DEFAULT '0'", 'value' => '');
        $a_table['fields']['hour'] = array('type' => "tinyint(2) NOT NULL DEFAULT '0'", 'value' => '');
        $a_table['fields']['counter'] = array('type' => 'integer', 'value' => NULL);
        $a_table['oldfields'] = array();
        $a_table['renamefields'] = array();
        $a_table['keys'] = array();
        $a_table['oldkeys'] = array();
        migrateTablesFusionInventory($migration, $a_table);
        require_once GLPI_ROOT . "/plugins/fusioninventory/inc/inventorycomputerstat.class.php";
        PluginFusioninventoryInventoryComputerStat::init();
    }
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstorages
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerstorages";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "uuid", "uuid", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "totalsize", "totalsize", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "freesize", "freesize", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerstoragetypes_id", "plugin_fusioninventory_inventorycomputerstoragetypes_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "computers_id", "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "uuid", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "totalsize", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "freesize", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerstoragetypes_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "uuid");
    $migration->addKey($newTable, "computers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstoragetypes
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerstoragetypes";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "level", "level", "tinyint(2) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "level", "tinyint(2) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "level");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstorages_storages
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerstorages_storages";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_1", "plugin_fusioninventory_inventorycomputerstorages_id_1", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_2", "plugin_fusioninventory_inventorycomputerstorages_id_2", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_1", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_2", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_1");
    $migration->addKey($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_2");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * glpi_plugin_fusioninventory_configlogfields
     */
    $newTable = "glpi_plugin_fusioninventory_configlogfields";
    $migration->renameTable("glpi_plugin_fusioninventory_config_snmp_history", $newTable);
    $migration->renameTable("glpi_plugin_fusinvsnmp_configlogfields", $newTable);
    if (TableExists($newTable)) {
        if (FieldExists($newTable, "field")) {
            $query = "SELECT * FROM `" . $newTable . "`";
            $result = $DB->query($query);
            while ($data = $DB->fetch_array($result)) {
                $pfMapping = new PluginFusioninventoryMapping();
                $mapping = 0;
                if ($mapping = $pfMapping->get("NetworkEquipment", $data['field'])) {
                    $queryu = "UPDATE `" . $newTable . "`\n                     SET `field`='" . $mapping['id'] . "'\n                     WHERE `field`='" . $data['field'] . "'";
                    $DB->query($queryu);
                }
            }
        }
    }
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(8) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "id", "id", "int(8) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "plugin_fusioninventory_mappings_id", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "days", "days", "int(255) NOT NULL DEFAULT '-1'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(8) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "field", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(8) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "days", "int(255) NOT NULL DEFAULT '-1'");
    $migration->addKey($newTable, "plugin_fusioninventory_mappings_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    $configLogField = new PluginFusioninventoryConfigLogField();
    $configLogField->initConfig();
    /*
     * Table glpi_plugin_fusioninventory_networkportconnectionlogs
     */
    $newTable = "glpi_plugin_fusioninventory_networkportconnectionlogs";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkportconnectionlogs", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "date", "date_mod", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "date_mod", "date_mod", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "creation", "creation", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_port_source", "networkports_id_source", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "networkports_id_source", "networkports_id_source", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_port_destination", "networkports_id_destination", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "networkports_id_destination", "networkports_id_destination", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_agentprocesses_id", "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->dropField($newTable, "process_number");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "date_mod", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "creation", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "networkports_id_source", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "networkports_id_destination", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, array("networkports_id_source", "networkports_id_destination", "plugin_fusioninventory_agentprocesses_id"), "networkports_id_source");
    $migration->addKey($newTable, "date_mod");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_networkporttypes
     */
    $newTable = "glpi_plugin_fusioninventory_networkporttypes";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkporttypes", $newTable);
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "number", "number", "int(4) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "othername", "othername", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "import", "import", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "number", "int(4) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "othername", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "import", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_printers
     */
    $newTable = "glpi_plugin_fusioninventory_printers";
    $migration->renameTable("glpi_plugin_fusinvsnmp_printers", $newTable);
    $migration->renameTable("glpi_plugin_tracker_printers", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "printers_id", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "sysdescr", "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusinvsnmp_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "frequence_days", "frequence_days", "int(5) NOT NULL DEFAULT '1'");
    $migration->changeField($newTable, "last_fusioninventory_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_printers", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_snmp_connection", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "last_tracker_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->dropKey($newTable, "FK_printers");
    $migration->dropKey($newTable, "FK_snmp_connection");
    $migration->dropKey($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->migrationOneTable($newTable);
    $migration->dropField($newTable, "plugin_fusinvsnmp_models_id");
    $migration->dropField($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->dropField($newTable, "FK_model_infos");
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "frequence_days", "int(5) NOT NULL DEFAULT '1'");
    $migration->addField($newTable, "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->addField($newTable, "serialized_inventory", "longblob");
    $migration->addKey($newTable, "plugin_fusioninventory_configsecurities_id");
    $migration->addKey($newTable, "printers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_printerlogs
     */
    $newTable = "glpi_plugin_fusioninventory_printerlogs";
    $migration->renameTable("glpi_plugin_fusinvsnmp_printerlogs", $newTable);
    $migration->renameTable("glpi_plugin_tracker_printers_history", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "printers_id", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "date", "date", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "pages_total", "pages_total", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_n_b", "pages_n_b", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_color", "pages_color", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_recto_verso", "pages_recto_verso", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "scanned", "scanned", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_total_print", "pages_total_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_n_b_print", "pages_n_b_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_color_print", "pages_color_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_total_copy", "pages_total_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_n_b_copy", "pages_n_b_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_color_copy", "pages_color_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_total_fax", "pages_total_fax", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_printers", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "date", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "pages_total", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_n_b", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_color", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_recto_verso", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "scanned", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_total_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_n_b_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_color_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_total_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_n_b_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_color_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_total_fax", "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, array("printers_id", "date"), "printers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     *  glpi_plugin_fusioninventory_printercartridges
     */
    $newTable = "glpi_plugin_fusioninventory_printercartridges";
    $migration->renameTable("glpi_plugin_fusinvsnmp_printercartridges", $newTable);
    $migration->renameTable("glpi_plugin_tracker_printers_cartridges", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` bigint(100) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "bigint(100) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "printers_id", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_mappings_id", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "cartridges_id", "cartridges_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "state", "state", "int(3) NOT NULL DEFAULT '100'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "bigint(100) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_printers", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_cartridges", "cartridges_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    // Update with mapping
    if (FieldExists($newTable, "object_name")) {
        $query = "SELECT * FROM `" . $newTable . "`\n               GROUP BY `object_name`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $pfMapping = new PluginFusioninventoryMapping();
            $mapping = 0;
            if ($mapping = $pfMapping->get("Printer", $data['object_name'])) {
                $DB->query("UPDATE `" . $newTable . "`\n                     SET `plugin_fusioninventory_mappings_id`='" . $mapping['id'] . "'\n                        WHERE `object_name`='" . $data['object_name'] . "'");
            }
        }
    }
    $migration->dropField($newTable, "object_name");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "bigint(100) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "cartridges_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "state", "int(3) NOT NULL DEFAULT '100'");
    $migration->addKey($newTable, "printers_id");
    $migration->addKey($newTable, "plugin_fusioninventory_mappings_id");
    $migration->addKey($newTable, "cartridges_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * glpi_plugin_fusioninventory_networkports
     */
    $newTable = "glpi_plugin_fusioninventory_networkports";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkports", $newTable);
    $migration->renameTable("glpi_plugin_tracker_networking_ports", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "networkports_id", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifmtu", "ifmtu", "int(8) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifspeed", "ifspeed", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifinternalstatus", "ifinternalstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "ifconnectionstatus", "ifconnectionstatus", "int(8) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "iflastchange", "iflastchange", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "ifinoctets", "ifinoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifinerrors", "ifinerrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifoutoctets", "ifoutoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifouterrors", "ifouterrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifstatus", "ifstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "mac", "mac", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "ifdescr", "ifdescr", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "portduplex", "portduplex", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "trunk", "trunk", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "lastup", "lastup", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_networking_ports", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifmac", "mac", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->dropKey($newTable, "FK_networking_ports");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifmtu", "int(8) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifspeed", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifinternalstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifconnectionstatus", "int(8) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "iflastchange", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifinoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifinerrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifoutoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifouterrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "mac", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifdescr", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifalias", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "portduplex", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "trunk", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "lastup", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addKey($newTable, "networkports_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_networkequipments
     */
    $newTable = "glpi_plugin_fusioninventory_networkequipments";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkequipments", $newTable);
    $migration->renameTable("glpi_plugin_tracker_networking", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "networkequipments_id", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "sysdescr", "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusioninventory_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "uptime", "uptime", "varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "cpu", "cpu", "int(3) NOT NULL DEFAULT '0' COMMENT '%'");
    $migration->changeField($newTable, "memory", "memory", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "last_fusioninventory_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "last_PID_update", "last_PID_update", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_networking", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_snmp_connection", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "last_tracker_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusinvsnmp_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->dropKey($newTable, "FK_networking");
    $migration->dropKey($newTable, "FK_model_infos");
    $migration->dropKey($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->migrationOneTable($newTable);
    $migration->dropField($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->dropField($newTable, "plugin_fusinvsnmp_models_id");
    $migration->dropField($newTable, "FK_model_infos");
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "uptime", "varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "cpu", "int(3) NOT NULL DEFAULT '0' COMMENT '%'");
    $migration->addField($newTable, "memory", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->addField($newTable, "last_PID_update", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "serialized_inventory", "longblob");
    $migration->addKey($newTable, "networkequipments_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * glpi_plugin_fusioninventory_networkequipmentips
     * Removed in 0.84, but required here for update, we drop in edn of this function
     */
    if (TableExists("glpi_plugin_fusioninventory_networkequipmentips") || TableExists("glpi_plugin_fusinvsnmp_networkequipmentips") || TableExists("glpi_plugin_tracker_networking_ifaddr")) {
        $newTable = "glpi_plugin_fusioninventory_networkequipmentips";
        $migration->renameTable("glpi_plugin_fusinvsnmp_networkequipmentips", $newTable);
        $migration->renameTable("glpi_plugin_tracker_networking_ifaddr", $newTable);
        if (!TableExists($newTable)) {
            $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
        }
        $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
        $migration->changeField($newTable, "networkequipments_id", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
        $migration->changeField($newTable, "ip", "ip", "varchar(255) DEFAULT NULL");
        $migration->migrationOneTable($newTable);
        $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
        $migration->changeField($newTable, "FK_networking", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
        $migration->changeField($newTable, "ifaddr", "ip", "varchar(255) DEFAULT NULL");
        $migration->dropKey($newTable, "ifaddr");
        $migration->migrationOneTable($newTable);
        $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
        $migration->addField($newTable, "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
        $migration->addField($newTable, "ip", "varchar(255) DEFAULT NULL");
        $migration->addKey($newTable, "ip");
        $migration->addKey($newTable, "networkequipments_id");
        $migration->migrationOneTable($newTable);
        $DB->list_fields($newTable, FALSE);
    }
    /*
     * Table glpi_plugin_fusioninventory_networkportlogs
     */
    $newTable = "glpi_plugin_fusioninventory_networkportlogs";
    if (TableExists("glpi_plugin_tracker_snmp_history")) {
        // **** Update history
        update213to220_ConvertField($migration);
        // **** Migration network history connections
        $query = "SELECT count(ID) FROM `glpi_plugin_tracker_snmp_history`\n                              WHERE `Field`='0'";
        $result = $DB->query($query);
        $datas = $DB->fetch_assoc($result);
        $nb = $datas['count(ID)'];
        //echo "Move Connections history to another table...";
        for ($i = 0; $i < $nb; $i = $i + 500) {
            $migration->displayMessage("{$i} / {$nb}");
            $sql_connection = "SELECT * FROM `glpi_plugin_tracker_snmp_history`\n                                 WHERE `Field`='0'\n                                 ORDER BY `FK_process` DESC, `date_mod` DESC\n                                 LIMIT 500";
            $result_connection = $DB->query($sql_connection);
            while ($thread_connection = $DB->fetch_array($result_connection)) {
                $input = array();
                $input['process_number'] = $thread_connection['FK_process'];
                $input['date'] = $thread_connection['date_mod'];
                if ($thread_connection["old_device_ID"] != "0" or $thread_connection["new_device_ID"] != "0") {
                    if ($thread_connection["old_device_ID"] != "0") {
                        // disconnection
                        $input['creation'] = '0';
                    } else {
                        if ($thread_connection["new_device_ID"] != "0") {
                            // connection
                            $input['creation'] = '1';
                        }
                    }
                    $input['FK_port_source'] = $thread_connection["FK_ports"];
                    $dataPort = array();
                    if ($thread_connection["old_device_ID"] != "0") {
                        $queryPort = "SELECT *\n                                      FROM `glpi_networkports`\n                                      WHERE `mac`='" . $thread_connection['old_value'] . "'\n                                      LIMIT 1";
                        $resultPort = $DB->query($queryPort);
                        $dataPort = $DB->fetch_assoc($resultPort);
                    } else {
                        if ($thread_connection["new_device_ID"] != "0") {
                            $queryPort = "SELECT *\n                                      FROM `glpi_networkports`\n                                      WHERE `mac`='" . $thread_connection['new_value'] . "'\n                                      LIMIT 1";
                            $resultPort = $DB->query($queryPort);
                            $dataPort = $DB->fetch_assoc($resultPort);
                        }
                    }
                    if (isset($dataPort['id'])) {
                        $input['FK_port_destination'] = $dataPort['id'];
                    } else {
                        $input['FK_port_destination'] = 0;
                    }
                    $query_ins = "INSERT INTO `glpi_plugin_fusinvsnmp_networkportconnectionlogs`\n                        (`date_mod`, `creation`, `networkports_id_source`,\n                         `networkports_id_destination`)\n                        VALUES ('" . $input['date'] . "',\n                                '" . $input['creation'] . "',\n                                '" . $input['FK_port_source'] . "',\n                                '" . $input['FK_port_destination'] . "')";
                    $DB->query($query_ins);
                }
            }
        }
        $query_del = "DELETE FROM `glpi_plugin_tracker_snmp_history`\n               WHERE `Field`='0'\n               AND (`old_device_ID`!='0' OR `new_device_ID`!='0')";
        $DB->query($query_del);
        $migration->displayMessage("{$nb} / {$nb}");
    }
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkportlogs", $newTable);
    $migration->renameTable("glpi_plugin_tracker_snmp_history", $newTable);
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "networkports_id", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_mappings_id", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "date_mod", "date_mod", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "value_old", "value_old", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "value_new", "value_new", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusioninventory_agentprocesses_id", "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_ports", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    // Update with mapping
    if (FieldExists($newTable, "Field")) {
        //            $pfNetworkPortLog = new PluginFusioninventoryNetworkPortLog();
        $pfMapping = new PluginFusioninventoryMapping();
        $query = "SELECT * FROM `" . $newTable . "`\n               GROUP BY `Field`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $mapping = 0;
            if ($mapping = $pfMapping->get("NetworkEquipment", $data['Field'])) {
                $DB->query("UPDATE `" . $newTable . "`\n                     SET `plugin_fusioninventory_mappings_id`='" . $mapping['id'] . "'\n                     WHERE `Field`='" . $data['Field'] . "'\n                        AND `plugin_fusioninventory_mappings_id`!='" . $mapping['id'] . "'");
            }
        }
    }
    $migration->dropField($newTable, "Field");
    $migration->changeField($newTable, "old_value", "value_old", "varchar(255) DEFAULT NULL");
    $migration->dropField($newTable, "old_device_type");
    $migration->dropField($newTable, "old_device_ID");
    $migration->changeField($newTable, "new_value", "value_new", "varchar(255) DEFAULT NULL");
    $migration->dropField($newTable, "new_device_type");
    $migration->dropField($newTable, "new_device_ID");
    $migration->dropField($newTable, "FK_process");
    $migration->dropKey($newTable, "FK_process");
    $migration->dropKey($newTable, "FK_ports");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "date_mod", "datetime DEFAULT NULL");
    $migration->addField($newTable, "value_old", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "value_new", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, array("networkports_id", "date_mod"), "networkports_id");
    $migration->addKey($newTable, "plugin_fusioninventory_mappings_id");
    $migration->addKey($newTable, "plugin_fusioninventory_agentprocesses_id");
    $migration->addKey($newTable, "date_mod");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_configsecurities
     */
    // TODO get info to create SNMP authentification with old values of Tracker plugin
    $newTable = "glpi_plugin_fusioninventory_configsecurities";
    $migration->renameTable("glpi_plugin_fusinvsnmp_configsecurities", $newTable);
    $migration->renameTable("glpi_plugin_tracker_snmp_connection", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "snmpversion", "snmpversion", "varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'");
    $migration->changeField($newTable, "community", "community", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "username", "username", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "authentication", "authentication", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "auth_passphrase", "auth_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "encryption", "encryption", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "priv_passphrase", "priv_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "is_deleted", "is_deleted", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_snmp_version", "snmpversion", "varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'");
    $migration->changeField($newTable, "sec_name", "username", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->dropField($newTable, "sec_level");
    $migration->dropField($newTable, "auth_protocol");
    $migration->dropField($newTable, "priv_protocol");
    $migration->dropField($newTable, "deleted");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "snmpversion", "varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'");
    $migration->addField($newTable, "community", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "username", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "authentication", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "auth_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "encryption", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "priv_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "is_deleted", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, "snmpversion");
    $migration->addKey($newTable, "is_deleted");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     *  glpi_plugin_fusioninventory_statediscoveries
     */
    $newTable = "glpi_plugin_fusioninventory_statediscoveries";
    $migration->renameTable("glpi_plugin_fusinvsnmp_statediscoveries", $newTable);
    if (!TableExists($newTable)) {
        $DB->query("CREATE TABLE `" . $newTable . "` (\n                        `id` int(11) NOT NULL AUTO_INCREMENT,\n                        PRIMARY KEY (`id`)\n                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1");
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "plugin_fusioninventory_taskjob_id", "plugin_fusioninventory_taskjob_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_agents_id", "plugin_fusioninventory_agents_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "start_time", "start_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "end_time", "end_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "date_mod", "date_mod", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "threads", "threads", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_ip", "nb_ip", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_found", "nb_found", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_error", "nb_error", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_exists", "nb_exists", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_import", "nb_import", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "plugin_fusioninventory_taskjob_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_agents_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "start_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "end_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "date_mod", "datetime DEFAULT NULL");
    $migration->addField($newTable, "threads", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_ip", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_found", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_error", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_exists", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_import", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_computerlicenseinfos
     */
    if (TableExists("glpi_plugin_fusinvinventory_licenseinfos")) {
        $DB->query("UPDATE `glpi_plugin_fusinvinventory_licenseinfos`" . " SET `softwarelicenses_id`='0'" . " WHERE `softwarelicenses_id` IS NULL");
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_computerlicenseinfos';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_licenseinfos');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['softwarelicenses_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['fullname'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['serial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['is_trial'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['is_update'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['is_oem'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['activation_date'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'fullname', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_computerarchs
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_computerarchs';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Deploy Update Begin
     */
    /*
     * glpi_plugin_fusioninventory_deployfiles
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_deployfiles';
    $a_table['oldname'] = array();
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'name' => array('type' => 'varchar(255) NOT NULL', 'value' => NULL), 'mimetype' => array('type' => 'varchar(255) NOT NULL', 'value' => NULL), 'filesize' => array('type' => 'bigint(20) NOT NULL', 'value' => NULL), 'comment' => array('type' => 'text DEFAULT NULL', 'value' => NULL), 'sha512' => array('type' => 'char(128) NOT NULL', 'value' => NULL), 'shortsha512' => array('type' => 'char(6) NOT NULL', 'value' => NULL), 'entities_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'is_recursive' => array('type' => 'tinyint(1) NOT NULL DEFAULT 0', 'value' => 0), 'date_mod' => array('type' => 'datetime DEFAULT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'id', 'name' => '', 'type' => 'KEY'), array('field' => 'shortsha512', 'name' => '', 'type' => 'KEY'), array('field' => 'entities_id', 'name' => '', 'type' => 'KEY'), array('field' => 'date_mod', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deployorders
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deployorders';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_orders');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'type' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'create_date' => array('type' => ' datetime NOT NULL', 'value' => NULL), 'plugin_fusioninventory_deploypackages_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'json' => array('type' => 'longtext DEFAULT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array('plugin_fusinvdeploy_packages_id' => 'plugin_fusioninventory_deploypackages_id');
    $a_table['keys'] = array(array('field' => 'type', 'name' => '', 'type' => 'KEY'), array('field' => 'create_date', 'name' => '', 'type' => 'KEY'), array('field' => 'plugin_fusioninventory_deploypackages_id', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array('plugin_fusinvdeploy_packages_id');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploypackages
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploypackages';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_packages');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'name' => array('type' => 'varchar(255) COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL), 'comment' => array('type' => "text", 'value' => NULL), 'entities_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'is_recursive' => array('type' => 'tinyint(1) NOT NULL DEFAULT 0', 'value' => NULL), 'date_mod' => array('type' => 'datetime DEFAULT NULL', 'value' => NULL), 'uuid' => array('type' => 'string', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'KEY'), array('field' => 'date_mod', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploymirrors
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploymirrors';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_mirrors');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'entities_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'is_recursive' => array('type' => 'tinyint(1) NOT NULL DEFAULT 0', 'value' => NULL), 'name' => array('type' => 'varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL), 'url' => array('type' => "varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci" . " NOT NULL DEFAULT ''", 'value' => NULL), 'locations_id' => array('type' => 'int(11) NOT NULL', 'value' => 0), 'comment' => array('type' => "text", 'value' => NULL), 'date_mod' => array('type' => 'datetime DEFAULT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'KEY'), array('field' => 'date_mod', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploygroups
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploygroups';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_groups');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'name' => array('type' => 'varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL), 'comment' => array('type' => "text", 'value' => NULL), 'type' => array('type' => 'varchar(255) COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploygroups_staticdatas
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploygroups_staticdatas';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_groups_staticdatas');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'groups_id' => array('type' => 'integer', 'value' => NULL), 'itemtype' => array('type' => 'varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL', 'value' => NULL), 'items_id' => array('type' => 'integer', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'groups_id', 'name' => '', 'type' => 'KEY'), array('field' => 'items_id', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploygroups_dynamicdatas
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploygroups_dynamicdatas';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_groups_dynamicdatas');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'groups_id' => array('type' => 'integer', 'value' => NULL), 'fields_array' => array('type' => 'text', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'groups_id', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * import old datas as json in order table before migrate this table
     */
    migrateTablesFromFusinvDeploy($migration);
    /*
     * Deploy Update End
     */
    /*
     * Table glpi_plugin_fusioninventory_collects
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['type'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['is_active'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_registries
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_registries';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['hive'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['path'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['key'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_registries_contents
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_registries_contents';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_registries_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['key'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'computers_id', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_wmis
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_wmis';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['moniker'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['class'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['properties'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_wmis_contents
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_wmis_contents';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_wmis_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['property'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_files
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_files';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['dir'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['limit'] = array('type' => "int(4) NOT NULL DEFAULT '50'", 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['filter_regex'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_sizeequals'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['filter_sizegreater'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['filter_sizelower'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['filter_checksumsha512'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_checksumsha2'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_iname'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_is_file'] = array('type' => 'bool', 'value' => '1');
    $a_table['fields']['filter_is_dir'] = array('type' => 'bool', 'value' => '0');
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_files_contents
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_files_contents';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_files_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['pathfile'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['size'] = array('type' => 'integer', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblockinventorynames
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblockinventorynames';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => "varchar(100) NOT NULL DEFAULT ''", 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblockinventories
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblockinventories';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblocksoftwares
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblocksoftwares';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblocksoftwareversions
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblocksoftwareversions';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Add ESX module appear in version 2.4.0(0.80+1.0)
     */
    $DB->query("UPDATE `glpi_plugin_fusioninventory_agentmodules`\n         SET `modulename`='InventoryComputerESX'\n         WHERE `modulename`='ESX'");
    $agentmodule = new PluginFusioninventoryAgentmodule();
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n         WHERE `modulename`='InventoryComputerESX'\n         LIMIT 1";
    $result = $DB->query($query);
    if ($DB->numrows($result) == '0') {
        $input = array();
        $input['modulename'] = "InventoryComputerESX";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $url = '';
        if (isset($_SERVER['HTTP_REFERER'])) {
            $url = $_SERVER['HTTP_REFERER'];
        }
        $agentmodule->add($input);
    }
    /*
     * Add Collect module appear in version 0.84+2.0
     */
    $agentmodule = new PluginFusioninventoryAgentmodule();
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n         WHERE `modulename`='Collect'\n         LIMIT 1";
    $result = $DB->query($query);
    if ($DB->numrows($result) == '0') {
        $input = array();
        $input['modulename'] = "Collect";
        $input['is_active'] = 1;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Update pci and usb ids and oui
     */
    foreach (array('usbid.sql', 'pciid.sql', 'oui.sql') as $sql) {
        $DB_file = GLPI_ROOT . "/plugins/fusioninventory/install/mysql/{$sql}";
        $DBf_handle = fopen($DB_file, "rt");
        $sql_query = fread($DBf_handle, filesize($DB_file));
        fclose($DBf_handle);
        foreach (explode(";\n", "{$sql_query}") as $sql_line) {
            if (Toolbox::get_magic_quotes_runtime()) {
                $sql_line = Toolbox::stripslashes_deep($sql_line);
            }
            if (!empty($sql_line)) {
                $DB->query($sql_line);
            }
        }
    }
    /*
     * Migrate data of table glpi_plugin_fusinvsnmp_agentconfigs into
     * glpi_plugin_fusioninventory_agents
     */
    if (TableExists("glpi_plugin_fusinvsnmp_agentconfigs")) {
        $query = "SELECT * FROM `glpi_plugin_fusinvsnmp_agentconfigs`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $queryu = "UPDATE `glpi_plugin_fusioninventory_agents`\n            SET `threads_networkdiscovery`='" . $data['threads_netdiscovery'] . "',\n                `threads_networkinventory`='" . $data['threads_snmpquery'] . "',\n                `senddico`='" . $data['senddico'] . "'\n            WHERE `id`='" . $data['plugin_fusioninventory_agents_id'] . "'";
            $DB->query($queryu);
        }
    }
    // Update profiles
    if (TableExists("glpi_plugin_tracker_profiles")) {
        $profile = new Profile();
        $pfProfile = new PluginFusioninventoryProfile();
        $query = "SELECT * FROM `glpi_plugin_tracker_profiles`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $profiledata = current($profile->find("`name`='" . $data['name'] . "'", "", 1));
            if (!empty($profiledata)) {
                $newprofile = array();
                $newprofile['snmp_networking'] = "networkequipment";
                $newprofile['snmp_printers'] = "printer";
                $newprofile['snmp_models'] = "model";
                $newprofile['snmp_authentification'] = "configsecurity";
                $newprofile['general_config'] = "configuration";
                $newprofile['snmp_report'] = "reportprinter";
                foreach ($newprofile as $old => $new) {
                    if (isset($profiledata[$old])) {
                        //                  $pfProfile->addProfile($new,
                        //                                         $profiledata[$old],
                        //                                         $profiledata['id']);
                    }
                }
                if (isset($profiledata["snmp_report"])) {
                    //               $pfProfile->addProfile("reportnetworkequipment",
                    //                                      $profiledata["snmp_report"],
                    //                                      $profiledata['id']);
                }
            }
        }
        $DB->query("DROP TABLE `glpi_plugin_tracker_profiles`");
    }
    update213to220_ConvertField($migration);
    /*
     * Move networkequipment IPs to net system
     */
    if (TableExists("glpi_plugin_fusioninventory_networkequipmentips")) {
        $networkPort = new NetworkPort();
        $networkName = new NetworkName();
        $ipAddress = new IPAddress();
        $networkEquipment = new NetworkEquipment();
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_networkequipments`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            if ($networkEquipment->getFromDB($data['networkequipments_id'])) {
                $oldtableip = array();
                $queryIP = "SELECT * FROM `glpi_plugin_fusioninventory_networkequipmentips`\n               WHERE `networkequipments_id`='" . $data['networkequipments_id'] . "'";
                $resultIP = $DB->query($queryIP);
                while ($dataIP = $DB->fetch_array($resultIP)) {
                    $oldtableip[$dataIP['ip']] = $dataIP['ip'];
                }
                // Get actual IP defined
                $networknames_id = 0;
                $a_ports = $networkPort->find("`itemtype`='NetworkEquipment'\n                  AND `items_id`='" . $data['networkequipments_id'] . "'\n                  AND `instantiation_type`='NetworkPortAggregate'\n                  AND `name`='management'", "", 1);
                foreach ($a_ports as $a_port) {
                    $a_networknames = $networkName->find("`itemtype`='NetworkPort'\n                  AND `items_id`='" . $a_port['id'] . "'");
                    foreach ($a_networknames as $a_networkname) {
                        $networknames_id = $a_networkname['id'];
                        $a_ipaddresses = $ipAddress->find("`itemtype`='NetworkName'\n                     AND `items_id`='" . $a_networkname['id'] . "'");
                        foreach ($a_ipaddresses as $a_ipaddress) {
                            if (isset($oldtableip[$a_ipaddress['name']])) {
                                unset($oldtableip[$a_ipaddress['name']]);
                            } else {
                                $ipAddress->delete($a_ipaddress, 1);
                            }
                        }
                    }
                }
                // Update
                foreach ($oldtableip as $ip) {
                    $input = array();
                    $input['itemtype'] = "NetworkName";
                    $input['items_id'] = $networknames_id;
                    $input['name'] = $ip;
                    $input['is_dynamic'] = 1;
                    $ipAddress->add($input);
                }
            }
        }
    }
    /*
     * Table Delete old table not used
     */
    $a_drop = array();
    $a_drop[] = 'glpi_plugin_tracker_computers';
    $a_drop[] = 'glpi_plugin_tracker_connection_history';
    $a_drop[] = 'glpi_plugin_tracker_agents_processes';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_history';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_networking';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_printer';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_script';
    $a_drop[] = 'glpi_plugin_tracker_connection_stats';
    $a_drop[] = 'glpi_plugin_tracker_discovery';
    $a_drop[] = 'glpi_plugin_tracker_errors';
    $a_drop[] = 'glpi_plugin_tracker_model_infos';
    $a_drop[] = 'glpi_plugin_tracker_processes';
    $a_drop[] = 'glpi_plugin_tracker_processes_values';
    $a_drop[] = 'glpi_plugin_fusioninventory_agents_errors';
    $a_drop[] = 'glpi_plugin_fusioninventory_agents_processes';
    $a_drop[] = 'glpi_plugin_fusioninventory_computers';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_auth_auth_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_auth_priv_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_auth_sec_level';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_version';
    $a_drop[] = 'glpi_plugin_fusioninventory_config_snmp_networking';
    $a_drop[] = 'glpi_plugin_fusioninventory_config_snmp_history';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_agentconfigs';
    $a_drop[] = 'glpi_plugin_tracker_computers';
    $a_drop[] = 'glpi_plugin_tracker_config';
    $a_drop[] = 'glpi_plugin_tracker_config_discovery';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_mib_label';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_mib_object';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_mib_oid';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_snmp_auth_auth_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_snmp_auth_priv_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_snmp_version';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_temp_profiles';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_tmp_agents';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_tmp_configs';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_tmp_tasks';
    $a_drop[] = 'glpi_plugin_tracker_tmp_connections';
    $a_drop[] = 'glpi_plugin_tracker_tmp_netports';
    $a_drop[] = 'glpi_plugin_tracker_walks';
    $a_drop[] = 'glpi_plugin_fusioninventory_networkequipmentips';
    foreach ($a_drop as $droptable) {
        if (TableExists($droptable)) {
            $DB->query("DROP TABLE `" . $droptable . "`");
        }
    }
    $migration->executeMigration();
    /*
     * Add WakeOnLan module appear in version 2.3.0
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='WAKEONLAN'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['plugins_id'] = $plugins_id;
        $input['modulename'] = "WAKEONLAN";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Add storage type if not present
     */
    $a_storage = array();
    $a_storage['partition'] = 5;
    $a_storage['volume groups'] = 10;
    $a_storage['logical volumes'] = 20;
    $a_storage['hard disk'] = 1;
    $a_storage['mount'] = 25;
    foreach ($a_storage as $name => $level) {
        $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_inventorycomputerstoragetypes`\n         WHERE `name`='" . $name . "'";
        $result = $DB->query($query);
        if (!$DB->numrows($result)) {
            $DB->query("INSERT INTO `glpi_plugin_fusioninventory_inventorycomputerstoragetypes`\n            (`name`, `level`) VALUES\n            ('" . $name . "', '" . $level . "')");
        }
    }
    /*
     * Clean for port orphelin
     */
    //networkports with item_type = 0
    $NetworkPort = new NetworkPort();
    $NetworkPort_Vlan = new NetworkPort_Vlan();
    $NetworkPort_NetworkPort = new NetworkPort_NetworkPort();
    $a_networkports = $NetworkPort->find("`itemtype`=''");
    foreach ($a_networkports as $data) {
        if ($NetworkPort_NetworkPort->getFromDBForNetworkPort($data['id'])) {
            $NetworkPort_NetworkPort->delete($NetworkPort_NetworkPort->fields);
        }
        $a_vlans = $NetworkPort_Vlan->find("`networkports_id`='" . $data['id'] . "'");
        foreach ($a_vlans as $a_vlan) {
            $NetworkPort_Vlan->delete($a_vlan);
        }
        $NetworkPort->delete($data, 1);
    }
    /*
     *  Clean old ports deleted but have some informations in SNMP tables
     */
    //echo "Clean ports purged\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_networkports`.`id`\n                    FROM `glpi_plugin_fusioninventory_networkports`\n                          LEFT JOIN `glpi_networkports`\n                                    ON `glpi_networkports`.`id` = `networkports_id`\n                          LEFT JOIN `glpi_networkequipments`\n                              ON `glpi_networkequipments`.`id` = `glpi_networkports`.`items_id`\n                    WHERE `glpi_networkequipments`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_networkports`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     * Clean for switch more informations again in DB when switch is purged
     */
    //echo "Clean for switch more informations again in DB when switch is purged\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_networkequipments`.`id`\n                    FROM `glpi_plugin_fusioninventory_networkequipments`\n                    LEFT JOIN `glpi_networkequipments`\n                        ON `glpi_networkequipments`.`id` = `networkequipments_id`\n                    WHERE `glpi_networkequipments`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_networkequipments`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     * Clean for printer more informations again in DB when printer is purged
     */
    //echo "Clean for printer more informations again in DB when printer is purged\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_printers`.`id`\n                    FROM `glpi_plugin_fusioninventory_printers`\n                          LEFT JOIN `glpi_printers` ON `glpi_printers`.`id` = `printers_id`\n                    WHERE `glpi_printers`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_printers`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     *  Clean printer cartridge not deleted with the printer associated
     */
    //echo "Clean printer cartridge not deleted with the printer associated\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_printercartridges`.`id`\n                    FROM `glpi_plugin_fusioninventory_printercartridges`\n                          LEFT JOIN `glpi_printers` ON `glpi_printers`.`id` = `printers_id`\n                    WHERE `glpi_printers`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_printercartridges`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     *  Clean printer history not deleted with printer associated
     */
    //echo "Clean printer history not deleted with printer associated\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_printerlogs`.`id`\n                    FROM `glpi_plugin_fusioninventory_printerlogs`\n                          LEFT JOIN `glpi_printers` ON `glpi_printers`.`id` = `printers_id`\n                    WHERE `glpi_printers`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_printerlogs`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     * Fix problem with mapping with many entries with same mapping
     */
    $a_mapping = array();
    $a_mappingdouble = array();
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_mappings`\n      ORDER BY `id`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        if (!isset($a_mapping[$data['itemtype'] . "." . $data['name']])) {
            $a_mapping[$data['itemtype'] . "." . $data['name']] = $data['id'];
        } else {
            $a_mappingdouble[$data['id']] = $data['itemtype'] . "." . $data['name'];
        }
    }
    foreach ($a_mappingdouble as $mapping_id => $mappingkey) {
        $query = "UPDATE `glpi_plugin_fusioninventory_printercartridges`\n         SET plugin_fusioninventory_mappings_id='" . $a_mapping[$mappingkey] . "'\n         WHERE plugin_fusioninventory_mappings_id='" . $mapping_id . "'";
        $DB->query($query);
        $query = "UPDATE `glpi_plugin_fusioninventory_networkportlogs`\n         SET plugin_fusioninventory_mappings_id='" . $a_mapping[$mappingkey] . "'\n         WHERE plugin_fusioninventory_mappings_id='" . $mapping_id . "'";
        $DB->query($query);
        $query = "UPDATE `glpi_plugin_fusioninventory_configlogfields`\n         SET plugin_fusioninventory_mappings_id='" . $a_mapping[$mappingkey] . "'\n         WHERE plugin_fusioninventory_mappings_id='" . $mapping_id . "'";
        $DB->query($query);
        $query = "DELETE FROM `glpi_plugin_fusioninventory_mappings`\n         WHERE `id` = '" . $mapping_id . "'";
        $DB->query($query);
    }
    /*
     * Update networports to convert itemtype 5153 to PluginFusioninventoryUnknownDevice
     */
    $sql = "UPDATE `glpi_networkports`\n      SET `itemtype`='PluginFusioninventoryUnknownDevice'\n      WHERE `itemtype`='5153'";
    $DB->query($sql);
    $sql = "UPDATE `glpi_networkports`\n      SET `itemtype`='PluginFusioninventoryTask'\n      WHERE `itemtype`='5166'";
    $DB->query($sql);
    /*
     * Clean display preferences not used
     */
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5150' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5160' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5161' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5163' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5165' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5190' ";
    $DB->query($sql);
    /*
     * Update display preferences
     */
    changeDisplayPreference("5153", "PluginFusioninventoryUnknownDevice");
    changeDisplayPreference("5158", "PluginFusioninventoryAgent");
    changeDisplayPreference("PluginFusinvinventoryBlacklist", "PluginFusioninventoryInventoryComputerBlacklist");
    changeDisplayPreference("5151", "PluginFusinvsnmpModel");
    changeDisplayPreference("PluginFusinvsnmpModel", "PluginFusioninventorySnmpmodel");
    changeDisplayPreference("5152", "PluginFusinvsnmpConfigSecurity");
    changeDisplayPreference("5156", "PluginFusinvsnmpPrinterCartridge");
    changeDisplayPreference("5157", "PluginFusinvsnmpNetworkEquipment");
    changeDisplayPreference("PluginFusinvsnmpNetworkEquipment", "PluginFusioninventoryNetworkEquipment");
    changeDisplayPreference("5159", "PluginFusinvsnmpIPRange");
    changeDisplayPreference("5162", "PluginFusinvsnmpNetworkPortLog");
    changeDisplayPreference("5167", "PluginFusioninventorySnmpmodelConstructDevice");
    changeDisplayPreference("PluginFusinvsnmpConstructDevice", "PluginFusioninventorySnmpmodelConstructDevice");
    changeDisplayPreference("5168", "PluginFusinvsnmpPrinterLog");
    changeDisplayPreference("PluginFusinvsnmpPrinterLogReport", "PluginFusioninventoryPrinterLogReport");
    changeDisplayPreference("PluginFusioninventoryUnknownDevice", "PluginFusioninventoryUnmanaged");
    /*
     * Delete IP and MAC of PluginFusioninventoryUnknownDevice in displaypreference
     */
    $queryd = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='PluginFusioninventoryUnknownDevice'\n            AND (`num`='11' OR `num`='12' OR `num`='16')";
    $DB->query($queryd);
    /*
     * Clean in displaypreference
     */
    $queryd = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='PluginFusioninventorysnmpModel'";
    $DB->query($queryd);
    /*
     * Modify displaypreference for PluginFusioninventoryPrinterLog
     */
    $pfPrinterLogReport = new PluginFusioninventoryPrinterLog();
    $a_searchoptions = $pfPrinterLogReport->getSearchOptions();
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryPrinterLogReport'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == '0') {
        $query = "INSERT INTO `glpi_displaypreferences` (`id`, `itemtype`, `num`, `rank`,\n                        `users_id`)\n                     VALUES (NULL, 'PluginFusioninventoryPrinterLogReport', '2', '1', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '18', '2', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '20', '3', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '5', '4', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '6', '5', '0')";
        $DB->query($query);
    } else {
        while ($data = $DB->fetch_array($result)) {
            if (!isset($a_searchoptions[$data['num']])) {
                $queryd = "DELETE FROM `glpi_displaypreferences`\n                  WHERE `id`='" . $data['id'] . "'";
                $DB->query($queryd);
            }
        }
    }
    /*
     * Modify displaypreference for PluginFusinvsnmpNetworkEquipment
     */
    $a_check = array();
    $a_check["2"] = 1;
    $a_check["3"] = 2;
    $a_check["4"] = 3;
    $a_check["5"] = 4;
    $a_check["6"] = 5;
    $a_check["7"] = 6;
    $a_check["8"] = 7;
    $a_check["9"] = 8;
    $a_check["10"] = 9;
    $a_check["11"] = 10;
    $a_check["14"] = 11;
    $a_check["12"] = 12;
    $a_check["13"] = 13;
    foreach ($a_check as $num => $rank) {
        $query = "SELECT * FROM `glpi_displaypreferences`\n         WHERE `itemtype` = 'PluginFusioninventoryNetworkEquipment'\n         AND `num`='" . $num . "'\n            AND `users_id`='0'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `glpi_displaypreferences` (`id`, `itemtype`, `num`, `rank`,\n                           `users_id`)\n                        VALUES (NULL, 'PluginFusioninventoryNetworkEquipment', '" . $num . "',\n                           '" . $rank . "', '0')";
            $DB->query($query);
        }
    }
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryNetworkEquipment'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        if (!isset($a_check[$data['num']])) {
            $queryd = "DELETE FROM `glpi_displaypreferences`\n               WHERE `id`='" . $data['id'] . "'";
            $DB->query($queryd);
        }
    }
    // If no PluginFusioninventoryTaskjoblog in preferences, add them
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryTaskjoblog'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == 0) {
        $DB->query("INSERT INTO `glpi_displaypreferences`\n            (`id`, `itemtype`, `num`, `rank`, `users_id`)\n         VALUES (NULL,'PluginFusioninventoryTaskjoblog', '2', '1', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '3', '2', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '4', '3', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '5', '4', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '6', '5', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '7', '6', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '8', '7', '0')");
    }
    // If no PluginFusioninventoryNetworkPort in preferences, add them
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryNetworkPort'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == 0) {
        $DB->query("INSERT INTO `glpi_displaypreferences`\n            (`id`, `itemtype`, `num`, `rank`, `users_id`)\n         VALUES (NULL,'PluginFusioninventoryNetworkPort', '3', '1', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '5', '2', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '6', '3', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '7', '4', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '8', '5', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '9', '6', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '10', '7', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '11', '8', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '12', '9', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '13', '10', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '14', '11', '0')");
    }
    /*
     * Convert taskjob definition from PluginFusinvsnmpIPRange to PluginFusioninventoryIPRange
     * onvert taskjob definition from PluginFusinvdeployPackage to PluginFusioninventoryDeployPackage
     */
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_taskjobs`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_defs = importArrayFromDB($data['targets']);
        foreach ($a_defs as $num => $a_def) {
            if (key($a_def) == 'PluginFusinvsnmpIPRange') {
                $a_defs[$num] = array('PluginFusioninventoryIPRange' => current($a_def));
            } else {
                if (key($a_def) == 'PluginFusinvdeployPackage') {
                    $a_defs[$num] = array('PluginFusioninventoryDeployPackage' => current($a_def));
                }
            }
        }
        $queryu = "UPDATE `glpi_plugin_fusioninventory_taskjobs`\n         SET `targets`='" . exportArrayToDB($a_defs) . "'\n         WHERE `id`='" . $data['id'] . "'";
        $DB->query($queryu);
    }
    /*
     * Convert taskjoblogs itemtype from PluginFusinvdeployPackage to
     * PluginFusioninventoryDeployPackage
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_taskjoblogs` " . "SET `itemtype`='PluginFusioninventoryDeployPackage'" . "WHERE `itemtype`='PluginFusinvdeployPackage'";
    $result = $DB->query($query);
    /*
     * Convert taskjobstates itemtype from PluginFusinvdeployPackage to
     * PluginFusioninventoryDeployPackage
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_taskjobstates` " . "SET `itemtype`='PluginFusioninventoryDeployPackage'" . "WHERE `itemtype` = 'PluginFusinvdeployPackage'";
    $result = $DB->query($query);
    /*
     * Convert taskjob action from PluginFusinvdeployGroup to PluginFusioninventoryDeployGroup
     */
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_taskjobs`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_defs = importArrayFromDB($data['actors']);
        foreach ($a_defs as $num => $a_def) {
            if (key($a_def) == 'PluginFusinvdeployGroup') {
                $a_defs[$num] = array('PluginFusioninventoryDeployGroup' => current($a_def));
            }
        }
        $queryu = "UPDATE `glpi_plugin_fusioninventory_taskjobs`\n         SET `actors`='" . exportArrayToDB($a_defs) . "'\n         WHERE `id`='" . $data['id'] . "'";
        $DB->query($queryu);
    }
    /*
     * Convert itemtype from glpi_plugin_fusioninventory_unknowndevices to
     * PluginFusioninventoryUnmanaged
     */
    $tables = array('glpi_networkports', 'glpi_logs', 'glpi_plugin_fusioninventory_ignoredimportdevices');
    foreach ($tables as $table) {
        $query = "UPDATE `" . $table . "` " . "SET `itemtype`='PluginFusioninventoryUnmanaged'" . "WHERE `itemtype` = 'PluginFusioninventoryUnknowndevice'";
        $DB->query($query);
    }
    $query = "UPDATE `glpi_ipaddresses` " . "SET `mainitemtype`='PluginFusioninventoryUnmanaged'" . "WHERE `mainitemtype` = 'PluginFusioninventoryUnknowndevice'";
    $DB->query($query);
    /*
     * Update rules
     */
    $query = "UPDATE glpi_rules SET `sub_type`='PluginFusioninventoryInventoryRuleImport'\n      WHERE `sub_type`='PluginFusioninventoryRuleImportEquipment'";
    $DB->query($query);
    $query = "SELECT * FROM `glpi_rules`\n               WHERE `sub_type`='PluginFusioninventoryInventoryRuleImport'";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $querya = "UPDATE glpi_ruleactions SET `value`='1'\n         WHERE `rules_id`='" . $data['id'] . "'\n            AND `value`='0'\n            AND `field`='_fusion'";
        $DB->query($querya);
    }
    $query = "UPDATE glpi_rules SET `sub_type`='PluginFusioninventoryInventoryRuleEntity'\n      WHERE `sub_type`='PluginFusinvinventoryRuleEntity'";
    $DB->query($query);
    /*
     *  Add default rules
     */
    if (TableExists("glpi_plugin_tracker_config_discovery")) {
        $migration->displayMessage("Create rules");
        $pfSetup = new PluginFusioninventorySetup();
        $pfSetup->initRules();
    }
    // If no rules, add them
    if (countElementsInTable('glpi_rules', "`sub_type`='PluginFusioninventoryInventoryRuleImport'") == 0) {
        $migration->displayMessage("Create rules");
        $pfSetup = new PluginFusioninventorySetup();
        $pfSetup->initRules();
    }
    // Add peripheral rules (in first in rule list) when use it since 0.85
    $query = "DELETE FROM `glpi_plugin_fusioninventory_configs`" . " WHERE `type`='import_peripheral' ";
    $DB->query($query);
    $query = "UPDATE `glpi_rules` " . " SET `ranking` = `ranking`+3" . " WHERE `sub_type`='PluginFusioninventoryInventoryRuleImport' ";
    $ranking = 0;
    // Create rule for : Peripheral + serial
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Peripheral serial';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 10;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Peripheral';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Peripheral import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Peripheral import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Peripheral';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Peripheral ignore import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Peripheral ignore import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Peripheral';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_ignore_import';
    $input['value'] = '1';
    $ruleaction->add($input);
    // Add monitor rules (in first in rule list) when use it since 0.85
    $query = "DELETE FROM `glpi_plugin_fusioninventory_configs`" . " WHERE `type`='import_monitor' ";
    $DB->query($query);
    $query = "UPDATE `glpi_rules` " . " SET `ranking` = `ranking`+3" . " WHERE `sub_type`='PluginFusioninventoryInventoryRuleImport' ";
    $ranking = 0;
    // Create rule for : Monitor + serial
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Monitor serial';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 10;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Monitor';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Monitor import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Monitor import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Monitor';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Monitor ignore import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Monitor ignore import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Monitor';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_ignore_import';
    $input['value'] = '1';
    $ruleaction->add($input);
    // Add printer rules (in first in rule list) when use it since 0.85
    $query = "DELETE FROM `glpi_plugin_fusioninventory_configs`" . " WHERE `type`='import_printer' ";
    /*
     *  Manage configuration of plugin
     */
    $config = new PluginFusioninventoryConfig();
    $pfSetup = new PluginFusioninventorySetup();
    $users_id = $pfSetup->createFusionInventoryUser();
    $a_input = array();
    $a_input['ssl_only'] = 0;
    $a_input['delete_task'] = 20;
    $a_input['inventory_frequence'] = 24;
    $a_input['agent_port'] = 62354;
    $a_input['extradebug'] = 0;
    $a_input['users_id'] = $users_id;
    $a_input['agents_old_days'] = 0;
    $config->addValues($a_input, FALSE);
    //      $DB->query("DELETE FROM `glpi_plugin_fusioninventory_configs`
    //        WHERE `plugins_id`='0'");
    //      $query = "SELECT * FROM `glpi_plugin_fusioninventory_configs`
    //           WHERE `type`='version'
    //           LIMIT 1, 10";
    //      $result = $DB->query($query);
    //      while ($data=$DB->fetch_array($result)) {
    //         $config->delete($data);
    //      }
    $a_input = array();
    $a_input['version'] = PLUGIN_FUSIONINVENTORY_VERSION;
    $config->addValues($a_input, TRUE);
    $a_input = array();
    $a_input['ssl_only'] = 0;
    if (isset($prepare_Config['ssl_only'])) {
        $a_input['ssl_only'] = $prepare_Config['ssl_only'];
    }
    $a_input['delete_task'] = 20;
    $a_input['inventory_frequence'] = 24;
    $a_input['agent_port'] = 62354;
    $a_input['extradebug'] = 0;
    $a_input['users_id'] = 0;
    //Deploy configuration options
    $a_input['server_upload_path'] = Toolbox::addslashes_deep(implode(DIRECTORY_SEPARATOR, array(GLPI_PLUGIN_DOC_DIR, 'fusioninventory', 'upload')));
    $a_input['alert_winpath'] = 1;
    $a_input['server_as_mirror'] = 1;
    $config->addValues($a_input, FALSE);
    $pfSetup = new PluginFusioninventorySetup();
    $users_id = $pfSetup->createFusionInventoryUser();
    $query = "UPDATE `glpi_plugin_fusioninventory_configs`\n                         SET `value`='" . $users_id . "'\n                  WHERE `type`='users_id'";
    $DB->query($query);
    // Update fusinvinventory _config values to this plugin
    $input = array();
    $input['import_software'] = 1;
    $input['import_volume'] = 1;
    $input['import_antivirus'] = 1;
    $input['import_registry'] = 1;
    $input['import_process'] = 1;
    $input['import_vm'] = 1;
    $input['component_processor'] = 1;
    $input['component_memory'] = 1;
    $input['component_harddrive'] = 1;
    $input['component_networkcard'] = 1;
    $input['component_graphiccard'] = 1;
    $input['component_soundcard'] = 1;
    $input['component_drive'] = 1;
    $input['component_networkdrive'] = 1;
    $input['component_control'] = 1;
    $input['states_id_default'] = 0;
    $input['location'] = 0;
    $input['group'] = 0;
    $input['component_networkcardvirtual'] = 1;
    $config->addValues($input, FALSE);
    // Add new config values if not added
    $input = $config->initConfigModule(TRUE);
    foreach ($input as $name => $value) {
        $a_conf = $config->find("`type`='" . $name . "'");
        if (count($a_conf) == 0) {
            $config->add(array('type' => $name, 'value' => $value));
        }
    }
    $migration->displayMessage("Clean printers");
    /*
     * Remove / at the end of printers (bugs in older versions of agents.
     */
    $printer = new Printer();
    $query = "SELECT * FROM `glpi_printers`\n         WHERE `serial` LIKE '%/' ";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $cleanSerial = preg_replace('/\\/$/', '', $data['serial']);
        $querynb = "SELECT * FROM `glpi_printers`\n            WHERE `serial`='" . $cleanSerial . "'\n            LIMIT 1";
        $resultnb = $DB->query($querynb);
        if ($DB->numrows($resultnb) == '0') {
            $input = array();
            $input['id'] = $data['id'];
            $input["serial"] = $cleanSerial;
            $printer->update($input);
        }
    }
    /*
     * Update blacklist
     */
    $input = array();
    $input['03000200-0400-0500-0006-000700080009'] = '2';
    $input['6AB5B300-538D-1014-9FB5-B0684D007B53'] = '2';
    $input['01010101-0101-0101-0101-010101010101'] = '2';
    $input['20:41:53:59:4e:ff'] = '3';
    $input['02:00:4e:43:50:49'] = '3';
    $input['e2:e6:16:20:0a:35'] = '3';
    $input['d2:0a:2d:a0:04:be'] = '3';
    $input['00:a0:c6:00:00:00'] = '3';
    $input['d2:6b:25:2f:2c:e7'] = '3';
    $input['33:50:6f:45:30:30'] = '3';
    $input['0a:00:27:00:00:00'] = '3';
    $input['00:50:56:C0:00:01'] = '3';
    $input['00:50:56:C0:00:02'] = '3';
    $input['00:50:56:C0:00:03'] = '3';
    $input['00:50:56:C0:00:04'] = '3';
    $input['00:50:56:C0:00:08'] = '3';
    $input['FE:FF:FF:FF:FF:FF'] = '3';
    $input['00:00:00:00:00:00'] = '3';
    $input['00:0b:ca:fe:00:00'] = '3';
    $input['02:80:37:EC:02:00'] = '3';
    $input['MB-1234567890'] = '1';
    $input['Not Specified'] = '1';
    $input['OEM_Serial'] = '1';
    $input['SystemSerialNumb'] = '1';
    $input['Not'] = '2';
    foreach ($input as $value => $type) {
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputerblacklists`\n         WHERE `plugin_fusioninventory_criterium_id`='" . $type . "'\n          AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `glpi_plugin_fusioninventory_inventorycomputerblacklists`\n            (`plugin_fusioninventory_criterium_id`, `value`) VALUES\n            ( '" . $type . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    $migration->displayMessage("Add Crontasks");
    /*
     * Add Crontask if not exist
     */
    $crontask = new CronTask();
    if ($crontask->getFromDBbyName('PluginFusioninventoryTaskjob', 'taskscheduler')) {
        $crontask->fields['itemtype'] = 'PluginFusioninventoryTask';
        $crontask->updateInDB(array('itemtype'));
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryTask', 'taskscheduler')) {
        CronTask::Register('PluginFusioninventoryTask', 'taskscheduler', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    }
    if ($crontask->getFromDBbyName('PluginFusioninventoryTaskjobstate', 'cleantaskjob') and $crontask->getFromDBbyName('PluginFusioninventoryTaskjobstatus', 'cleantaskjob')) {
        $crontask->getFromDBbyName('PluginFusioninventoryTaskjobstatus', 'cleantaskjob');
        $crontask->delete($crontask->fields);
    }
    if ($crontask->getFromDBbyName('PluginFusioninventoryTaskjobstatus', 'cleantaskjob')) {
        $query = "UPDATE `glpi_crontasks` SET `itemtype`='PluginFusioninventoryTaskjobstate'\n         WHERE `itemtype`='PluginFusioninventoryTaskjobstatus'";
        $DB->query($query);
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryTaskjobstate', 'cleantaskjob')) {
        Crontask::Register('PluginFusioninventoryTaskjobstate', 'cleantaskjob', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    }
    if ($crontask->getFromDBbyName('PluginFusinvsnmpNetworkPortLog', 'cleannetworkportlogs')) {
        $crontask->delete($crontask->fields);
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryNetworkPortLog', 'cleannetworkportlogs')) {
        Crontask::Register('PluginFusioninventoryNetworkPortLog', 'cleannetworkportlogs', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    }
    if ($crontask->getFromDBbyName('PluginFusioninventoryConfigurationManagement', 'checkdevices')) {
        $crontask->delete($crontask->fields);
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryAgent', 'cleanoldagents')) {
        Crontask::Register('PluginFusioninventoryAgent', 'cleanoldagents', 86400, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'hourmin' => 22, 'hourmax' => 6, 'comment' => 'Clean agents not contacted since xxx days'));
    }
    /*
     * Update task's agents list from dynamic group periodically in order to automatically target new
     * computer.
     */
    if (!$crontask->getFromDBbyName('PluginFusioninventoryTaskjob', 'updatedynamictasks')) {
        CronTask::Register('PluginFusioninventoryTaskjob', 'updatedynamictasks', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'state' => 0));
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryAgentWakeup', 'wakeupAgents')) {
        Crontask::Register('PluginFusioninventoryAgentWakeup', 'wakeupAgents', 120, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'comment' => 'Wake agents ups'));
    }
    /**
     * Add field to manage which group can be refreshed by updatedynamictasks crontask
     */
    if (!FieldExists('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'can_update_group')) {
        $migration->addField('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'can_update_group', 'bool');
        $migration->addKey('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'can_update_group');
        $migration->migrationOneTable('glpi_plugin_fusioninventory_deploygroups_dynamicdatas');
    }
    //   $pfIgnoredimportdevice = new PluginFusioninventoryIgnoredimportdevice();
    //   $pfIgnoredimportdevice->install();
    //Change static & dynamic structure to fit the GLPI framework
    $migration->changeField('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'groups_id', 'plugin_fusioninventory_deploygroups_id', 'integer');
    $migration->migrationOneTable('glpi_plugin_fusioninventory_deploygroups_dynamicdatas');
    $migration->changeField('glpi_plugin_fusioninventory_deploygroups_staticdatas', 'groups_id', 'plugin_fusioninventory_deploygroups_id', 'integer');
    $migration->migrationOneTable('glpi_plugin_fusioninventory_deploygroups_staticdatas');
    // Delete data in glpi_logs(agent problem => ticket http://forge.fusioninventory.org/issues/1546)
    // ** Token
    $query = "DELETE FROM `glpi_logs`\n      WHERE `itemtype`='PluginFusioninventoryAgent'\n         AND `id_search_option`='9'";
    $DB->query($query);
    // ** Last contact
    $query = "DELETE FROM `glpi_logs`\n      WHERE `itemtype`='PluginFusioninventoryAgent'\n         AND `id_search_option`='4'";
    $DB->query($query);
    // ** Version
    $query = "DELETE FROM `glpi_logs`\n      WHERE `itemtype`='PluginFusioninventoryAgent'\n         AND `id_search_option`='8'\n         AND `old_value`=`new_value`";
    $DB->query($query);
    /*
     * Manage devices with is_dynamic
     */
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_networkequipments`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $DB->query("UPDATE `glpi_networkequipments` SET `is_dynamic`='1'\n                        WHERE `id`='" . $data['networkequipments_id'] . "'");
    }
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercomputers`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $DB->query("UPDATE `glpi_computers` SET `is_dynamic`='1'\n                        WHERE `id`='" . $data['computers_id'] . "'");
    }
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_printers`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $DB->query("UPDATE `glpi_printers` SET `is_dynamic`='1'\n                        WHERE `id`='" . $data['printers_id'] . "'");
    }
    // Update networkports types
    $pfNetworkporttype = new PluginFusioninventoryNetworkporttype();
    $pfNetworkporttype->init();
    if (TableExists('glpi_plugin_fusioninventory_profiles')) {
        //Migrate rights to the new system introduction in GLPI 0.85
        PluginFusioninventoryProfile::migrateProfiles();
        //Drop old table
        $migration->dropTable('glpi_plugin_fusioninventory_profiles');
    }
    //Create first access to the current profile is needed
    if (isset($_SESSION['glpiactiveprofile'])) {
        PluginFusioninventoryProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
    }
    // Define lastup field of fusion networkports
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_mappings`\n      WHERE `name`='ifstatus'\n      LIMIT 1";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $query_np = "SELECT * FROM `glpi_plugin_fusioninventory_networkports`";
        $result_np = $DB->query($query_np);
        while ($data_np = $DB->fetch_array($result_np)) {
            $query_nplog = "SELECT * FROM `glpi_plugin_fusioninventory_networkportlogs`\n            WHERE `networkports_id`='" . $data_np['networkports_id'] . "'\n               AND `plugin_fusioninventory_mappings_id`='" . $data['id'] . "'\n            ORDER BY `date_mod` DESC\n            LIMIT 1";
            $result_nplog = $DB->query($query_nplog);
            while ($data_nplog = $DB->fetch_array($result_nplog)) {
                $DB->query("UPDATE `glpi_plugin_fusioninventory_networkports`\n               SET `lastup`='" . $data_nplog['date_mod'] . "'\n               WHERE `id`='" . $data_np['id'] . "'");
            }
        }
    }
    //Migrate search params for dynamic groups
    doDynamicDataSearchParamsMigration();
}
コード例 #30
0
 /**
  * Get logs of job
  *
  * @param array $task_ids list of tasks id
  * @return array
  */
 function getJoblogs($task_ids = array())
 {
     global $DB;
     $debug_mode = $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE;
     $runclass = new PluginFusioninventoryTaskjobstate();
     $run_states = $runclass->getStateNames();
     $query_where = array();
     $query_where[] = "WHERE 1";
     if (isset($_SESSION['glpiactiveentities_string'])) {
         $query_where[] = getEntitiesRestrictRequest("AND", 'task');
     }
     if (is_array($task_ids) and count($task_ids) > 0) {
         $query_where[] = "AND task.`id` IN (" . implode(",", $task_ids) . ")";
     }
     // quickly filter empty WHERE entry
     $query_where = array_filter($query_where);
     $query_fields = array(array('task.id', 'task.`id`'), array('task.name', 'task.`name`'), array('job.id', 'job.`id`'), array('job.name', 'job.`name`'), array('job.method', 'job.`method`'), array('job.targets', 'job.`targets`'));
     $fieldmap = array();
     foreach ($query_fields as $index => $key) {
         $fieldmap[$key[0]] = $index;
     }
     $query_select = array();
     foreach ($query_fields as $index => $key) {
         $query_select[] = $key[1] . " AS '" . $key[0] . "'";
     }
     $query_joins = array();
     $query_joins['task'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_tasks` as task", "  ON job.`plugin_fusioninventory_tasks_id` = task.`id`", "  AND task.`is_active` = 1"));
     $data_structure = array('query' => implode("\n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_taskjobs` as job", implode("\n", $query_joins), implode("\n", $query_where))), 'result' => null);
     $data_structure['result'] = $DB->query($data_structure['query']);
     //Results grouped by tasks > jobs > jobstates
     $logs = array();
     //Target cache (used to speed up data formatting)
     $targets_cache = array();
     $expanded = array();
     if (isset($_SESSION['plugin_fusioninventory_tasks_expanded'])) {
         $expanded = $_SESSION['plugin_fusioninventory_tasks_expanded'];
     }
     while ($result = $data_structure['result']->fetch_row()) {
         $task_id = $result[$fieldmap['task.id']];
         if (!array_key_exists($task_id, $logs)) {
             $logs[$task_id] = array('task_name' => $result[$fieldmap['task.name']], 'task_id' => $result[$fieldmap['task.id']], 'expanded' => false, 'jobs' => array());
         }
         if (isset($expanded[$task_id])) {
             $logs[$task_id]['expanded'] = $expanded[$task_id];
         }
         $job_id = $result[$fieldmap['job.id']];
         $jobs_handle =& $logs[$task_id]['jobs'];
         if (!array_key_exists($job_id, $jobs_handle)) {
             $jobs_handle[$job_id] = array('name' => $result[$fieldmap['job.name']], 'id' => $result[$fieldmap['job.id']], 'method' => $result[$fieldmap['job.method']], 'targets' => array());
         }
         $targets = importArrayFromDB($result[$fieldmap['job.targets']]);
         $targets_handle =& $jobs_handle[$job_id]['targets'];
         $agent_state_types = array('agents_prepared', 'agents_cancelled', 'agents_running', 'agents_success', 'agents_error', 'agents_notdone');
         if ($result[$fieldmap['job.method']] == 'networkinventory') {
             $pfNetworkinventory = new PluginFusioninventoryNetworkinventory();
             foreach ($targets as $keyt => $target) {
                 $item_type = key($target);
                 $items_id = current($target);
                 if ($item_type == 'PluginFusioninventoryIPRange') {
                     unset($targets[$keyt]);
                     // In this case get devices of this iprange
                     $deviceList = $pfNetworkinventory->getDevicesOfIPRange($items_id);
                     $targets = array_merge($targets, $deviceList);
                 }
             }
         }
         foreach ($targets as $target) {
             $item_type = key($target);
             $item_id = current($target);
             $target_id = $item_type . "_" . $item_id;
             if (isset($targets_cache[$target_id])) {
                 $item = $targets_cache[$target_id];
             } else {
                 $item = new $item_type();
                 $item->getFromDB($item_id);
                 $targets_cache[$target_id] = $item;
             }
             $targets_handle[$target_id] = array('id' => $item->fields['id'], 'name' => $item->fields['name'], 'type_name' => $item->getTypeName(), 'item_link' => $item->getLinkUrl(), 'counters' => array(), 'agents' => array());
             // create agent states counter lists
             foreach ($agent_state_types as $type) {
                 $targets_handle[$target_id]['counters'][$type] = array();
             }
         }
     }
     // Query fields mapping used to easily select fields by name
     $query_fields = array(array('task.id', 'task.`id`'), array('task.name', 'task.`name`'), array('job.id', 'job.`id`'), array('job.name', 'job.`name`'), array('job.method', 'job.`method`'), array('agent.id', 'agent.`id`'), array('agent.name', 'agent.`name`'), array('run.id', 'run.`id`'), array('run.itemtype', 'run.`itemtype`'), array('run.items_id', 'run.`items_id`'), array('run.state', 'run.`state`'), array('log.last_date', 'log.`date`'), array('log.last_timestamp', 'UNIX_TIMESTAMP(log.`date`)'), array('log.last_id', 'log.`id`'), array('log.last_comment', 'log.`comment`'));
     $fieldmap = array();
     foreach ($query_fields as $index => $key) {
         $fieldmap[$key[0]] = $index;
     }
     $query_select = array();
     foreach ($query_fields as $index => $key) {
         $query_select[] = $key[1] . " AS '" . $key[0] . "'";
     }
     $query_joins = array();
     $query_joins['max_run'] = implode("\n", array("INNER JOIN (", "  SELECT", "     MAX(run.`id`) AS max_id,", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`,", "     MAX(log.`id`) AS max_log_id", "  FROM `glpi_plugin_fusioninventory_taskjobstates` AS run", "  LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` AS log", "  ON log.`plugin_fusioninventory_taskjobstates_id` = run.`id`", "  GROUP BY", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`", ") max_run ON max_run.`plugin_fusioninventory_agents_id` = agent.`id`"));
     $query_joins['run'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_taskjobstates` AS run", "  ON max_run.`max_id` = run.`id`"));
     $query_joins['log'] = implode("\n", array("LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` as log", "  ON log.`id` = max_run.`max_log_id`"));
     $query_joins['job'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_taskjobs` AS job", "  ON job.`id` = run.`plugin_fusioninventory_taskjobs_id`"));
     $query_joins['task'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_tasks` as task", "  ON job.`plugin_fusioninventory_tasks_id` = task.`id`"));
     $queries = array();
     /*
      * Get latest jobstates for agents
      */
     $queries['1_last_runs'] = array('query' => implode(" \n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_agents` AS agent", implode("\n", $query_joins), implode("\n", $query_where), "GROUP BY job.`id`, agent.`id`, run.`id`")), 'result' => null);
     /*
      * Get last finished jobstates (ie. `state` >= 3)
      */
     $query_joins['max_run'] = implode("\n", array("INNER JOIN (", "  SELECT", "     MAX(run.`id`) AS max_id,", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`,", "     MAX(log.`id`) AS max_log_id", "  FROM `glpi_plugin_fusioninventory_taskjobstates` AS run", "  LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` AS log", "  ON log.`plugin_fusioninventory_taskjobstates_id` = run.`id`", "  WHERE run.`state` IN ( " . implode(",", array(PluginFusioninventoryTaskjobstate::FINISHED, PluginFusioninventoryTaskjobstate::IN_ERROR)) . " )", "  GROUP BY", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`", ") max_run ON max_run.`plugin_fusioninventory_agents_id` = agent.`id`"));
     $queries['2_finished_runs'] = array('query' => implode(" \n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_agents` AS agent", implode("\n", $query_joins), implode("\n", $query_where), "GROUP BY job.`id`, agent.`id`, run.`id`")), 'result' => null);
     $query_chrono = array("start" => microtime(true), "end" => 0);
     ksort($queries);
     foreach ($queries as $query_name => $contents) {
         $queries[$query_name]['result'] = $DB->query($contents['query']);
         $query_chrono['end'] = microtime(true);
         // For debug only
         //if ($debug_mode) {
         //   file_put_contents("/tmp/glpi_".$query_name.".sql",$contents['query']);
         //}
     }
     $agents = array();
     $format_chrono = array("start" => microtime(true), "end" => 0);
     foreach ($queries as $query_name => $contents) {
         if (!is_null($contents['result'])) {
             while ($result = $contents['result']->fetch_row()) {
                 // We need to check if the results are consistent with the view's structure gathered
                 // by the first query
                 $task_id = $result[$fieldmap['task.id']];
                 //if (!array_key_exists($task_id, $logs)) {
                 if (!isset($logs[$task_id])) {
                     continue;
                 }
                 $job_id = $result[$fieldmap['job.id']];
                 $jobs =& $logs[$task_id]['jobs'];
                 if (!isset($jobs[$job_id])) {
                     continue;
                 }
                 $target_id = $result[$fieldmap['run.itemtype']] . '_' . $result[$fieldmap['run.items_id']];
                 $targets =& $jobs[$job_id]['targets'];
                 if (!isset($targets[$target_id])) {
                     continue;
                 }
                 $counters =& $targets[$target_id]['counters'];
                 $agent_id = $result[$fieldmap['agent.id']];
                 $agents[$agent_id] = $result[$fieldmap['agent.name']];
                 if (!isset($targets[$target_id]['agents'][$agent_id])) {
                     $targets[$target_id]['agents'][$agent_id] = array();
                 }
                 $agent_state = '';
                 // Update counters
                 switch ($result[$fieldmap['run.state']]) {
                     case PluginFusioninventoryTaskjobstate::CANCELLED:
                         // We put this agent in the cancelled counter if it does not have any other job
                         // states.
                         if (!isset($counters['agents_prepared'][$agent_id]) and !isset($counters['agents_running'][$agent_id])) {
                             $counters['agents_cancelled'][$agent_id] = 1;
                             $agent_state = 'cancelled';
                         }
                         break;
                     case PluginFusioninventoryTaskjobstate::PREPARED:
                         // We put this agent in the prepared counter if it has not yet completed any job.
                         $counters['agents_prepared'][$agent_id] = 1;
                         $agent_state = 'prepared';
                         break;
                     case PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA:
                     case PluginFusioninventoryTaskjobstate::AGENT_HAS_SENT_DATA:
                         // This agent is running so it must not be in any other counter
                         foreach ($agent_state_types as $type) {
                             if (isset($counters[$type][$agent_id])) {
                                 unset($counters[$type][$agent_id]);
                             }
                         }
                         $counters['agents_running'][$agent_id] = 1;
                         $agent_state = 'running';
                         break;
                     case PluginFusioninventoryTaskjobstate::IN_ERROR:
                         if (isset($counters['agents_success'][$agent_id])) {
                             unset($counters['agents_success'][$agent_id]);
                         }
                         $counters['agents_error'][$agent_id] = 1;
                         $agent_state = 'error';
                         if (isset($counters['agents_notdone'][$agent_id])) {
                             unset($counters['agents_notdone'][$agent_id]);
                         }
                         break;
                     case PluginFusioninventoryTaskjobstate::FINISHED:
                         if (isset($counters['agents_error'][$agent_id])) {
                             unset($counters['agents_error'][$agent_id]);
                         }
                         $counters['agents_success'][$agent_id] = 1;
                         $agent_state = 'success';
                         if (isset($counters['agents_notdone'][$agent_id])) {
                             unset($counters['agents_notdone'][$agent_id]);
                         }
                         break;
                 }
                 if (!isset($counters['agents_error'][$agent_id]) and !isset($counters['agents_success'][$agent_id])) {
                     $counters['agents_notdone'][$agent_id] = 1;
                 }
                 if (isset($counters['agents_running'][$agent_id]) or isset($counters['agents_prepared'][$agent_id])) {
                     unset($counters['agents_cancelled'][$agent_id]);
                 }
                 $targets[$target_id]['agents'][$agent_id][] = array('agent_id' => $agent_id, 'numstate' => $result[$fieldmap['run.state']], 'state' => $agent_state, 'jobstate_id' => $result[$fieldmap['run.id']], 'last_log_id' => $result[$fieldmap['log.last_id']], 'last_log_date' => $result[$fieldmap['log.last_date']], 'timestamp' => $result[$fieldmap['log.last_timestamp']], 'last_log' => $result[$fieldmap['log.last_comment']]);
             }
         }
     }
     $format_chrono['end'] = microtime(true);
     if ($debug_mode) {
         function tmp_display_log($log)
         {
             return "ID:" . $log['task_id'] . "(" . $log['task_name'] . ")";
         }
         if (PluginFusioninventoryConfig::isExtradebugActive()) {
             Toolbox::logDebug(array("tasks" => implode(',', array_map('tmp_display_log', $logs)), "row count" => count($logs), "Joblogs Query" => self::FormatChrono($query_chrono), "Format logs results" => self::FormatChrono($format_chrono)));
         }
     }
     return array('tasks' => $logs, 'agents' => $agents);
 }