Class to manage virtual machines
Inheritance: extends CommonDBChild
Example #1
1
 /**
  *
  * Synchronize virtual machines
  *
  * @param unknown $computers_id
  * @param unknown $ocsid
  * @param unknown $ocsservers_id
  * @param unknown $cfg_ocs
  * @param unknown $dohistory
  * @return boolean
  */
 static function updateVirtualMachines($computers_id, $ocsid, $ocsservers_id, $cfg_ocs, $dohistory)
 {
     global $PluginOcsinventoryngDBocs, $DB;
     // No VM before OCS 1.3
     if ($cfg_ocs['ocs_version'] < self::OCS1_3_VERSION_LIMIT) {
         return false;
     }
     self::checkOCSconnection($ocsservers_id);
     $already_processed = array();
     //Get vms for this host
     $query = "SELECT*\n                FROM `virtualmachines`\n                WHERE `HARDWARE_ID` = '{$ocsid}'";
     $result = $PluginOcsinventoryngDBocs->query($query);
     $virtualmachine = new ComputerVirtualMachine();
     if ($PluginOcsinventoryngDBocs->numrows($result) > 0) {
         while ($line = $PluginOcsinventoryngDBocs->fetch_assoc($result)) {
             $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line));
             $vm = array();
             $vm['name'] = $line['NAME'];
             $vm['vcpu'] = $line['VCPU'];
             $vm['ram'] = $line['MEMORY'];
             $vm['uuid'] = $line['UUID'];
             $vm['computers_id'] = $computers_id;
             $vm['is_dynamic'] = 1;
             $vm['virtualmachinestates_id'] = Dropdown::importExternal('VirtualMachineState', $line['STATUS']);
             $vm['virtualmachinetypes_id'] = Dropdown::importExternal('VirtualMachineType', $line['VMTYPE']);
             $vm['virtualmachinesystems_id'] = Dropdown::importExternal('VirtualMachineType', $line['SUBSYSTEM']);
             $query = "SELECT `id`\n                      FROM `glpi_computervirtualmachines`\n                      WHERE `computers_id`='{$computers_id}'\n                         AND `is_dynamic`";
             if ($line['UUID']) {
                 $query .= " AND `uuid`='" . $line['UUID'] . "'";
             } else {
                 // Failback on name
                 $query .= " AND `name`='" . $line['NAME'] . "'";
             }
             $results = $DB->query($query);
             if ($DB->numrows($results) > 0) {
                 $id = $DB->result($results, 0, 'id');
             } else {
                 $id = 0;
             }
             if (!$id) {
                 $virtualmachine->reset();
                 if (!$dohistory) {
                     $vm['_no_history'] = true;
                 }
                 $id_vm = $virtualmachine->add($vm);
                 if ($id_vm) {
                     $already_processed[] = $id_vm;
                 }
             } else {
                 if ($virtualmachine->getFromDB($id)) {
                     $vm['id'] = $id;
                     $virtualmachine->update($vm);
                 }
                 $already_processed[] = $id;
             }
         }
     }
     // Delete Unexisting Items not found in OCS
     //Look for all ununsed virtual machines
     $query = "SELECT `id`\n                FROM `glpi_computervirtualmachines`\n                WHERE `computers_id`='{$computers_id}'\n                   AND `is_dynamic`";
     if (!empty($already_processed)) {
         $query .= "AND `id` NOT IN (" . implode(',', $already_processed) . ")";
     }
     foreach ($DB->request($query) as $data) {
         //Delete all connexions
         $virtualmachine->delete(array('id' => $data['id'], '_ocsservers_id' => $ocsservers_id), true);
     }
 }
 static function pdfForComputer(PluginPdfSimplePDF $pdf, Computer $item)
 {
     global $DB;
     $ID = $item->getField('id');
     // From ComputerVirtualMachine::showForComputer()
     $virtualmachines = getAllDatasFromTable('glpi_computervirtualmachines', "`computers_id` = '{$ID}'");
     $pdf->setColumnsSize(100);
     if (count($virtualmachines)) {
         $pdf->displayTitle("<b>" . __('List of virtual machines') . "</b>");
         $pdf->setColumnsSize(20, 8, 8, 8, 25, 8, 8, 15);
         $pdf->setColumnsAlign('left', 'center', 'center', 'center', 'left', 'right', 'right', 'left');
         $typ = explode(' ', __('Virtualization system'));
         $sys = explode(' ', __('Virtualization model'));
         $sta = explode(' ', __('State of the virtual machine'));
         $pdf->displayTitle(__('Name'), $typ[0], $sys[0], $sta[0], __('UUID'), __('CPU'), __('Mio'), __('Machine'));
         foreach ($virtualmachines as $virtualmachine) {
             $name = '';
             if ($link_computer = ComputerVirtualMachine::findVirtualMachine($virtualmachine)) {
                 $computer = new Computer();
                 if ($computer->getFromDB($link_computer)) {
                     $name = $computer->getName();
                 }
             }
             $pdf->displayLine($virtualmachine['name'], Html::clean(Dropdown::getDropdownName('glpi_virtualmachinetypes', $virtualmachine['virtualmachinetypes_id'])), Html::clean(Dropdown::getDropdownName('glpi_virtualmachinesystems', $virtualmachine['virtualmachinesystems_id'])), Html::clean(Dropdown::getDropdownName('glpi_virtualmachinestates', $virtualmachine['virtualmachinestates_id'])), $virtualmachine['uuid'], $virtualmachine['vcpu'], Html::clean(Html::formatNumber($virtualmachine['ram'], false, 0)), $name);
         }
     } else {
         $pdf->displayTitle("<b>" . __('No virtual machine associated with the computer') . "</b>");
     }
     // From ComputerVirtualMachine::showForVirtualMachine()
     if ($item->fields['uuid']) {
         $where = "`uuid`" . ComputerVirtualMachine::getUUIDRestrictRequest($item->fields['uuid']);
         $hosts = getAllDatasFromTable('glpi_computervirtualmachines', $where);
         if (count($hosts)) {
             $pdf->setColumnsSize(100);
             $pdf->displayTitle("<b>" . __('List of host machines') . "</b>");
             $pdf->setColumnsSize(26, 37, 37);
             $pdf->displayTitle(__('Name'), __('Operating system'), __('Entity'));
             $computer = new Computer();
             foreach ($hosts as $host) {
                 if ($computer->getFromDB($host['computers_id'])) {
                     $pdf->displayLine($computer->getName(), Html::clean(Dropdown::getDropdownName('glpi_operatingsystems', $computer->getField('operatingsystems_id'))), Html::clean(Dropdown::getDropdownName('glpi_entities', $computer->getEntityID())));
                 }
             }
         }
     }
     $pdf->displaySpace();
 }
Example #3
0
 function cleanDBonPurge()
 {
     $csv = new Computer_SoftwareVersion();
     $csv->cleanDBonItemDelete('Computer', $this->fields['id']);
     $csl = new Computer_SoftwareLicense();
     $csl->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ip = new Item_Problem();
     $ip->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ci = new Change_Item();
     $ci->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ip = new Item_Project();
     $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']);
     $ci = new Computer_Item();
     $ci->cleanDBonItemDelete('Computer', $this->fields['id']);
     Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'], !empty($this->input['keep_devices']));
     $disk = new ComputerDisk();
     $disk->cleanDBonItemDelete('Computer', $this->fields['id']);
     $vm = new ComputerVirtualMachine();
     $vm->cleanDBonItemDelete('Computer', $this->fields['id']);
 }
You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include '../inc/includes.php';
Session::checkCentralAccess();
if (!isset($_GET["id"])) {
    $_GET["id"] = "";
}
if (!isset($_GET["computers_id"])) {
    $_GET["computers_id"] = "";
}
$disk = new ComputerVirtualMachine();
if (isset($_POST["add"])) {
    $disk->check(-1, CREATE, $_POST);
    if ($newID = $disk->add($_POST)) {
        Event::log($_POST['computers_id'], "computers", 4, "inventory", sprintf(__('%s adds a virtual machine'), $_SESSION["glpiname"]));
        if ($_SESSION['glpibackcreated']) {
            Html::redirect(Toolbox::getItemTypeFormURL('ComputerVirtualMachine') . "?id=" . $newID);
        }
    }
    Html::back();
} else {
    if (isset($_POST["purge"])) {
        $disk->check($_POST["id"], PURGE);
        if ($disk->delete($_POST, 1)) {
            Event::log($disk->fields['computers_id'], "computers", 4, "inventory", sprintf(__('%s purges a virtual machine'), $_SESSION["glpiname"]));
        }
 /**
  * Update computer data
  *
  * @global type $DB
  *
  * @param php array $a_computerinventory all data from the agent
  * @param integer $computers_id id of the computer
  * @param boolean $no_history set true if not want history
  *
  * @return nothing
  */
 function updateComputer($a_computerinventory, $computers_id, $no_history, $setdynamic = 0)
 {
     global $DB, $CFG_GLPI;
     $computer = new Computer();
     $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
     $item_DeviceProcessor = new Item_DeviceProcessor();
     $deviceProcessor = new DeviceProcessor();
     $item_DeviceMemory = new Item_DeviceMemory();
     $deviceMemory = new DeviceMemory();
     $computerVirtualmachine = new ComputerVirtualMachine();
     $computerDisk = new ComputerDisk();
     $item_DeviceControl = new Item_DeviceControl();
     $item_DeviceHardDrive = new Item_DeviceHardDrive();
     $item_DeviceDrive = new Item_DeviceDrive();
     $item_DeviceGraphicCard = new Item_DeviceGraphicCard();
     $item_DeviceNetworkCard = new Item_DeviceNetworkCard();
     $item_DeviceSoundCard = new Item_DeviceSoundCard();
     $networkPort = new NetworkPort();
     $networkName = new NetworkName();
     $iPAddress = new IPAddress();
     $ipnetwork = new IPNetwork();
     $pfInventoryComputerAntivirus = new PluginFusioninventoryInventoryComputerAntivirus();
     $pfConfig = new PluginFusioninventoryConfig();
     $pfComputerLicenseInfo = new PluginFusioninventoryComputerLicenseInfo();
     $computer_Item = new Computer_Item();
     $monitor = new Monitor();
     $printer = new Printer();
     $peripheral = new Peripheral();
     //      $pfInventoryComputerStorage   = new PluginFusioninventoryInventoryComputerStorage();
     //      $pfInventoryComputerStorage_Storage =
     //             new PluginFusioninventoryInventoryComputerStorage_Storage();
     $computer->getFromDB($computers_id);
     $a_lockable = PluginFusioninventoryLock::getLockFields('glpi_computers', $computers_id);
     // * Computer
     $db_computer = array();
     $db_computer = $computer->fields;
     $computerName = $a_computerinventory['Computer']['name'];
     $a_ret = PluginFusioninventoryToolbox::checkLock($a_computerinventory['Computer'], $db_computer, $a_lockable);
     $a_computerinventory['Computer'] = $a_ret[0];
     $input = $a_computerinventory['Computer'];
     $input['id'] = $computers_id;
     $history = TRUE;
     if ($no_history) {
         $history = FALSE;
     }
     $input['_no_history'] = $no_history;
     PluginFusioninventoryInventoryComputerInventory::addDefaultStateIfNeeded($input);
     $computer->update($input, !$no_history);
     $this->computer = $computer;
     // * Computer fusion (ext)
     $db_computer = array();
     if ($no_history === FALSE) {
         $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercomputers`\n                WHERE `computers_id` = '{$computers_id}'\n                LIMIT 1";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             foreach ($data as $key => $value) {
                 $data[$key] = Toolbox::addslashes_deep($value);
             }
             $db_computer = $data;
         }
     }
     if (count($db_computer) == '0') {
         // Add
         $a_computerinventory['fusioninventorycomputer']['computers_id'] = $computers_id;
         $pfInventoryComputerComputer->add($a_computerinventory['fusioninventorycomputer'], array(), FALSE);
     } else {
         // Update
         if (!empty($db_computer['serialized_inventory'])) {
             $setdynamic = 0;
         }
         $idtmp = $db_computer['id'];
         unset($db_computer['id']);
         unset($db_computer['computers_id']);
         $a_ret = PluginFusioninventoryToolbox::checkLock($a_computerinventory['fusioninventorycomputer'], $db_computer);
         $a_computerinventory['fusioninventorycomputer'] = $a_ret[0];
         $db_computer = $a_ret[1];
         $input = $a_computerinventory['fusioninventorycomputer'];
         $input['id'] = $idtmp;
         $input['_no_history'] = $no_history;
         $pfInventoryComputerComputer->update($input, !$no_history);
     }
     // Put all link item dynamic (in case of update computer not yet inventoried with fusion)
     if ($setdynamic == 1) {
         $this->setDynamicLinkItems($computers_id);
     }
     // * Processors
     if ($pfConfig->getValue("component_processor") != 0) {
         $db_processors = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_deviceprocessors`.`id`, `designation`,\n                     `frequency`, `frequence`, `frequency_default`,\n                     `serial`, `manufacturers_id`, `glpi_items_deviceprocessors`.`nbcores`,\n                     `glpi_items_deviceprocessors`.`nbthreads`\n                  FROM `glpi_items_deviceprocessors`\n                  LEFT JOIN `glpi_deviceprocessors`\n                     ON `deviceprocessors_id`=`glpi_deviceprocessors`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $db_processors[$idtmp] = Toolbox::addslashes_deep($data);
             }
         }
         if (count($db_processors) == 0) {
             foreach ($a_computerinventory['processor'] as $a_processor) {
                 $this->addProcessor($a_processor, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'serial', 'manufacturers_id',
             // 'frequence'
             foreach ($a_computerinventory['processor'] as $key => $arrays) {
                 $frequence = $arrays['frequence'];
                 unset($arrays['frequence']);
                 unset($arrays['frequency']);
                 unset($arrays['frequency_default']);
                 foreach ($db_processors as $keydb => $arraydb) {
                     $frequencedb = $arraydb['frequence'];
                     unset($arraydb['frequence']);
                     unset($arraydb['frequency']);
                     unset($arraydb['frequency_default']);
                     if ($arrays == $arraydb) {
                         $a_criteria = $deviceProcessor->getImportCriteria();
                         $criteriafrequence = $a_criteria['frequence'];
                         $compare = explode(':', $criteriafrequence);
                         if ($frequence > $frequencedb - $compare[1] && $frequence < $frequencedb + $compare[1]) {
                             unset($a_computerinventory['processor'][$key]);
                             unset($db_processors[$keydb]);
                             break;
                         }
                     }
                 }
             }
             if (count($a_computerinventory['processor']) == 0 and count($db_processors) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_processors) != 0) {
                     // Delete processor in DB
                     foreach ($db_processors as $idtmp => $data) {
                         $item_DeviceProcessor->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['processor']) != 0) {
                     foreach ($a_computerinventory['processor'] as $a_processor) {
                         $this->addProcessor($a_processor, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Memories
     if ($pfConfig->getValue("component_memory") != 0) {
         $db_memories = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicememories`.`id`, `designation`, `size`,\n                     `frequence`, `serial`, `devicememorytypes_id`,\n                     `glpi_items_devicememories`.`busID`\n                     FROM `glpi_items_devicememories`\n                  LEFT JOIN `glpi_devicememories` ON `devicememories_id`=`glpi_devicememories`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $db_memories[$idtmp] = $data1;
             }
         }
         if (count($db_memories) == 0) {
             foreach ($a_computerinventory['memory'] as $a_memory) {
                 $this->addMemory($a_memory, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'serial', 'size',
             // 'devicememorytypes_id', 'frequence'
             foreach ($a_computerinventory['memory'] as $key => $arrays) {
                 $frequence = $arrays['frequence'];
                 unset($arrays['frequence']);
                 foreach ($db_memories as $keydb => $arraydb) {
                     $frequencedb = $arraydb['frequence'];
                     unset($arraydb['frequence']);
                     if ($arrays == $arraydb) {
                         $a_criteria = $deviceMemory->getImportCriteria();
                         $criteriafrequence = $a_criteria['frequence'];
                         $compare = explode(':', $criteriafrequence);
                         if ($frequence > $frequencedb - $compare[1] && $frequence < $frequencedb + $compare[1]) {
                             unset($a_computerinventory['memory'][$key]);
                             unset($db_memories[$keydb]);
                             break;
                         }
                     }
                 }
             }
             if (count($a_computerinventory['memory']) == 0 and count($db_memories) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_memories) != 0) {
                     // Delete memory in DB
                     foreach ($db_memories as $idtmp => $data) {
                         $item_DeviceMemory->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['memory']) != 0) {
                     foreach ($a_computerinventory['memory'] as $a_memory) {
                         $this->addMemory($a_memory, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Hard drive
     if ($pfConfig->getValue("component_harddrive") != 0) {
         $db_harddrives = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_deviceharddrives`.`id`, `serial`,\n                     `capacity`\n                     FROM `glpi_items_deviceharddrives`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_harddrives[$idtmp] = $data2;
             }
         }
         if (count($db_harddrives) == 0) {
             foreach ($a_computerinventory['harddrive'] as $a_harddrive) {
                 $this->addHardDisk($a_harddrive, $computers_id, $no_history);
             }
         } else {
             foreach ($a_computerinventory['harddrive'] as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 foreach ($db_harddrives as $keydb => $arraydb) {
                     if ($arrayslower['serial'] == $arraydb['serial']) {
                         if ($arraydb['capacity'] == 0 and $arrayslower['capacity'] > 0) {
                             $input = array('id' => $keydb, 'capacity' => $arrayslower['capacity']);
                             $item_DeviceHardDrive->update($input);
                         }
                         unset($a_computerinventory['harddrive'][$key]);
                         unset($db_harddrives[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['harddrive']) == 0 and count($db_harddrives) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_harddrives) != 0) {
                     // Delete hard drive in DB
                     foreach ($db_harddrives as $idtmp => $data) {
                         $item_DeviceHardDrive->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['harddrive']) != 0) {
                     foreach ($a_computerinventory['harddrive'] as $a_harddrive) {
                         $this->addHardDisk($a_harddrive, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * drive
     if ($pfConfig->getValue("component_drive") != 0) {
         $db_drives = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicedrives`.`id`, `serial`,\n                     `glpi_devicedrives`.`designation`\n                     FROM `glpi_items_devicedrives`\n                  LEFT JOIN `glpi_devicedrives` ON `devicedrives_id`=`glpi_devicedrives`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_drives[$idtmp] = $data2;
             }
         }
         if (count($db_drives) == 0) {
             foreach ($a_computerinventory['drive'] as $a_drive) {
                 $this->addDrive($a_drive, $computers_id, $no_history);
             }
         } else {
             foreach ($a_computerinventory['drive'] as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 if ($arrayslower['serial'] == '') {
                     foreach ($db_drives as $keydb => $arraydb) {
                         if ($arrayslower['designation'] == $arraydb['designation']) {
                             unset($a_computerinventory['drive'][$key]);
                             unset($db_drives[$keydb]);
                             break;
                         }
                     }
                 } else {
                     foreach ($db_drives as $keydb => $arraydb) {
                         if ($arrayslower['serial'] == $arraydb['serial']) {
                             unset($a_computerinventory['drive'][$key]);
                             unset($db_drives[$keydb]);
                             break;
                         }
                     }
                 }
             }
             if (count($a_computerinventory['drive']) == 0 and count($db_drives) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_drives) != 0) {
                     // Delete drive in DB
                     foreach ($db_drives as $idtmp => $data) {
                         $item_DeviceDrive->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['drive']) != 0) {
                     foreach ($a_computerinventory['drive'] as $a_drive) {
                         $this->addDrive($a_drive, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Graphiccard
     if ($pfConfig->getValue("component_graphiccard") != 0) {
         $db_graphiccards = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicegraphiccards`.`id`, `designation`, `memory`\n                     FROM `glpi_items_devicegraphiccards`\n                  LEFT JOIN `glpi_devicegraphiccards`\n                     ON `devicegraphiccards_id`=`glpi_devicegraphiccards`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['designation'])) {
                     $data['designation'] = Toolbox::addslashes_deep($data['designation']);
                 }
                 $data['designation'] = trim(strtolower($data['designation']));
                 $db_graphiccards[$idtmp] = $data;
             }
         }
         if (count($db_graphiccards) == 0) {
             foreach ($a_computerinventory['graphiccard'] as $a_graphiccard) {
                 $this->addGraphicCard($a_graphiccard, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'memory'
             foreach ($a_computerinventory['graphiccard'] as $key => $arrays) {
                 $arrays['designation'] = strtolower($arrays['designation']);
                 foreach ($db_graphiccards as $keydb => $arraydb) {
                     if ($arrays == $arraydb) {
                         unset($a_computerinventory['graphiccard'][$key]);
                         unset($db_graphiccards[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['graphiccard']) == 0 and count($db_graphiccards) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_graphiccards) != 0) {
                     // Delete graphiccard in DB
                     foreach ($db_graphiccards as $idtmp => $data) {
                         $item_DeviceGraphicCard->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['graphiccard']) != 0) {
                     foreach ($a_computerinventory['graphiccard'] as $a_graphiccard) {
                         $this->addGraphicCard($a_graphiccard, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * networkcard
     if ($pfConfig->getValue("component_networkcard") != 0) {
         $db_networkcards = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicenetworkcards`.`id`, `designation`, `mac`,\n                     `manufacturers_id`\n                     FROM `glpi_items_devicenetworkcards`\n                  LEFT JOIN `glpi_devicenetworkcards`\n                     ON `devicenetworkcards_id`=`glpi_devicenetworkcards`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['designation'])) {
                     $data['designation'] = Toolbox::addslashes_deep($data['designation']);
                 }
                 $data['designation'] = trim(strtolower($data['designation']));
                 $db_networkcards[$idtmp] = $data;
             }
         }
         if (count($db_networkcards) == 0) {
             foreach ($a_computerinventory['networkcard'] as $a_networkcard) {
                 $this->addNetworkCard($a_networkcard, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'mac'
             foreach ($a_computerinventory['networkcard'] as $key => $arrays) {
                 $arrays['designation'] = strtolower($arrays['designation']);
                 foreach ($db_networkcards as $keydb => $arraydb) {
                     if ($arrays == $arraydb) {
                         unset($a_computerinventory['networkcard'][$key]);
                         unset($db_networkcards[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['networkcard']) == 0 and count($db_networkcards) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_networkcards) != 0) {
                     // Delete networkcard in DB
                     foreach ($db_networkcards as $idtmp => $data) {
                         $item_DeviceNetworkCard->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['networkcard']) != 0) {
                     foreach ($a_computerinventory['networkcard'] as $a_networkcard) {
                         $this->addNetworkCard($a_networkcard, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Sound
     if ($pfConfig->getValue("component_soundcard") != 0) {
         $db_soundcards = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicesoundcards`.`id`, `designation`, `comment`,\n                     `manufacturers_id` FROM `glpi_items_devicesoundcards`\n                  LEFT JOIN `glpi_devicesoundcards`\n                     ON `devicesoundcards_id`=`glpi_devicesoundcards`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $db_soundcards[$idtmp] = $data1;
             }
         }
         if (count($db_soundcards) == 0) {
             foreach ($a_computerinventory['soundcard'] as $a_soundcard) {
                 $this->addSoundCard($a_soundcard, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'memory', 'manufacturers_id'
             foreach ($a_computerinventory['soundcard'] as $key => $arrays) {
                 //               $arrayslower = array_map('strtolower', $arrays);
                 $arrayslower = $arrays;
                 foreach ($db_soundcards as $keydb => $arraydb) {
                     if ($arrayslower == $arraydb) {
                         unset($a_computerinventory['soundcard'][$key]);
                         unset($db_soundcards[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['soundcard']) == 0 and count($db_soundcards) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_soundcards) != 0) {
                     // Delete soundcard in DB
                     foreach ($db_soundcards as $idtmp => $data) {
                         $item_DeviceSoundCard->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['soundcard']) != 0) {
                     foreach ($a_computerinventory['soundcard'] as $a_soundcard) {
                         $this->addSoundCard($a_soundcard, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Controllers
     if ($pfConfig->getValue("component_control") != 0) {
         $db_controls = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicecontrols`.`id`, `interfacetypes_id`,\n                     `manufacturers_id`, `designation` FROM `glpi_items_devicecontrols`\n                  LEFT JOIN `glpi_devicecontrols` ON `devicecontrols_id`=`glpi_devicecontrols`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_controls[$idtmp] = $data2;
             }
         }
         if (count($db_controls) == 0) {
             foreach ($a_computerinventory['controller'] as $a_control) {
                 $this->addControl($a_control, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source:
             foreach ($a_computerinventory['controller'] as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 foreach ($db_controls as $keydb => $arraydb) {
                     if ($arrayslower == $arraydb) {
                         unset($a_computerinventory['controller'][$key]);
                         unset($db_controls[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['controller']) == 0 and count($db_controls) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_controls) != 0) {
                     // Delete controller in DB
                     foreach ($db_controls as $idtmp => $data) {
                         $item_DeviceControl->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['controller']) != 0) {
                     foreach ($a_computerinventory['controller'] as $a_control) {
                         $this->addControl($a_control, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Software
     if ($pfConfig->getValue("import_software") != 0) {
         $entities_id = 0;
         if (count($a_computerinventory['software']) > 0) {
             $a_softfirst = current($a_computerinventory['software']);
             if (isset($a_softfirst['entities_id'])) {
                 $entities_id = $a_softfirst['entities_id'];
             }
         }
         $db_software = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_computers_softwareversions`.`id` as sid,\n                          `glpi_softwares`.`name`,\n                          `glpi_softwareversions`.`name` AS version,\n                          `glpi_softwares`.`manufacturers_id`,\n                          `glpi_softwareversions`.`entities_id`,\n                          `glpi_computers_softwareversions`.`is_template_computer`,\n                          `glpi_computers_softwareversions`.`is_deleted_computer`\n                   FROM `glpi_computers_softwareversions`\n                   LEFT JOIN `glpi_softwareversions`\n                        ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                              = `glpi_softwareversions`.`id`)\n                   LEFT JOIN `glpi_softwares`\n                        ON (`glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`)\n                   WHERE `glpi_computers_softwareversions`.`computers_id` = '{$computers_id}'\n                     AND `glpi_computers_softwareversions`.`is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['sid'];
                 unset($data['sid']);
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['name'])) {
                     $data['name'] = Toolbox::addslashes_deep($data['name']);
                 }
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['version'])) {
                     $data['version'] = Toolbox::addslashes_deep($data['version']);
                 }
                 $comp_key = strtolower($data['name']) . "\$\$\$\$" . strtolower($data['version']) . "\$\$\$\$" . $data['manufacturers_id'] . "\$\$\$\$" . $data['entities_id'];
                 $db_software[$comp_key] = $idtmp;
             }
         }
         $lastSoftwareid = 0;
         $lastSoftwareVid = 0;
         /*
          * Schema
          *
          * LOCK software
          * 1/ Add all software
          * RELEASE software
          *
          * LOCK softwareversion
          * 2/ Add all software versions
          * RELEASE softwareversion
          *
          * 3/ add version to computer
          *
          */
         if (count($db_software) == 0) {
             // there are no software associated with computer
             $nb_unicity = count(FieldUnicity::getUnicityFieldsConfig("Software", $entities_id));
             $options = array();
             if ($nb_unicity == 0) {
                 $options['disable_unicity_check'] = TRUE;
             }
             $a_softwareInventory = array();
             $a_softwareVersionInventory = array();
             $lastSoftwareid = $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
             $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwares`\n                     SET `value`='1'";
             $CFG_GLPI["use_log_in_files"] = FALSE;
             while (!$DB->query($queryDBLOCK)) {
                 usleep(100000);
             }
             $CFG_GLPI["use_log_in_files"] = TRUE;
             $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
             foreach ($a_computerinventory['software'] as $a_software) {
                 if (!isset($this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']])) {
                     $this->addSoftware($a_software, $options);
                 }
             }
             $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwares`\n                     WHERE `value`='1'";
             $DB->query($queryDBLOCK);
             $lastSoftwareVid = $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
             $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                     SET `value`='1'";
             $CFG_GLPI["use_log_in_files"] = FALSE;
             while (!$DB->query($queryDBLOCK)) {
                 usleep(100000);
             }
             $CFG_GLPI["use_log_in_files"] = TRUE;
             $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
             foreach ($a_computerinventory['software'] as $a_software) {
                 $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                 if (!isset($this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id])) {
                     $this->addSoftwareVersion($a_software, $softwares_id);
                 }
             }
             $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                     WHERE `value`='1'";
             $DB->query($queryDBLOCK);
             $a_toinsert = array();
             foreach ($a_computerinventory['software'] as $a_software) {
                 $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                 $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                 $a_tmp = array('computers_id' => $computers_id, 'softwareversions_id' => $softwareversions_id, 'is_dynamic' => 1, 'entities_id' => $a_software['entities_id']);
                 $a_toinsert[] = "('" . implode("','", $a_tmp) . "')";
             }
             if (count($a_toinsert) > 0) {
                 $this->addSoftwareVersionsComputer($a_toinsert);
                 if (!$no_history) {
                     foreach ($a_computerinventory['software'] as $a_software) {
                         $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                         $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                         $changes[0] = '0';
                         $changes[1] = "";
                         $changes[2] = $a_software['name'] . " - " . sprintf(__('%1$s (%2$s)'), $a_software['version'], $softwareversions_id);
                         $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                         $changes[0] = '0';
                         $changes[1] = "";
                         $changes[2] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id);
                         $this->addPrepareLog($softwareversions_id, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                     }
                 }
             }
         } else {
             foreach ($a_computerinventory['software'] as $key => $arrayslower) {
                 if (isset($db_software[$key])) {
                     unset($a_computerinventory['software'][$key]);
                     unset($db_software[$key]);
                 }
             }
             if (count($a_computerinventory['software']) == 0 && count($db_software) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_software) > 0) {
                     // Delete softwares in DB
                     $a_delete = array();
                     foreach ($db_software as $idtmp) {
                         $this->computer_SoftwareVersion->getFromDB($idtmp);
                         $this->softwareVersion->getFromDB($this->computer_SoftwareVersion->fields['softwareversions_id']);
                         //                        $this->computer_SoftwareVersion->delete(array('id'=>$idtmp, '_no_history'=> TRUE), FALSE);
                         if (!$no_history) {
                             $changes[0] = '0';
                             $changes[1] = addslashes($this->computer_SoftwareVersion->getHistoryNameForItem1($this->softwareVersion, 'delete'));
                             $changes[2] = "";
                             $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_UNINSTALL_SOFTWARE);
                             $changes[0] = '0';
                             $changes[1] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id);
                             $changes[2] = "";
                             $this->addPrepareLog($idtmp, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_UNINSTALL_SOFTWARE);
                         }
                     }
                     $query = "DELETE FROM `glpi_computers_softwareversions` " . "WHERE `id` IN ('" . implode("', '", $db_software) . "')";
                     $DB->query($query);
                 }
                 if (count($a_computerinventory['software']) > 0) {
                     $nb_unicity = count(FieldUnicity::getUnicityFieldsConfig("Software", $entities_id));
                     $options = array();
                     if ($nb_unicity == 0) {
                         $options['disable_unicity_check'] = TRUE;
                     }
                     $lastSoftwareid = $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
                     $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwares`\n                           SET `value`='1'";
                     $CFG_GLPI["use_log_in_files"] = FALSE;
                     while (!$DB->query($queryDBLOCK)) {
                         usleep(100000);
                     }
                     $CFG_GLPI["use_log_in_files"] = TRUE;
                     $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
                     foreach ($a_computerinventory['software'] as $a_software) {
                         if (!isset($this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']])) {
                             $this->addSoftware($a_software, $options);
                         }
                     }
                     $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwares`\n                           WHERE `value`='1'";
                     $DB->query($queryDBLOCK);
                     $lastSoftwareVid = $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
                     $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                           SET `value`='1'";
                     $CFG_GLPI["use_log_in_files"] = FALSE;
                     while (!$DB->query($queryDBLOCK)) {
                         usleep(100000);
                     }
                     $CFG_GLPI["use_log_in_files"] = TRUE;
                     $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
                     foreach ($a_computerinventory['software'] as $a_software) {
                         $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                         if (!isset($this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id])) {
                             $this->addSoftwareVersion($a_software, $softwares_id);
                         }
                     }
                     $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                           WHERE `value`='1'";
                     $DB->query($queryDBLOCK);
                     $a_toinsert = array();
                     foreach ($a_computerinventory['software'] as $a_software) {
                         $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                         $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                         $a_tmp = array('computers_id' => $computers_id, 'softwareversions_id' => $softwareversions_id, 'is_dynamic' => 1, 'entities_id' => $a_software['entities_id']);
                         $a_toinsert[] = "('" . implode("','", $a_tmp) . "')";
                     }
                     $this->addSoftwareVersionsComputer($a_toinsert);
                     if (!$no_history) {
                         foreach ($a_computerinventory['software'] as $a_software) {
                             $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                             $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                             $changes[0] = '0';
                             $changes[1] = "";
                             $changes[2] = $a_software['name'] . " - " . sprintf(__('%1$s (%2$s)'), $a_software['version'], $softwareversions_id);
                             $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                             $changes[0] = '0';
                             $changes[1] = "";
                             $changes[2] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id);
                             $this->addPrepareLog($softwareversions_id, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                         }
                     }
                 }
             }
         }
     }
     // * Virtualmachines
     if ($pfConfig->getValue("import_vm") == 1) {
         $db_computervirtualmachine = array();
         if ($no_history === FALSE) {
             $query = "SELECT `id`, `name`, `uuid`, `virtualmachinesystems_id`\n                     FROM `glpi_computervirtualmachines`\n                  WHERE `computers_id` = '{$computers_id}'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $db_computervirtualmachine[$idtmp] = $data1;
             }
         }
         $simplecomputervirtualmachine = array();
         if (isset($a_computerinventory['virtualmachine'])) {
             foreach ($a_computerinventory['virtualmachine'] as $key => $a_computervirtualmachine) {
                 $a_field = array('name', 'uuid', 'virtualmachinesystems_id');
                 foreach ($a_field as $field) {
                     if (isset($a_computervirtualmachine[$field])) {
                         $simplecomputervirtualmachine[$key][$field] = $a_computervirtualmachine[$field];
                     }
                 }
             }
         }
         foreach ($simplecomputervirtualmachine as $key => $arrays) {
             foreach ($db_computervirtualmachine as $keydb => $arraydb) {
                 if ($arrays == $arraydb) {
                     $input = array();
                     $input['id'] = $keydb;
                     if (isset($a_computerinventory['virtualmachine'][$key]['vcpu'])) {
                         $input['vcpu'] = $a_computerinventory['virtualmachine'][$key]['vcpu'];
                     }
                     if (isset($a_computerinventory['virtualmachine'][$key]['ram'])) {
                         $input['ram'] = $a_computerinventory['virtualmachine'][$key]['ram'];
                     }
                     if (isset($a_computerinventory['virtualmachine'][$key]['virtualmachinetypes_id'])) {
                         $input['virtualmachinetypes_id'] = $a_computerinventory['virtualmachine'][$key]['virtualmachinetypes_id'];
                     }
                     if (isset($a_computerinventory['virtualmachine'][$key]['virtualmachinestates_id'])) {
                         $input['virtualmachinestates_id'] = $a_computerinventory['virtualmachine'][$key]['virtualmachinestates_id'];
                     }
                     $computerVirtualmachine->update($input, !$no_history);
                     unset($simplecomputervirtualmachine[$key]);
                     unset($a_computerinventory['virtualmachine'][$key]);
                     unset($db_computervirtualmachine[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_computerinventory['virtualmachine']) == 0 && count($db_computervirtualmachine) == 0) {
             // Nothing to do
         } else {
             if (count($db_computervirtualmachine) != 0) {
                 // Delete virtualmachine in DB
                 foreach ($db_computervirtualmachine as $idtmp => $data) {
                     $computerVirtualmachine->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_computerinventory['virtualmachine']) != 0) {
                 foreach ($a_computerinventory['virtualmachine'] as $a_virtualmachine) {
                     $a_virtualmachine['computers_id'] = $computers_id;
                     $computerVirtualmachine->add($a_virtualmachine, array(), !$no_history);
                 }
             }
         }
     }
     if ($pfConfig->getValue("create_vm") == 1) {
         // Create VM based on information of section VIRTUALMACHINE
         $pfAgent = new PluginFusioninventoryAgent();
         // Use ComputerVirtualMachine::getUUIDRestrictRequest to get existant
         // vm in computer list
         $computervm = new Computer();
         if (isset($a_computerinventory['virtualmachine_creation']) && is_array($a_computerinventory['virtualmachine_creation'])) {
             foreach ($a_computerinventory['virtualmachine_creation'] as $a_vm) {
                 // Define location of physical computer (host)
                 $a_vm['locations_id'] = $computer->fields['locations_id'];
                 if (isset($a_vm['uuid']) && $a_vm['uuid'] != '') {
                     $query = "SELECT * FROM `glpi_computers`\n                        WHERE `uuid` " . ComputerVirtualMachine::getUUIDRestrictRequest($a_vm['uuid']) . "\n                        LIMIT 1";
                     // TODO: Add entity search
                     $result = $DB->query($query);
                     $computers_vm_id = 0;
                     while ($data = $DB->fetch_assoc($result)) {
                         $computers_vm_id = $data['id'];
                     }
                     if ($computers_vm_id == 0) {
                         // Add computer
                         $a_vm['entities_id'] = $computer->fields['entities_id'];
                         $computers_vm_id = $computervm->add($a_vm, array(), !$no_history);
                         // Manage networks
                         $this->manageNetworkPort($a_vm['networkport'], $computers_vm_id, FALSE);
                     } else {
                         if ($pfAgent->getAgentWithComputerid($computers_vm_id) === FALSE) {
                             // Update computer
                             $a_vm['id'] = $computers_vm_id;
                             $computervm->update($a_vm, !$no_history);
                             // Manage networks
                             $this->manageNetworkPort($a_vm['networkport'], $computers_vm_id, FALSE);
                         }
                     }
                 }
             }
         }
     }
     // * ComputerDisk
     if ($pfConfig->getValue("import_volume") != 0) {
         $db_computerdisk = array();
         if ($no_history === FALSE) {
             $query = "SELECT `id`, `name`, `device`, `mountpoint`\n                   FROM `glpi_computerdisks`\n                   WHERE `computers_id` = '" . $computers_id . "'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_computerdisk[$idtmp] = $data2;
             }
         }
         $simplecomputerdisk = array();
         foreach ($a_computerinventory['computerdisk'] as $key => $a_computerdisk) {
             $a_field = array('name', 'device', 'mountpoint');
             foreach ($a_field as $field) {
                 if (isset($a_computerdisk[$field])) {
                     $simplecomputerdisk[$key][$field] = $a_computerdisk[$field];
                 }
             }
         }
         foreach ($simplecomputerdisk as $key => $arrays) {
             $arrayslower = array_map('strtolower', $arrays);
             foreach ($db_computerdisk as $keydb => $arraydb) {
                 if ($arrayslower == $arraydb) {
                     $input = array();
                     $input['id'] = $keydb;
                     if (isset($a_computerinventory['computerdisk'][$key]['filesystems_id'])) {
                         $input['filesystems_id'] = $a_computerinventory['computerdisk'][$key]['filesystems_id'];
                     }
                     $input['totalsize'] = $a_computerinventory['computerdisk'][$key]['totalsize'];
                     $input['freesize'] = $a_computerinventory['computerdisk'][$key]['freesize'];
                     $input['_no_history'] = TRUE;
                     $computerDisk->update($input, FALSE);
                     unset($simplecomputerdisk[$key]);
                     unset($a_computerinventory['computerdisk'][$key]);
                     unset($db_computerdisk[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_computerinventory['computerdisk']) == 0 and count($db_computerdisk) == 0) {
             // Nothing to do
         } else {
             if (count($db_computerdisk) != 0) {
                 // Delete computerdisk in DB
                 foreach ($db_computerdisk as $idtmp => $data) {
                     $computerDisk->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_computerinventory['computerdisk']) != 0) {
                 foreach ($a_computerinventory['computerdisk'] as $a_computerdisk) {
                     $a_computerdisk['computers_id'] = $computers_id;
                     $a_computerdisk['is_dynamic'] = 1;
                     $a_computerdisk['_no_history'] = $no_history;
                     $computerDisk->add($a_computerdisk, array(), !$no_history);
                 }
             }
         }
     }
     // * Networkports
     if ($pfConfig->getValue("component_networkcard") != 0) {
         // Get port from unmanaged device if exist
         $this->manageNetworkPort($a_computerinventory['networkport'], $computers_id, $no_history);
     }
     // * Antivirus
     $db_antivirus = array();
     if ($no_history === FALSE) {
         $query = "SELECT `id`, `name`, `version`\n                  FROM `glpi_plugin_fusioninventory_inventorycomputerantiviruses`\n               WHERE `computers_id` = '{$computers_id}'";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             $idtmp = $data['id'];
             unset($data['id']);
             $data1 = Toolbox::addslashes_deep($data);
             $data2 = array_map('strtolower', $data1);
             $db_antivirus[$idtmp] = $data2;
         }
     }
     $simpleantivirus = array();
     foreach ($a_computerinventory['antivirus'] as $key => $a_antivirus) {
         $a_field = array('name', 'version');
         foreach ($a_field as $field) {
             if (isset($a_antivirus[$field])) {
                 $simpleantivirus[$key][$field] = $a_antivirus[$field];
             }
         }
     }
     foreach ($simpleantivirus as $key => $arrays) {
         $arrayslower = array_map('strtolower', $arrays);
         foreach ($db_antivirus as $keydb => $arraydb) {
             if ($arrayslower == $arraydb) {
                 $input = array();
                 $input = $a_computerinventory['antivirus'][$key];
                 $input['id'] = $keydb;
                 $pfInventoryComputerAntivirus->update($input, !$no_history);
                 unset($simpleantivirus[$key]);
                 unset($a_computerinventory['antivirus'][$key]);
                 unset($db_antivirus[$keydb]);
                 break;
             }
         }
     }
     if (count($a_computerinventory['antivirus']) == 0 and count($db_antivirus) == 0) {
         // Nothing to do
     } else {
         if (count($db_antivirus) != 0) {
             foreach ($db_antivirus as $idtmp => $data) {
                 $pfInventoryComputerAntivirus->delete(array('id' => $idtmp), 1);
             }
         }
         if (count($a_computerinventory['antivirus']) != 0) {
             foreach ($a_computerinventory['antivirus'] as $a_antivirus) {
                 $a_antivirus['computers_id'] = $computers_id;
                 $pfInventoryComputerAntivirus->add($a_antivirus, array(), !$no_history);
             }
         }
     }
     // * Licenseinfo
     $db_licenseinfo = array();
     if ($no_history === FALSE) {
         $query = "SELECT `id`, `name`, `fullname`, `serial`\n                  FROM `glpi_plugin_fusioninventory_computerlicenseinfos`\n               WHERE `computers_id` = '{$computers_id}'";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             $idtmp = $data['id'];
             unset($data['id']);
             $data1 = Toolbox::addslashes_deep($data);
             $data2 = array_map('strtolower', $data1);
             $db_licenseinfo[$idtmp] = $data2;
         }
     }
     foreach ($a_computerinventory['licenseinfo'] as $key => $arrays) {
         $arrayslower = array_map('strtolower', $arrays);
         foreach ($db_licenseinfo as $keydb => $arraydb) {
             if ($arrayslower == $arraydb) {
                 unset($a_computerinventory['licenseinfo'][$key]);
                 unset($db_licenseinfo[$keydb]);
                 break;
             }
         }
     }
     if (count($a_computerinventory['licenseinfo']) == 0 and count($db_licenseinfo) == 0) {
         // Nothing to do
     } else {
         if (count($db_licenseinfo) != 0) {
             foreach ($db_licenseinfo as $idtmp => $data) {
                 $pfComputerLicenseInfo->delete(array('id' => $idtmp), 1);
             }
         }
         if (count($a_computerinventory['licenseinfo']) != 0) {
             foreach ($a_computerinventory['licenseinfo'] as $a_licenseinfo) {
                 $a_licenseinfo['computers_id'] = $computers_id;
                 $pfComputerLicenseInfo->add($a_licenseinfo, array(), !$no_history);
             }
         }
     }
     // * Batteries
     /* Standby, see ticket http://forge.fusioninventory.org/issues/1907
              $db_batteries = array();
              if ($no_history === FALSE) {
                 $query = "SELECT `id`, `name`, `serial`
                       FROM `glpi_plugin_fusioninventory_inventorycomputerbatteries`
                    WHERE `computers_id` = '$computers_id'";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_assoc($result)) {
                    $idtmp = $data['id'];
                    unset($data['id']);
                    $data = Toolbox::addslashes_deep($data);
                    $data = array_map('strtolower', $data);
                    $db_batteries[$idtmp] = $data;
                 }
              }
              $simplebatteries = array();
              foreach ($a_computerinventory['batteries'] as $key=>$a_batteries) {
                 $a_field = array('name', 'serial');
                 foreach ($a_field as $field) {
                    if (isset($a_batteries[$field])) {
                       $simplebatteries[$key][$field] = $a_batteries[$field];
                    }
                 }
              }
              foreach ($simplebatteries as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 foreach ($db_batteries as $keydb => $arraydb) {
                    if ($arrayslower == $arraydb) {
                       $input = array();
                       $input = $a_computerinventory['batteries'][$key];
                       $input['id'] = $keydb;
                       $pfInventoryComputerBatteries->update($input);
                       unset($simplebatteries[$key]);
                       unset($a_computerinventory['batteries'][$key]);
                       unset($db_batteries[$keydb]);
                       break;
                    }
                 }
              }
              if (count($a_computerinventory['batteries']) == 0
                 AND count($db_batteries) == 0) {
                 // Nothing to do
              } else {
                 if (count($db_batteries) != 0) {
                    foreach ($db_batteries as $idtmp => $data) {
                       $pfInventoryComputerBatteries->delete(array('id'=>$idtmp), 1);
                    }
                 }
                 if (count($a_computerinventory['batteries']) != 0) {
                    foreach($a_computerinventory['batteries'] as $a_batteries) {
                       $a_batteries['computers_id'] = $computers_id;
                       $pfInventoryComputerBatteries->add($a_batteries, array(), FALSE);
                    }
                 }
              }
     */
     $entities_id = $_SESSION["plugin_fusioninventory_entity"];
     // * Monitors
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $a_monitors = array();
     foreach ($a_computerinventory['monitor'] as $key => $arrays) {
         $input = array();
         $input['itemtype'] = "Monitor";
         $input['name'] = $arrays['name'];
         $input['serial'] = $arrays['serial'];
         $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE));
         if (isset($data['found_equipment'])) {
             if ($data['found_equipment'][0] == 0) {
                 // add monitor
                 $arrays['entities_id'] = $entities_id;
                 $a_monitors[] = $monitor->add($arrays);
             } else {
                 $a_monitors[] = $data['found_equipment'][0];
             }
         }
     }
     $db_monitors = array();
     $query = "SELECT `glpi_monitors`.`id`,\n                       `glpi_computers_items`.`id` as link_id\n            FROM `glpi_computers_items`\n         LEFT JOIN `glpi_monitors` ON `items_id`=`glpi_monitors`.`id`\n         WHERE `itemtype`='Monitor'\n            AND `computers_id`='" . $computers_id . "'\n            AND `entities_id`='" . $entities_id . "'\n            AND `glpi_computers_items`.`is_dynamic`='1'\n            AND `glpi_monitors`.`is_global`='0'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['link_id'];
         unset($data['link_id']);
         $db_monitors[$idtmp] = $data['id'];
     }
     if (count($db_monitors) == 0) {
         foreach ($a_monitors as $monitors_id) {
             $input = array();
             $input['computers_id'] = $computers_id;
             $input['itemtype'] = 'Monitor';
             $input['items_id'] = $monitors_id;
             $input['is_dynamic'] = 1;
             $input['_no_history'] = $no_history;
             $computer_Item->add($input, array(), !$no_history);
         }
     } else {
         // Check all fields from source:
         foreach ($a_monitors as $key => $monitors_id) {
             foreach ($db_monitors as $keydb => $monits_id) {
                 if ($monitors_id == $monits_id) {
                     unset($a_monitors[$key]);
                     unset($db_monitors[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_monitors) == 0 and count($db_monitors) == 0) {
             // Nothing to do
         } else {
             if (count($db_monitors) != 0) {
                 // Delete monitors links in DB
                 foreach ($db_monitors as $idtmp => $monits_id) {
                     $computer_Item->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_monitors) != 0) {
                 foreach ($a_monitors as $key => $monitors_id) {
                     $input = array();
                     $input['computers_id'] = $computers_id;
                     $input['itemtype'] = 'Monitor';
                     $input['items_id'] = $monitors_id;
                     $input['is_dynamic'] = 1;
                     $input['_no_history'] = $no_history;
                     $computer_Item->add($input, array(), !$no_history);
                 }
             }
         }
     }
     // * Printers
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $a_printers = array();
     foreach ($a_computerinventory['printer'] as $key => $arrays) {
         $input = array();
         $input['itemtype'] = "Printer";
         $input['name'] = $arrays['name'];
         $input['serial'] = $arrays['serial'];
         $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE));
         if (isset($data['found_equipment'])) {
             if ($data['found_equipment'][0] == 0) {
                 // add printer
                 $arrays['entities_id'] = $entities_id;
                 $a_printers[] = $printer->add($arrays);
             } else {
                 $a_printers[] = $data['found_equipment'][0];
             }
         }
     }
     $db_printers = array();
     $query = "SELECT `glpi_printers`.`id`, `glpi_computers_items`.`id` as link_id\n            FROM `glpi_computers_items`\n         LEFT JOIN `glpi_printers` ON `items_id`=`glpi_printers`.`id`\n         WHERE `itemtype`='Printer'\n            AND `computers_id`='" . $computers_id . "'\n            AND `entities_id`='" . $entities_id . "'\n            AND `glpi_computers_items`.`is_dynamic`='1'\n            AND `glpi_printers`.`is_global`='0'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['link_id'];
         unset($data['link_id']);
         $db_printers[$idtmp] = $data['id'];
     }
     if (count($db_printers) == 0) {
         foreach ($a_printers as $printers_id) {
             $input['entities_id'] = $entities_id;
             $input['computers_id'] = $computers_id;
             $input['itemtype'] = 'Printer';
             $input['items_id'] = $printers_id;
             $input['is_dynamic'] = 1;
             $input['_no_history'] = $no_history;
             $computer_Item->add($input, array(), !$no_history);
         }
     } else {
         // Check all fields from source:
         foreach ($a_printers as $key => $printers_id) {
             foreach ($db_printers as $keydb => $prints_id) {
                 if ($printers_id == $prints_id) {
                     unset($a_printers[$key]);
                     unset($db_printers[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_printers) == 0 and count($db_printers) == 0) {
             // Nothing to do
         } else {
             if (count($db_printers) != 0) {
                 // Delete printers links in DB
                 foreach ($db_printers as $idtmp => $data) {
                     $computer_Item->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_printers) != 0) {
                 foreach ($a_printers as $printers_id) {
                     $input['entities_id'] = $entities_id;
                     $input['computers_id'] = $computers_id;
                     $input['itemtype'] = 'Printer';
                     $input['items_id'] = $printers_id;
                     $input['is_dynamic'] = 1;
                     $input['_no_history'] = $no_history;
                     $computer_Item->add($input, array(), !$no_history);
                 }
             }
         }
     }
     // * Peripheral
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $a_peripherals = array();
     foreach ($a_computerinventory['peripheral'] as $key => $arrays) {
         $input = array();
         $input['itemtype'] = "Peripheral";
         $input['name'] = $arrays['name'];
         $input['serial'] = $arrays['serial'];
         $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE));
         if (isset($data['found_equipment'])) {
             if ($data['found_equipment'][0] == 0) {
                 // add peripheral
                 $arrays['entities_id'] = $entities_id;
                 $a_peripherals[] = $peripheral->add($arrays);
             } else {
                 $a_peripherals[] = $data['found_equipment'][0];
             }
         }
     }
     $db_peripherals = array();
     $query = "SELECT `glpi_peripherals`.`id`, `glpi_computers_items`.`id` as link_id\n            FROM `glpi_computers_items`\n         LEFT JOIN `glpi_peripherals` ON `items_id`=`glpi_peripherals`.`id`\n         WHERE `itemtype`='Peripheral'\n            AND `computers_id`='" . $computers_id . "'\n            AND `entities_id`='" . $entities_id . "'\n            AND `glpi_computers_items`.`is_dynamic`='1'\n      AND `glpi_peripherals`.`is_global`='0'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['link_id'];
         unset($data['link_id']);
         $db_peripherals[$idtmp] = $data['id'];
     }
     if (count($db_peripherals) == 0) {
         foreach ($a_peripherals as $peripherals_id) {
             $input = array();
             $input['computers_id'] = $computers_id;
             $input['itemtype'] = 'Peripharal';
             $input['items_id'] = $peripherals_id;
             $input['is_dynamic'] = 1;
             $input['_no_history'] = $no_history;
             $computer_Item->add($input, array(), !$no_history);
         }
     } else {
         // Check all fields from source:
         foreach ($a_peripherals as $key => $peripherals_id) {
             foreach ($db_peripherals as $keydb => $periphs_id) {
                 if ($peripherals_id == $periphs_id) {
                     unset($a_peripherals[$key]);
                     unset($db_peripherals[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_peripherals) == 0 and count($db_peripherals) == 0) {
             // Nothing to do
         } else {
             if (count($db_peripherals) != 0) {
                 // Delete peripherals links in DB
                 foreach ($db_peripherals as $idtmp => $data) {
                     $computer_Item->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_peripherals) != 0) {
                 foreach ($a_peripherals as $peripherals_id) {
                     $input = array();
                     $input['computers_id'] = $computers_id;
                     $input['itemtype'] = 'Peripharal';
                     $input['items_id'] = $peripherals_id;
                     $input['is_dynamic'] = 1;
                     $input['_no_history'] = $no_history;
                     $computer_Item->add($input, array(), !$no_history);
                 }
             }
         }
     }
     // * storage
     // Manage by uuid to correspond with GLPI data
     //         $db_storage = array();
     //         if ($no_history === FALSE) {
     //            $query = "SELECT `id`, `uuid` FROM ".
     //                "`glpi_plugin_fusioninventory_inventorycomputerstorages`
     //                WHERE `computers_id` = '$computers_id'";
     //            $result = $DB->query($query);
     //            while ($data = $DB->fetch_assoc($result)) {
     //               $idtmp = $data['id'];
     //               unset($data['id']);
     //               $data = Toolbox::addslashes_deep($data);
     //               $data = array_map('strtolower', $data);
     //               $db_storage[$idtmp] = $data;
     //            }
     //         }
     //         if (count($db_storage) == 0) {
     //            $a_links = array();
     //            $a_uuid  = array();
     //            foreach ($a_computerinventory['storage'] as $a_storage) {
     //               $a_storage['computers_id'] = $computers_id;
     //               $insert_id = $pfInventoryComputerStorage->add($a_storage);
     //               if (isset($a_storage['uuid'])) {
     //                  $a_uuid[$a_storage['uuid']] = $insert_id;
     //                  if (isset($a_storage['uuid_link'])) {
     //                     if (is_array($a_storage['uuid_link'])) {
     //                        $a_links[$insert_id] = $a_storage['uuid_link'];
     //                     } else {
     //                        $a_links[$insert_id][] = $a_storage['uuid_link'];
     //                     }
     //                  }
     //               }
     //            }
     //            foreach ($a_links as $id=>$data) {
     //               foreach ($data as $num=>$uuid) {
     //                  $a_links[$id][$num] = $a_uuid[$uuid];
     //               }
     //            }
     //            foreach ($a_links as $id=>$data) {
     //               foreach ($data as $id2) {
     //                  $input = array();
     //                  $input['plugin_fusioninventory_inventorycomputerstorages_id_1'] = $id;
     //                  $input['plugin_fusioninventory_inventorycomputerstorages_id_2'] = $id2;
     //                  $pfInventoryComputerStorage_Storage->add($input);
     //               }
     //            }
     //         } else {
     //            // Check only field *** from source:
     //
     //         }
     $this->addLog();
 }
 /**
  * @param $plugin_ocsinventoryng_ocsservers_id
  * @param $itemtype
  * @param int $ID
  * @param $ocsSnmp
  * @param $loc_id
  * @param $dom_id
  * @param $action
  * @param bool $linked
  * @return int
  */
 static function addOrUpdateComputer($plugin_ocsinventoryng_ocsservers_id, $itemtype, $ID = 0, $ocsSnmp, $loc_id, $dom_id, $action, $linked = false)
 {
     global $DB;
     $snmpDevice = new $itemtype();
     $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($plugin_ocsinventoryng_ocsservers_id);
     $input = array("is_dynamic" => 1, "entities_id" => isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : 0);
     if ($cfg_ocs['importsnmp_name'] && $action == "add" || $cfg_ocs['linksnmp_name'] && $linked || $action == "update" && $cfg_ocs['importsnmp_name'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_name'] && $linked) {
         $input["name"] = $ocsSnmp['META']['NAME'];
     }
     if ($cfg_ocs['importsnmp_contact'] && $action == "add" || $cfg_ocs['linksnmp_contact'] && $linked || $action == "update" && $cfg_ocs['importsnmp_name'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_name'] && $linked) {
         $input["contact"] = $ocsSnmp['META']['CONTACT'];
     }
     if ($cfg_ocs['importsnmp_comment'] && $action == "add" || $cfg_ocs['linksnmp_comment'] && $linked || $action == "update" && $cfg_ocs['importsnmp_name'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_name'] && $linked) {
         $input["comment"] = $ocsSnmp['META']['DESCRIPTION'];
     }
     if ($loc_id > 0) {
         $input["locations_id"] = $loc_id;
     }
     if ($dom_id > 0 && $itemtype != "Phone") {
         $input["domains_id"] = $dom_id;
     }
     $id_item = 0;
     if ($action == "add") {
         $id_item = $snmpDevice->add($input, array('unicity_error_message' => true), $cfg_ocs['history_hardware']);
     } else {
         $input["id"] = $ID;
         $id_item = $ID;
         if ($snmpDevice->getFromDB($id_item)) {
             $input["entities_id"] = $snmpDevice->fields['entities_id'];
         }
         $snmpDevice->update($input, $cfg_ocs['history_hardware'], array('unicity_error_message' => false, '_no_history' => !$cfg_ocs['history_hardware']));
     }
     if ($id_item > 0 && isset($ocsSnmp['MEMORIES']) && ($cfg_ocs['importsnmp_computermemory'] && $action == "add" || $cfg_ocs['linksnmp_computermemory'] && $linked || $action == "update" && $cfg_ocs['importsnmp_computermemory'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_computermemory'] && $linked) && count($ocsSnmp['MEMORIES']) > 0 && $ocsSnmp['MEMORIES'][0]['CAPACITY'] > 0) {
         $dev['designation'] = __('Computer Memory', 'ocsinventoryng');
         $item = new $itemtype();
         $entity = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : 0;
         if ($item->getFromDB($id_item)) {
             $entity = $item->fields['entities_id'];
         }
         $dev['entities_id'] = $entity;
         $device = new DeviceMemory();
         $device_id = $device->import($dev);
         if ($device_id) {
             $CompDevice = new Item_DeviceMemory();
             if ($cfg_ocs['history_devices']) {
                 $table = getTableForItemType("Item_DeviceMemory");
                 $query = "DELETE\n                            FROM `" . $table . "`\n                            WHERE `items_id` = '" . $id_item . "'\n                            AND `itemtype` = '" . $itemtype . "'";
                 $DB->query($query);
             }
             //            CANNOT USE BEFORE 9.1.2 - for _no_history problem
             //            $CompDevice->deleteByCriteria(array('items_id' => $id_item,
             //               'itemtype' => $itemtype), 1);
             $CompDevice->add(array('items_id' => $id_item, 'itemtype' => $itemtype, 'size' => $ocsSnmp['MEMORIES'][0]['CAPACITY'], 'entities_id' => $entity, 'devicememories_id' => $device_id, 'is_dynamic' => 1), array(), $cfg_ocs['history_devices']);
         }
     }
     if ($id_item > 0 && isset($ocsSnmp['NETWORKS']) && ($cfg_ocs['importsnmp_computernetworkcards'] && $action == "add" || $cfg_ocs['linksnmp_computernetworkcards'] && $linked || $action == "update" && $cfg_ocs['importsnmp_computernetworkcards'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_computernetworkcards'] && $linked) && count($ocsSnmp['NETWORKS']) > 0) {
         $CompDevice = new Item_DeviceNetworkCard();
         if ($cfg_ocs['history_devices']) {
             $table = getTableForItemType("Item_DeviceNetworkCard");
             $query = "DELETE\n                            FROM `" . $table . "`\n                            WHERE `items_id` = '" . $id_item . "'\n                            AND `itemtype` = '" . $itemtype . "'";
             $DB->query($query);
         }
         //            CANNOT USE BEFORE 9.1.2 - for _no_history problem
         //         $CompDevice->deleteByCriteria(array('items_id' => $id_item,
         //                                             'itemtype' => $itemtype), 1);
         foreach ($ocsSnmp['NETWORKS'] as $k => $net) {
             $dev["designation"] = $net['SLOT'];
             $dev["comment"] = $net['TYPE'];
             $mac = $net['MACADDR'];
             /*$speed = 0;
               if (strstr($processor['SPEED'], "GHz")) {
                  $speed = str_replace("GHz", "", $processor['SPEED']);
                  $speed = $speed * 1000;
               }
               if (strstr($processor['SPEED'], "MHz")) {
                  $speed = str_replace("MHz", "", $processor['SPEED']);
               }*/
             $item = new $itemtype();
             $entity = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : 0;
             if ($item->getFromDB($id_item)) {
                 $entity = $item->fields['entities_id'];
             }
             $dev['entities_id'] = $entity;
             $device = new DeviceNetworkCard();
             $device_id = $device->import($dev);
             if ($device_id) {
                 $CompDevice->add(array('items_id' => $id_item, 'itemtype' => $itemtype, 'mac' => $mac, 'entities_id' => $entity, 'devicenetworkcards_id' => $device_id, 'is_dynamic' => 1), array(), $cfg_ocs['history_devices']);
             }
         }
     }
     if ($id_item > 0 && isset($ocsSnmp['SOFTWARES']) && ($cfg_ocs['importsnmp_computersoftwares'] && $action == "add" || $cfg_ocs['linksnmp_computersoftwares'] && $linked || $action == "update" && $cfg_ocs['importsnmp_computersoftwares'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_computersoftwares'] && $linked) && count($ocsSnmp['SOFTWARES']) > 0) {
         $entity = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : 0;
         if ($item->getFromDB($id_item)) {
             $entity = $item->fields['entities_id'];
         }
         PluginOcsinventoryngOcsServer::updateSoftware($cfg_ocs, $id_item, $ocsSnmp["SOFTWARES"], $entity);
     }
     if ($id_item > 0 && isset($ocsSnmp['CPU']) && ($cfg_ocs['importsnmp_computerprocessors'] && $action == "add" || $cfg_ocs['linksnmp_computerprocessors'] && $linked || $action == "update" && $cfg_ocs['importsnmp_computerprocessors'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_computerprocessors'] && $linked) && count($ocsSnmp['CPU']) > 0) {
         $CompDevice = new Item_DeviceProcessor();
         if ($cfg_ocs['history_devices']) {
             $table = getTableForItemType("Item_DeviceProcessor");
             $query = "DELETE\n                            FROM `" . $table . "`\n                            WHERE `items_id` = '" . $id_item . "'\n                            AND `itemtype` = '" . $itemtype . "'";
             $DB->query($query);
         }
         //            CANNOT USE BEFORE 9.1.2 - for _no_history problem
         //         $CompDevice->deleteByCriteria(array('items_id' => $id_item,
         //                                             'itemtype' => $itemtype), 1);
         foreach ($ocsSnmp['CPU'] as $k => $processor) {
             $dev["designation"] = $processor['TYPE'];
             $dev["manufacturers_id"] = Dropdown::importExternal('Manufacturer', PluginOcsinventoryngOcsServer::encodeOcsDataInUtf8($cfg_ocs['ocs_db_utf8'], $processor['MANUFACTURER']));
             $speed = 0;
             if (strstr($processor['SPEED'], "GHz")) {
                 $speed = str_replace("GHz", "", $processor['SPEED']);
                 $speed = $speed * 1000;
             }
             if (strstr($processor['SPEED'], "MHz")) {
                 $speed = str_replace("MHz", "", $processor['SPEED']);
             }
             $item = new $itemtype();
             $entity = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : 0;
             if ($item->getFromDB($id_item)) {
                 $entity = $item->fields['entities_id'];
             }
             $dev['entities_id'] = $entity;
             $device = new DeviceProcessor();
             $device_id = $device->import($dev);
             if ($device_id) {
                 $CompDevice->add(array('items_id' => $id_item, 'itemtype' => $itemtype, 'frequency' => $speed, 'entities_id' => $entity, 'deviceprocessors_id' => $device_id, 'is_dynamic' => 1), array(), $cfg_ocs['history_devices']);
             }
         }
     }
     if ($id_item > 0 && isset($ocsSnmp['VIRTUALMACHINES']) && ($cfg_ocs['importsnmp_computervm'] && $action == "add" || $cfg_ocs['linksnmp_computervm'] && $linked || $action == "update" && $cfg_ocs['importsnmp_computervm'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_computervm'] && $linked) && count($ocsSnmp['VIRTUALMACHINES']) > 0) {
         $already_processed = array();
         $virtualmachine = new ComputerVirtualMachine();
         foreach ($ocsSnmp['VIRTUALMACHINES'] as $k => $ocsVirtualmachine) {
             $ocsVirtualmachine = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($ocsVirtualmachine));
             $vm = array();
             $vm['name'] = $ocsVirtualmachine['NAME'];
             $vm['vcpu'] = $ocsVirtualmachine['CPU'];
             $vm['ram'] = $ocsVirtualmachine['MEMORY'];
             $vm['uuid'] = $ocsVirtualmachine['UUID'];
             $vm['computers_id'] = $id_item;
             $vm['is_dynamic'] = 1;
             $vm['virtualmachinestates_id'] = Dropdown::importExternal('VirtualMachineState', $ocsVirtualmachine['POWER']);
             //$vm['virtualmachinetypes_id'] = Dropdown::importExternal('VirtualMachineType', $ocsVirtualmachine['VMTYPE']);
             //$vm['virtualmachinesystems_id'] = Dropdown::importExternal('VirtualMachineType', $ocsVirtualmachine['SUBSYSTEM']);
             $query = "SELECT `id`\n                         FROM `glpi_computervirtualmachines`\n                         WHERE `computers_id`='{$id_item}'\n                            AND `is_dynamic`";
             if ($ocsVirtualmachine['UUID']) {
                 $query .= " AND `uuid`='" . $ocsVirtualmachine['UUID'] . "'";
             } else {
                 // Failback on name
                 $query .= " AND `name`='" . $ocsVirtualmachine['NAME'] . "'";
             }
             $results = $DB->query($query);
             if ($DB->numrows($results) > 0) {
                 $id = $DB->result($results, 0, 'id');
             } else {
                 $id = 0;
             }
             if (!$id) {
                 $virtualmachine->reset();
                 $id_vm = $virtualmachine->add($vm, array(), $cfg_ocs['history_vm']);
                 if ($id_vm) {
                     $already_processed[] = $id_vm;
                 }
             } else {
                 if ($virtualmachine->getFromDB($id)) {
                     $vm['id'] = $id;
                     $virtualmachine->update($vm, $cfg_ocs['history_vm']);
                 }
                 $already_processed[] = $id;
             }
             // Delete Unexisting Items not found in OCS
             //Look for all ununsed virtual machines
             $query = "SELECT `id`\n                      FROM `glpi_computervirtualmachines`\n                      WHERE `computers_id`='{$id_item}'\n                         AND `is_dynamic`";
             if (!empty($already_processed)) {
                 $query .= "AND `id` NOT IN (" . implode(',', $already_processed) . ")";
             }
             foreach ($DB->request($query) as $data) {
                 //Delete all connexions
                 $virtualmachine->delete(array('id' => $data['id'], '_ocsservers_id' => $plugin_ocsinventoryng_ocsservers_id, '_no_history' => !$cfg_ocs['history_vm']), true, $cfg_ocs['history_vm']);
             }
         }
     }
     if ($id_item > 0 && ($cfg_ocs['importsnmp_createport'] && $action == "add" || $cfg_ocs['linksnmp_createport'] && $linked || $action == "update" && $cfg_ocs['importsnmp_createport'] && !$linked || $action == "update" && $cfg_ocs['linksnmp_createport'] && $linked)) {
         //Add network port
         $ip = $ocsSnmp['META']['IPADDR'];
         $mac = $ocsSnmp['META']['MACADDR'];
         $np = new NetworkPort();
         $np->getFromDBByQuery("WHERE `mac` LIKE '{$mac}' AND `items_id` = '{$id_item}' AND `itemtype` LIKE '{$itemtype}' ");
         if (count($np->fields) < 1) {
             $item = new $itemtype();
             $entity = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : 0;
             if ($item->getFromDB($id_item)) {
                 $entity = $item->fields['entities_id'];
             }
             $port_input = array('name' => $ocsSnmp['META']['NAME'], 'mac' => $mac, 'items_id' => $id_item, 'itemtype' => $itemtype, 'instantiation_type' => "NetworkPortEthernet", "entities_id" => $entity, "NetworkName__ipaddresses" => array("-100" => $ip), '_create_children' => 1, 'is_deleted' => 0);
             $np->add($port_input, array(), $cfg_ocs['history_network']);
         }
     }
     return $id_item;
 }
 function cleanDBonPurge()
 {
     global $DB;
     $query = "DELETE\n                FROM `glpi_computers_softwareversions`\n                WHERE `computers_id` = '" . $this->fields['id'] . "'";
     $result = $DB->query($query);
     $query = "SELECT `id`\n                FROM `glpi_computers_items`\n                WHERE `computers_id` = '" . $this->fields['id'] . "'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) > 0) {
             $conn = new Computer_Item();
             while ($data = $DB->fetch_array($result)) {
                 $data['_no_auto_action'] = true;
                 $conn->delete($data);
             }
         }
     }
     $query = "DELETE\n                FROM `glpi_registrykeys`\n                WHERE `computers_id` = '" . $this->fields['id'] . "'";
     $result = $DB->query($query);
     $compdev = new Computer_Device();
     $compdev->cleanDBonItemDelete('Computer', $this->fields['id']);
     $query = "DELETE\n                FROM `glpi_ocslinks`\n                WHERE `computers_id` = '" . $this->fields['id'] . "'";
     $result = $DB->query($query);
     $disk = new ComputerDisk();
     $disk->cleanDBonItemDelete('Computer', $this->fields['id']);
     $vm = new ComputerVirtualMachine();
     $vm->cleanDBonItemDelete('Computer', $this->fields['id']);
 }
            case 10:
                showNotesForm($_POST['target'], 'Computer', $_POST["id"]);
                break;
            case 11:
                Reservation::showForItem('Computer', $_POST["id"]);
                break;
            case 12:
                Log::showForItem($computer);
                break;
            case 13:
                OcsLink::showForItem($computer);
                OcsServer::editLock($_POST['target'], $_POST["id"]);
                break;
            case 14:
                RegistryKey::showForComputer($_POST["id"]);
                break;
            case 20:
                ComputerDisk::showForComputer($computer);
                break;
            case 21:
                ComputerVirtualMachine::showForVirtualMachine($computer);
                ComputerVirtualMachine::showForComputer($computer);
                break;
            default:
                if (!Plugin::displayAction($computer, $_REQUEST['glpi_tab'])) {
                    Computer_Device::showForComputer($computer);
                }
        }
    }
}
ajaxFooter();
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file:
// Purpose of file:
// ----------------------------------------------------------------------
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
header_nocache();
if (!isset($_POST['id'])) {
    exit;
}
if (!isset($_REQUEST['glpi_tab'])) {
    exit;
}
$disk = new ComputerVirtualMachine();
if (isset($_POST["id"]) && $_POST['id'] > 0 && $disk->can($_POST['id'], 'r')) {
    switch ($_REQUEST['glpi_tab']) {
        default:
            if (!Plugin::displayAction($disk, $_REQUEST['glpi_tab'])) {
            }
    }
}
ajaxFooter();
Example #10
0
 function cleanDBonPurge()
 {
     $csv = new Computer_SoftwareVersion();
     $csv->cleanDBonItemDelete('Computer', $this->fields['id']);
     $csl = new Computer_SoftwareLicense();
     $csl->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ip = new Item_Problem();
     $ip->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ci = new Computer_Item();
     $ci->cleanDBonItemDelete('Computer', $this->fields['id']);
     Item_Devices::cleanItemDeviceDBOnItemDelete('Computer', $this->fields['id']);
     $disk = new ComputerDisk();
     $disk->cleanDBonItemDelete('Computer', $this->fields['id']);
     $vm = new ComputerVirtualMachine();
     $vm->cleanDBonItemDelete('Computer', $this->fields['id']);
 }
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file:
// Purpose of file:
// ----------------------------------------------------------------------
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
if (!isset($_GET["id"])) {
    $_GET["id"] = "";
}
if (!isset($_GET["computers_id"])) {
    $_GET["computers_id"] = "";
}
$disk = new ComputerVirtualMachine();
if (isset($_POST["add"])) {
    $disk->check(-1, 'w', $_POST);
    if ($newID = $disk->add($_POST)) {
        Event::log($_POST['computers_id'], "computers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][21]);
    }
    glpi_header($_SERVER['HTTP_REFERER']);
} else {
    if (isset($_POST["delete"])) {
        $disk->check($_POST["id"], 'w');
        if ($disk->delete($_POST)) {
            Event::log($disk->fields['computers_id'], "computers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][21]);
        }
        $computer = new Computer();
        $computer->getFromDB($disk->fields['computers_id']);
        glpi_header(getItemTypeFormURL('Computer') . '?id=' . $disk->fields['computers_id'] . ($computer->fields['is_template'] ? "&withtemplate=1" : ""));
Example #12
0
 /**
  *
  * Synchronize virtual machines
  *
  * @param unknown $computers_id
  * @param unknown $ocsid
  * @param unknown $ocsservers_id
  * @param unknown $cfg_ocs
  * @param unknown $dohistory
  * @return boolean
  */
 static function updateVirtualMachines($computers_id, $ocsComuter, $ocsservers_id, $cfg_ocs, $dohistory)
 {
     global $DB;
     $already_processed = array();
     $virtualmachine = new ComputerVirtualMachine();
     if (isset($ocsComuter["VIRTUALMACHINES"])) {
         $ocsVirtualmachines = $ocsComuter["VIRTUALMACHINES"];
         if (count($ocsVirtualmachines) > 0) {
             foreach ($ocsVirtualmachines as $ocsVirtualmachine) {
                 $ocsVirtualmachine = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($ocsVirtualmachine));
                 $vm = array();
                 $vm['name'] = $ocsVirtualmachine['NAME'];
                 $vm['vcpu'] = $ocsVirtualmachine['VCPU'];
                 $vm['ram'] = $ocsVirtualmachine['MEMORY'];
                 $vm['uuid'] = $ocsVirtualmachine['UUID'];
                 $vm['computers_id'] = $computers_id;
                 $vm['is_dynamic'] = 1;
                 $vm['virtualmachinestates_id'] = Dropdown::importExternal('VirtualMachineState', $ocsVirtualmachine['STATUS']);
                 $vm['virtualmachinetypes_id'] = Dropdown::importExternal('VirtualMachineType', $ocsVirtualmachine['VMTYPE']);
                 $vm['virtualmachinesystems_id'] = Dropdown::importExternal('VirtualMachineType', $ocsVirtualmachine['SUBSYSTEM']);
                 $query = "SELECT `id`\n                         FROM `glpi_computervirtualmachines`\n                         WHERE `computers_id`='{$computers_id}'\n                            AND `is_dynamic`";
                 if ($ocsVirtualmachine['UUID']) {
                     $query .= " AND `uuid`='" . $ocsVirtualmachine['UUID'] . "'";
                 } else {
                     // Failback on name
                     $query .= " AND `name`='" . $ocsVirtualmachine['NAME'] . "'";
                 }
                 $results = $DB->query($query);
                 if ($DB->numrows($results) > 0) {
                     $id = $DB->result($results, 0, 'id');
                 } else {
                     $id = 0;
                 }
                 if (!$id) {
                     $virtualmachine->reset();
                     if (!$dohistory) {
                         $vm['_no_history'] = true;
                     }
                     $id_vm = $virtualmachine->add($vm);
                     if ($id_vm) {
                         $already_processed[] = $id_vm;
                     }
                 } else {
                     if ($virtualmachine->getFromDB($id)) {
                         $vm['id'] = $id;
                         $virtualmachine->update($vm);
                     }
                     $already_processed[] = $id;
                 }
             }
         }
     }
     // Delete Unexisting Items not found in OCS
     //Look for all ununsed virtual machines
     $query = "SELECT `id`\n                FROM `glpi_computervirtualmachines`\n                WHERE `computers_id`='{$computers_id}'\n                   AND `is_dynamic`";
     if (!empty($already_processed)) {
         $query .= "AND `id` NOT IN (" . implode(',', $already_processed) . ")";
     }
     foreach ($DB->request($query) as $data) {
         //Delete all connexions
         $virtualmachine->delete(array('id' => $data['id'], '_ocsservers_id' => $ocsservers_id), true);
     }
 }
 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();
     $pmConfig = new PluginMonitoringConfig();
     $computerType = new ComputerType();
     $a_services = array();
     $i = 0;
     // Get computer type contener / VM
     $conteners = $computerType->find("`name`='BSDJail'");
     $pmConfig->getFromDB(1);
     // TODO: only contacts in allowed entities ...
     // Prepare individual contacts
     $a_contacts_entities = array();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n         AND `users_id`>0");
     foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
             $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
     }
     // Prepare groups contacts
     $group = new Group();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringComponentscatalog'\n         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`\n            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_single = array();
         $a_hostname_type = array();
         $a_hostname_id = array();
         $queryh = "SELECT * FROM `glpi_plugin_monitoring_componentscatalogs_hosts`\n               WHERE `id` = '" . $data['plugin_monitoring_componentscatalogs_hosts_id'] . "'\n               LIMIT 1";
         $resulth = $DB->query($queryh);
         $hostname = '';
         $plugin_monitoring_componentscatalogs_id = 0;
         $computerTypes_id = 0;
         $entities_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'])) {
                     $h = self::shinkenFilter($item->fields['name']);
                     $a_hostname_single[] = $h;
                     if ($pmConfig->fields['append_id_hostname'] == 1) {
                         $h .= "-" . $datah['items_id'];
                     }
                     $a_hostname[] = $h;
                     $a_hostname_type[] = $datah['itemtype'];
                     $a_hostname_id[] = $datah['items_id'];
                     $hostname = $item->fields['name'];
                     $entities_id = $item->fields['entities_id'];
                     $plugin_monitoring_componentscatalogs_id = $datah['plugin_monitoring_componentscalalog_id'];
                     if ($itemtype == 'Computer') {
                         $computerTypes_id = $item->fields['computertypes_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'] : self::shinkenFilter($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'] .= '-' . self::shinkenFilter($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($a_hostname_id[0], $a_hostname_type[0], '');
                         $alias_command = str_replace("[[IP]]", $ip, $alias_command);
                     }
                     if (current($a_hostname_type) == 'Computer') {
                         if ($pmConfig->fields['nrpe_prefix_contener'] == 1) {
                             if (isset($conteners[$computerTypes_id])) {
                                 // get Host of contener/VM
                                 $where = "LOWER(`uuid`)" . ComputerVirtualMachine::getUUIDRestrictRequest($item->fields['uuid']);
                                 $hosts = getAllDatasFromTable('glpi_computervirtualmachines', $where);
                                 if (!empty($hosts)) {
                                     $host = current($hosts);
                                     //                                 $ip = PluginMonitoringHostaddress::getIp($host['computers_id'], 'Computer', '');
                                     $alias_command = current($a_hostname_single) . "_" . $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'\n                  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`\n                        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'];
                 $timeperiodsuffix = '-' . $pmHostconfig->getValueAncestor('jetlag', $entities_id);
                 if ($timeperiodsuffix == '-0') {
                     $timeperiodsuffix = '';
                 }
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'] . $timeperiodsuffix;
                 }
                 $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';
                 $timeperiodsuffix = '-' . $pmHostconfig->getValueAncestor('jetlag', $entities_id);
                 if ($timeperiodsuffix == '-0') {
                     $timeperiodsuffix = '';
                 }
                 if ($calendar->getFromDB($a_component['calendars_id'])) {
                     $a_services[$i]['check_period'] = $calendar->fields['name'] . $timeperiodsuffix;
                 }
             }
             // 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'\n         AND `users_id`>0");
     foreach ($a_list_contact as $data) {
         $contactentities = getSonsOf('glpi_entities', $data['entities_id']);
         if (isset($a_contacts_entities[$data['items_id']][$data['users_id']])) {
             $contactentities = array_merge($contactentities, $a_contacts_entities[$data['items_id']][$data['users_id']]);
         }
         $a_contacts_entities[$data['items_id']][$data['users_id']] = $contactentities;
     }
     // Prepare groups contacts
     $group = new Group();
     $a_list_contact = $pmContact_Item->find("`itemtype`='PluginMonitoringServicescatalog'\n         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`\n            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 = self::shinkenFilter($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 . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 } else {
                                     $a_group[$gdata['id']] .= $operator . $hostname . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 }
                             } else {
                                 $a_group[$gdata['id']] = $gdata['operator'] . " " . $hostname . "," . self::shinkenFilter($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'] = self::shinkenFilter($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'\n                  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`\n                        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 = self::shinkenFilter($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 . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 } else {
                                     $a_group[$serviceFakeId] .= $operator . $hostname . "," . self::shinkenFilter($pmService->getName(array('shinken' => true)));
                                 }
                             } else {
                                 $a_group[$serviceFakeId] = $BRoperator . " " . $hostname . "," . self::shinkenFilter($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'] = self::shinkenFilter($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'] = self::shinkenFilter($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'\n                     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`\n                           WHERE `groups_id`='" . $data_contact['groups_id'] . "'";
                                 $resultg = $DB->query($queryg);
                                 while ($datag = $DB->fetch_array($resultg)) {
                                     if (in_array($data['entities_id'], $a_contacts_entities[$dataBA['id']][$datag['users_id']])) {
                                         $user->getFromDB($datag['users_id']);
                                         $a_contacts[] = $user->fields['name'];
                                     }
                                 }
                             }
                         }
                     }
                     $a_contacts_unique = array_unique($a_contacts);
                     $a_services[$i]['contacts'] = implode(',', $a_contacts_unique);
                     $i++;
                 }
             }
         }
     }
     PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateServicesCfg business rules templates\n");
     if ($file == "1") {
         $config = "# Generated by plugin monitoring for GLPI\n# on " . date("Y-m-d H:i:s") . "\n\n";
         foreach ($a_services as $data) {
             $config .= $this->writeFile("service", $data);
         }
         return array('services.cfg', $config);
     } else {
         return $a_services;
     }
 }
 static function updateVirtualMachines($computers_id, $ocsid, $ocsservers_id, $cfg_ocs, $import_vm, $dohistory)
 {
     global $DBocs;
     // No VM before OCS 1.3
     if ($cfg_ocs['ocs_version'] < self::OCS1_3_VERSION_LIMIT) {
         return false;
     }
     self::checkOCSconnection($ocsservers_id);
     //Get vms for this host
     $query = "SELECT *\n                FROM `virtualmachines`\n                WHERE `HARDWARE_ID` = '{$ocsid}'";
     $result = $DBocs->query($query);
     $virtualmachine = new ComputerVirtualMachine();
     if ($DBocs->numrows($result) > 0) {
         while ($line = $DBocs->fetch_array($result)) {
             $line = clean_cross_side_scripting_deep(addslashes_deep($line));
             $vm['name'] = $line['NAME'];
             $vm['vcpu'] = $line['VCPU'];
             $vm['ram'] = $line['MEMORY'];
             $vm['uuid'] = $line['UUID'];
             $vm['computers_id'] = $computers_id;
             $vm['virtualmachinestates_id'] = Dropdown::importExternal('VirtualMachineState', $line['STATUS']);
             $vm['virtualmachinetypes_id'] = Dropdown::importExternal('VirtualMachineType', $line['VMTYPE']);
             $vm['virtualmachinesystems_id'] = Dropdown::importExternal('VirtualMachineType', $line['SUBSYSTEM']);
             if (!in_array(stripslashes($line["ID"]), $import_vm)) {
                 $virtualmachine->reset();
                 if (!$dohistory) {
                     $vm['_no_history'] = true;
                 }
                 $id_vm = $virtualmachine->add($vm);
                 if ($id_vm) {
                     self::addToOcsArray($computers_id, array($id_vm => $line['ID']), "import_vm");
                 }
             } else {
                 $id = array_search(stripslashes($line["ID"]), $import_vm);
                 if ($virtualmachine->getFromDB($id)) {
                     $vm['id'] = $id;
                     $virtualmachine->update($vm);
                 }
                 unset($import_vm[$id]);
             }
         }
     }
 }