importExternal() static public méthode

This import a new dropdown if it doesn't exist - Play dictionnary if needed
static public importExternal ( $itemtype, $value, $entities_id, $external_params = [], $comment = '', $add = true ) : integer
$itemtype string name of the class
$value string Value of the new dropdown. (need to be addslashes)
$entities_id integer entity in case of specific dropdown (default -1)
$external_params array (need to be addslashes)
$comment (default '') (need to be addslashes)
$add if true, add it if not found. if false, just check if exists (true by default)
Résultat integer : dropdown id.
 function executeActions($output, $params)
 {
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "assign":
                     $output[$action->fields["field"]] = $action->fields["value"];
                     break;
                 case "regex_result":
                     //Regex result : assign value from the regex
                     $res = "";
                     if (isset($this->regex_results[0])) {
                         $res .= RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                     } else {
                         $res .= $action->fields["value"];
                     }
                     if ($res != '' && ($action->fields["field"] != 'user' && $action->fields["field"] != 'otherserial' && $action->fields["field"] != 'software' && $action->fields["field"] != 'softwareversion')) {
                         $res = Dropdown::importExternal(getItemTypeForTable(getTableNameForForeignKeyField($action->fields['field'])), $res);
                     }
                     $output[$action->fields["field"]] = $res;
                     break;
                 default:
                     //plugins actions
                     $executeaction = clone $this;
                     $ouput = $executeaction->executePluginsActions($action, $output, $params);
                     break;
             }
         }
     }
     return $output;
 }
 /**
  * Replay collection rules on an existing DB for model dropdowns
  *
  * @param $offset    offset used to begin (default 0)
  * @param $maxtime   maximum time of process (reload at the end) (default 0)
  *
  * @return -1 on completion else current offset
  **/
 function replayRulesOnExistingDBForModel($offset = 0, $maxtime = 0)
 {
     global $DB;
     if (isCommandLine()) {
         printf(__('Replay rules on existing database started on %s') . "\n", date("r"));
     }
     // Model check : need to check using manufacturer extra data
     if (strpos($this->item_table, 'models') === false) {
         _e('Error replaying rules');
         return false;
     }
     $model_table = getPlural(str_replace('models', '', $this->item_table));
     $model_field = getForeignKeyFieldForTable($this->item_table);
     // Need to give manufacturer from item table
     $Sql = "SELECT DISTINCT `glpi_manufacturers`.`id` AS idmanu,\n                     `glpi_manufacturers`.`name` AS manufacturer,\n                     `" . $this->item_table . "`.`id`,\n                     `" . $this->item_table . "`.`name` AS name,\n                     `" . $this->item_table . "`.`comment`\n              FROM `" . $this->item_table . "`,\n                   `{$model_table}`\n              LEFT JOIN `glpi_manufacturers`\n                  ON (`{$model_table}`.`manufacturers_id` = `glpi_manufacturers`.`id`)\n              WHERE `{$model_table}`.`{$model_field}` = `" . $this->item_table . "`.`id`";
     if ($offset) {
         $Sql .= " LIMIT " . intval($offset) . ",999999999";
     }
     $result = $DB->query($Sql);
     $nb = $DB->numrows($result) + $offset;
     $i = $offset;
     if ($result && $nb > $offset) {
         // Step to refresh progressbar
         $step = $nb > 20 ? floor($nb / 20) : 1;
         $tocheck = array();
         while ($data = $DB->fetch_assoc($result)) {
             if (!($i % $step)) {
                 if (isCommandLine()) {
                     printf(__('Replay rules on existing database: %1$s/%2$s') . "\r", $i, $nb);
                 } else {
                     Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
                 }
             }
             // Model case
             if (isset($data["manufacturer"])) {
                 $data["manufacturer"] = Manufacturer::processName(addslashes($data["manufacturer"]));
             }
             //Replay Type dictionnary
             $ID = Dropdown::importExternal(getItemTypeForTable($this->item_table), addslashes($data["name"]), -1, $data, addslashes($data["comment"]));
             if ($data['id'] != $ID) {
                 $tocheck[$data["id"]][] = $ID;
                 $sql = "UPDATE `{$model_table}`\n                                          SET `{$model_field}` = '{$ID}'\n                                          WHERE `{$model_field}` = '" . $data['id'] . "'";
                 if (empty($data['idmanu'])) {
                     $sql .= " AND (`manufacturers_id` IS NULL\n                                 OR `manufacturers_id` = '0')";
                 } else {
                     $sql .= " AND `manufacturers_id` = '" . $data['idmanu'] . "'";
                 }
                 $DB->query($sql);
             }
             $i++;
             if ($maxtime) {
                 $crt = explode(" ", microtime());
                 if ($crt[0] + $crt[1] > $maxtime) {
                     break;
                 }
             }
         }
         foreach ($tocheck as $ID => $tab) {
             $sql = "SELECT COUNT(*)\n                                 FROM `{$model_table}`\n                                 WHERE `{$model_field}` = '{$ID}'";
             $result = $DB->query($sql);
             $deletecartmodel = false;
             // No item left : delete old item
             if ($result && $DB->result($result, 0, 0) == 0) {
                 $Sql = "DELETE\n                                    FROM `" . $this->item_table . "`\n                                    WHERE `id` = '{$ID}'";
                 $resdel = $DB->query($Sql);
                 $deletecartmodel = true;
             }
             // Manage cartridge assoc Update items
             if ($this->getRuleClassName() == 'RuleDictionnaryPrinterModel') {
                 $sql = "SELECT *\n                       FROM `glpi_cartridgeitems_printermodels`\n                       WHERE `printermodels_id` = '{$ID}'";
                 if ($result = $DB->query($sql)) {
                     if ($DB->numrows($result)) {
                         // Get compatible cartridge type
                         $carttype = array();
                         while ($data = $DB->fetch_assoc($result)) {
                             $carttype[] = $data['cartridgeitems_id'];
                         }
                         // Delete cartrodges_assoc
                         if ($deletecartmodel) {
                             $sql = "DELETE\n                                FROM `glpi_cartridgeitems_printermodels`\n                                WHERE `printermodels_id` = 'id'";
                             $DB->query($sql);
                         }
                         // Add new assoc
                         $ct = new CartridgeItem();
                         foreach ($carttype as $cartID) {
                             foreach ($tab as $model) {
                                 $ct->addCompatibleType($cartID, $model);
                             }
                         }
                     }
                 }
             }
         }
         // each tocheck
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database ended on %s') . "\n", date("r"));
     } else {
         Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
     }
     return $i == $nb ? -1 : $i;
 }
 /**
  *
  * Import peripherals from OCS
  * @since 1.0
  * @param $cfg_ocs OCSNG mode configuration
  * @param $computers_id computer's id in GLPI
  * @param $ocsid computer's id in OCS
  * @param $ocsservers_id OCS server id
  * @param $entity the entity in which the peripheral will be created
  * @param $dohistory record in history link between peripheral and computer
  */
 static function importPeripheral($cfg_ocs, $computers_id, $ocsservers_id, $ocsid, $entity, $dohistory)
 {
     global $PluginOcsinventoryngDBocs, $DB;
     self::checkOCSconnection($ocsservers_id);
     if ($cfg_ocs["import_periph"]) {
         $already_processed = array();
         $p = new Peripheral();
         $conn = new Computer_Item();
         $query = "SELECT DISTINCT `CAPTION`, `MANUFACTURER`, `INTERFACE`, `TYPE`\n                   FROM `inputs`\n                   WHERE `HARDWARE_ID` = '{$ocsid}'\n                   AND `CAPTION` <> ''";
         $result = $PluginOcsinventoryngDBocs->query($query);
         if ($PluginOcsinventoryngDBocs->numrows($result) > 0) {
             while ($line = $PluginOcsinventoryngDBocs->fetch_array($result)) {
                 $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line));
                 $periph = array();
                 $periph["name"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["CAPTION"]);
                 //Look for a monitor with the same name (and serial if possible) already connected
                 //to this computer
                 $query = "SELECT `p`.`id`, `gci`.`is_deleted`\n                         FROM `glpi_printers` as `p`, `glpi_computers_items` as `gci`\n                         WHERE `p`.`id` = `gci`.`items_id`\n                            AND `gci`.`is_dynamic`='1'\n                            AND `computers_id`='{$computers_id}'\n                            AND `itemtype`='Peripheral'\n                            AND `p`.`name`='" . $periph["name"] . "'";
                 $results = $DB->query($query);
                 $id = false;
                 $lock = false;
                 if ($DB->numrows($results) > 0) {
                     $id = $DB->result($results, 0, 'id');
                     $lock = $DB->result($results, 0, 'is_deleted');
                 }
                 if (!$id) {
                     // Clean peripheral object
                     $p->reset();
                     if ($line["MANUFACTURER"] != "NULL") {
                         $periph["brand"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["MANUFACTURER"]);
                     }
                     if ($line["INTERFACE"] != "NULL") {
                         $periph["comment"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["INTERFACE"]);
                     }
                     $periph["peripheraltypes_id"] = Dropdown::importExternal('PeripheralType', $line["TYPE"]);
                     $id_periph = 0;
                     if ($cfg_ocs["import_periph"] == 1) {
                         //Config says : manage peripherals as global
                         //check if peripherals already exists in GLPI
                         $periph["is_global"] = 1;
                         $query = "SELECT `id`\n                               FROM `glpi_peripherals`\n                               WHERE `name` = '" . $periph["name"] . "'\n                                  AND `is_global` = '1'\n                                  AND `entities_id` = '{$entity}'";
                         $result_search = $DB->query($query);
                         if ($DB->numrows($result_search) > 0) {
                             //Periph is already in GLPI
                             //Do not import anything just get periph ID for link
                             $id_periph = $DB->result($result_search, 0, "id");
                         } else {
                             $input = $periph;
                             if ($cfg_ocs["states_id_default"] > 0) {
                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                             }
                             $input["entities_id"] = $entity;
                             $id_periph = $p->add($input);
                         }
                     } else {
                         if ($cfg_ocs["import_periph"] == 2) {
                             //Config says : manage peripherals as single units
                             //Import all peripherals as non global.
                             $input = $periph;
                             $input["is_global"] = 0;
                             if ($cfg_ocs["states_id_default"] > 0) {
                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                             }
                             $input["entities_id"] = $entity;
                             $id_periph = $p->add($input);
                         }
                     }
                     if ($id_periph) {
                         $already_processed[] = $id_periph;
                         $conn = new Computer_Item();
                         if ($connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Peripheral', 'items_id' => $id_periph, '_no_history' => !$dohistory, 'is_dynamic' => 1))) {
                             //Update column "is_deleted" set value to 0 and set status to default
                             $input = array();
                             $input["id"] = $id_periph;
                             $input["is_deleted"] = 0;
                             $input["entities_id"] = $entity;
                             if ($cfg_ocs["states_id_default"] > 0) {
                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                             }
                             $p->update($input);
                         }
                     }
                 } else {
                     $already_processed[] = $id;
                 }
             }
         }
         //Look for all monitors, not locked, not linked to the computer anymore
         $query = "SELECT `id`\n                   FROM `glpi_computers_items`\n                   WHERE `itemtype`='Peripheral'\n                      AND `computers_id`='{$computers_id}'\n                      AND `is_dynamic`='1'\n                      AND `is_deleted`='0'";
         if (!empty($already_processed)) {
             $query .= "AND `items_id` NOT IN (" . implode(',', $already_processed) . ")";
         }
         foreach ($DB->request($query) as $data) {
             //Delete all connexions
             $conn->delete(array('id' => $data['id'], '_ocsservers_id' => $ocsservers_id), true);
         }
     }
 }
 /**
  * Update an existing preloaded switch with the instance values
  *
  *@return nothing
  **/
 function updateDB()
 {
     if (array_key_exists('model', $this->ptcdUpdates)) {
         $manufacturer = Dropdown::getDropdownName("glpi_dropdown_manufacturer", $this->getValue('FK_glpi_enterprise'));
         $this->ptcdUpdates['model'] = Dropdown::importExternal("NetworkEquipmentModel", $this->ptcdUpdates['model'], 0, array('manufacturer' => $manufacturer));
     }
     if (array_key_exists('firmware', $this->ptcdUpdates)) {
         $this->ptcdUpdates['firmware'] = Dropdown::importExternal("NetworkEquipmentFirmware", $this->ptcdUpdates['firmware']);
     }
     if (array_key_exists('location', $this->ptcdUpdates)) {
         $this->ptcdUpdates['location'] = Dropdown::importExternal("Location", $this->ptcdUpdates['location']);
     }
     parent::updateDB();
     // update last_fusioninventory_update even if no other update
     $this->setValue('last_fusioninventory_update', date("Y-m-d H:i:s"));
     $this->oFusionInventory_networking->updateDB();
     // ports
     $this->savePorts();
 }
 /**
  * @see Rule::findWithGlobalCriteria()
  **/
 function findWithGlobalCriteria($input)
 {
     global $DB, $PLUGIN_HOOKS;
     $complex_criterias = array();
     $sql_where = '';
     $sql_from = '';
     $continue = true;
     $global_criteria = array('manufacturer', 'model', 'name', 'serial');
     //Add plugin global criteria
     if (isset($PLUGIN_HOOKS['use_rules'])) {
         foreach ($PLUGIN_HOOKS['use_rules'] as $plugin => $val) {
             if (is_array($val) && in_array($this->getType(), $val)) {
                 $global_criteria = Plugin::doOneHook($plugin, "ruleImportComputer_addGlobalCriteria", $global_criteria);
             }
         }
     }
     foreach ($global_criteria as $criterion) {
         $criteria = $this->getCriteriaByID($criterion);
         if (!empty($criteria)) {
             foreach ($criteria as $crit) {
                 // is a real complex criteria
                 if ($crit->fields["condition"] == Rule::PATTERN_FIND) {
                     if (!isset($input[$criterion]) || $input[$criterion] == '') {
                         $continue = false;
                     } else {
                         $complex_criterias[] = $crit;
                     }
                 }
             }
         }
     }
     foreach ($this->getCriteriaByID('states_id') as $crit) {
         $complex_criterias[] = $crit;
     }
     //If a value is missing, then there's a problem !
     if (!$continue) {
         return false;
     }
     //No complex criteria
     if (empty($complex_criterias)) {
         return true;
     }
     //Build the request to check if the machine exists in GLPI
     if (is_array($input['entities_id'])) {
         $where_entity = implode($input['entities_id'], ',');
     } else {
         $where_entity = $input['entities_id'];
     }
     $sql_where = '1';
     $sql_from = '';
     $needport = false;
     $needip = false;
     foreach ($complex_criterias as $criteria) {
         switch ($criteria->fields['criteria']) {
             case 'name':
                 if ($criteria->fields['condition'] == Rule::PATTERN_IS_EMPTY) {
                     $sql_where .= " AND (`glpi_computers`.`name`=''\n                                       OR `glpi_computers`.`name` IS NULL) ";
                 } else {
                     $sql_where .= " AND (`glpi_computers`.`name`='" . $input['name'] . "') ";
                 }
                 break;
             case 'serial':
                 $sql_where .= " AND `glpi_computers`.`serial`='" . $input["serial"] . "'";
                 break;
             case 'model':
                 // search for model, don't create it if not found
                 $options = array('manufacturer' => addslashes($input['manufacturer']));
                 $mid = Dropdown::importExternal('ComputerModel', addslashes($input['model']), -1, $options, '', false);
                 $sql_where .= " AND `glpi_computers`.`computermodels_id` = '{$mid}'";
                 break;
             case 'manufacturer':
                 // search for manufacturer, don't create it if not found
                 $mid = Dropdown::importExternal('Manufacturer', addslashes($input['manufacturer']), -1, array(), '', false);
                 $sql_where .= " AND `glpi_computers`.`manufacturers_id` = '{$mid}'";
                 break;
             case 'states_id':
                 if ($criteria->fields['condition'] == Rule::PATTERN_IS) {
                     $condition = " IN ";
                 } else {
                     $condition = " NOT IN ";
                 }
                 $sql_where .= " AND `glpi_computers`.`states_id`\n                                 {$condition} ('" . $criteria->fields['pattern'] . "')";
                 break;
         }
     }
     if (isset($PLUGIN_HOOKS['use_rules'])) {
         foreach ($PLUGIN_HOOKS['use_rules'] as $plugin => $val) {
             if (is_array($val) && in_array($this->getType(), $val)) {
                 $params = array('where_entity' => $where_entity, 'input' => $input, 'criteria' => $complex_criterias, 'sql_where' => $sql_where, 'sql_from' => $sql_from);
                 $sql_results = Plugin::doOneHook($plugin, "ruleImportComputer_getSqlRestriction", $params);
                 $sql_where = $sql_results['sql_where'];
                 $sql_from = $sql_results['sql_from'];
             }
         }
     }
     $sql_glpi = "SELECT `glpi_computers`.`id`\n                   FROM {$sql_from}\n                   WHERE {$sql_where}\n                   ORDER BY `glpi_computers`.`is_deleted` ASC";
     $result_glpi = $DB->query($sql_glpi);
     if ($DB->numrows($result_glpi) > 0) {
         while ($data = $DB->fetch_assoc($result_glpi)) {
             $this->criterias_results['found_computers'][] = $data['id'];
         }
         return true;
     }
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             if ($action->fields['field'] == '_fusion') {
                 if ($action->fields["value"] == self::RULE_ACTION_LINK_OR_NO_IMPORT) {
                     return true;
                 }
             }
         }
     }
     return false;
 }
 /**
  * Function that try to load from LDAP the user information...
  *
  * @param $ldap_connection ldap connection descriptor
  * @param $ldap_method LDAP method
  * @param $userdn Basedn of the user
  * @param $login User Login
  *
  * @return String : basedn of the user / false if not founded
  **/
 function getFromLDAP($ldap_connection, $ldap_method, $userdn, $login)
 {
     global $DB, $CFG_GLPI;
     // we prevent some delay...
     if (empty($ldap_method["host"])) {
         return false;
     }
     if ($ldap_connection) {
         //Set all the search fields
         $this->fields['password'] = "";
         $fields = AuthLDAP::getSyncFields($ldap_method);
         $fields = array_filter($fields);
         $f = array_values($fields);
         $sr = @ldap_read($ldap_connection, $userdn, "objectClass=*", $f);
         $v = ldap_get_entries_clean($ldap_connection, $sr);
         if (!is_array($v) || count($v) == 0 || empty($v[0][$fields['name']][0])) {
             return false;
         }
         //Store user's dn
         $this->fields['user_dn'] = addslashes($userdn);
         //Store date_sync
         $this->fields['date_sync'] = $_SESSION['glpi_currenttime'];
         foreach ($fields as $k => $e) {
             if (empty($v[0][$e][0])) {
                 switch ($k) {
                     case "language":
                         // Not set value : managed but user class
                         break;
                     case "usertitles_id":
                     case "usercategories_id":
                         $this->fields[$k] = 0;
                         break;
                     default:
                         $this->fields[$k] = "";
                 }
             } else {
                 switch ($k) {
                     case "language":
                         $language = Config::getLanguage($v[0][$e][0]);
                         if ($language != '') {
                             $this->fields[$k] = $language;
                         }
                         break;
                     case "usertitles_id":
                         $this->fields[$k] = Dropdown::importExternal('UserTitle', addslashes($v[0][$e][0]));
                         break;
                     case "usercategories_id":
                         $this->fields[$k] = Dropdown::importExternal('UserCategory', addslashes($v[0][$e][0]));
                         break;
                     default:
                         if (!empty($v[0][$e][0])) {
                             $this->fields[$k] = addslashes($v[0][$e][0]);
                         } else {
                             $this->fields[$k] = "";
                         }
                 }
             }
         }
         // Empty array to ensure than syncLdapGroups will be done
         $this->fields["_groups"] = array();
         ///The groups are retrieved by looking into an ldap user object
         if ($ldap_method["group_search_type"] == 0 || $ldap_method["group_search_type"] == 2) {
             $this->getFromLDAPGroupVirtual($ldap_connection, $ldap_method, $userdn, $login);
         }
         ///The groups are retrived by looking into an ldap group object
         if ($ldap_method["group_search_type"] == 1 || $ldap_method["group_search_type"] == 2) {
             $this->getFromLDAPGroupDiscret($ldap_connection, $ldap_method, $userdn, $login);
         }
         ///Only process rules if working on the master database
         if (!$DB->isSlave()) {
             //Instanciate the affectation's rule
             $rule = new RuleRightCollection();
             //Process affectation rules :
             //we don't care about the function's return because all
             //the datas are stored in session temporary
             if (isset($this->fields["_groups"])) {
                 $groups = $this->fields["_groups"];
             } else {
                 $groups = array();
             }
             $this->fields = $rule->processAllRules($groups, $this->fields, array('type' => 'LDAP', 'ldap_server' => $ldap_method["id"], 'connection' => $ldap_connection, 'userdn' => $userdn));
             $this->fields['_ruleright_process'] = true;
             //If rule  action is ignore import
             if (isset($this->fields["_stop_import"])) {
                 return false;
             }
             //or no rights found & do not import users with no rights
             if (!$CFG_GLPI["use_noright_users_add"]) {
                 $ok = false;
                 if (isset($this->fields["_ldap_rules"]) && count($this->fields["_ldap_rules"])) {
                     if (isset($this->fields["_ldap_rules"]["rules_entities_rights"]) && count($this->fields["_ldap_rules"]["rules_entities_rights"])) {
                         $ok = true;
                     }
                     if (!$ok) {
                         $entity_count = 0;
                         $right_count = 0;
                         if (Profile::getDefault()) {
                             $right_count++;
                         }
                         if (isset($this->fields["_ldap_rules"]["rules_entities"])) {
                             $entity_count += count($this->fields["_ldap_rules"]["rules_entities"]);
                         }
                         if (isset($this->input["_ldap_rules"]["rules_rights"])) {
                             $right_count += count($this->fields["_ldap_rules"]["rules_rights"]);
                         }
                         if ($entity_count && $right_count) {
                             $ok = true;
                         }
                     }
                 }
                 if (!$ok) {
                     $this->fields["_stop_import"] = true;
                     return false;
                 }
             }
             //Hook to retrieve more informations for ldap
             $this->fields = doHookFunction("retrieve_more_data_from_ldap", $this->fields);
         }
         return true;
     }
     return false;
 }
 /**
  * Import discovered device (add / update data in GLPI DB)
  *
  * @param object $item
  */
 function importDevice($item)
 {
     PluginFusioninventoryLogger::logIfExtradebugAndDebugMode('fusioninventorycommunication', 'Function PluginFusinvsnmpCommunicationNetDiscovery->importDevice().');
     $arrayinventory = $_SESSION['SOURCE_XMLDEVICE'];
     $input = array();
     $input['id'] = $item->getID();
     $a_lockable = PluginFusioninventoryLock::getLockFields(getTableForItemType($item->getType()), $item->getID());
     if (!in_array('name', $a_lockable)) {
         if (isset($arrayinventory['SNMPHOSTNAME']) && !empty($arrayinventory['SNMPHOSTNAME'])) {
             $input['name'] = $arrayinventory['SNMPHOSTNAME'];
         } else {
             if (isset($arrayinventory['NETBIOSNAME']) && !empty($arrayinventory['NETBIOSNAME'])) {
                 $input['name'] = $arrayinventory['NETBIOSNAME'];
             } else {
                 if (isset($arrayinventory['DNSHOSTNAME']) && !empty($arrayinventory['DNSHOSTNAME'])) {
                     $input['name'] = $arrayinventory['DNSHOSTNAME'];
                 }
             }
         }
     }
     if (!in_array('serial', $a_lockable)) {
         if (isset($arrayinventory['SERIAL'])) {
             if (trim($arrayinventory['SERIAL']) != '') {
                 $input['serial'] = trim($arrayinventory['SERIAL']);
             }
         }
     }
     if (isset($input['name']) && $input['name'] == '') {
         unset($input['name']);
     }
     if (isset($input['serial']) && $input['serial'] == '') {
         unset($input['serial']);
     }
     if (isset($arrayinventory['ENTITY']) and !empty($arrayinventory['ENTITY'])) {
         $input['entities_id'] = $arrayinventory['ENTITY'];
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $arrayinventory['ENTITY'] . "'";
         }
     }
     if (!isset($_SESSION['glpiactiveentities_string'])) {
         $_SESSION['glpiactiveentities_string'] = "'" . $item->fields['entities_id'] . "'";
     }
     switch ($item->getType()) {
         case 'Computer':
             // don't update this computer, if it is already handled by
             // its own agent
             if (Dropdown::getDropdownName("glpi_autoupdatesystems", $item->fields['autoupdatesystems_id']) == 'FusionInventory') {
                 return;
             }
             if (isset($arrayinventory['WORKGROUP'])) {
                 $domain = new Domain();
                 if (!in_array('domains_id', $a_lockable)) {
                     $input['domains_id'] = $domain->import(array('name' => $arrayinventory['WORKGROUP']));
                 }
             }
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'Computer', $item->getID(), 'NetworkPortEthernet', 1);
             break;
         case 'PluginFusioninventoryUnmanaged':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'PluginFusioninventoryUnmanaged');
             }
             if (!in_array('contact', $a_lockable) && isset($arrayinventory['USERSESSION'])) {
                 $input['contact'] = $arrayinventory['USERSESSION'];
             }
             if (!in_array('domain', $a_lockable)) {
                 if (isset($arrayinventory['WORKGROUP']) && !empty($arrayinventory['WORKGROUP'])) {
                     $input['domain'] = Dropdown::importExternal("Domain", $arrayinventory['WORKGROUP'], $arrayinventory['ENTITY']);
                 }
             }
             if (!empty($arrayinventory['TYPE'])) {
                 switch ($arrayinventory['TYPE']) {
                     case '1':
                     case 'COMPUTER':
                         $input['item_type'] = 'Computer';
                         break;
                     case '2':
                     case 'NETWORKING':
                         $input['item_type'] = 'NetworkEquipment';
                         break;
                     case '3':
                     case 'PRINTER':
                         $input['item_type'] = 'Printer';
                         break;
                 }
             }
             $input['plugin_fusioninventory_agents_id'] = $_SESSION['glpi_plugin_fusioninventory_agentid'];
             $this->_updateSNMPInfo($arrayinventory, $input, $item);
             $this->_updateNetworkInfo($arrayinventory, 'PluginFusioninventoryUnmanaged', $item->getID(), 'NetworkPortEthernet', 1);
             break;
         case 'NetworkEquipment':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'NetworkEquipment');
             }
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'NetworkEquipment', $item->getID(), 'NetworkPortAggregate', 0);
             $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
             $input = $this->_initSpecificInfo('networkequipments_id', $item->getID(), $pfNetworkEquipment);
             $this->_updateSNMPInfo($arrayinventory, $input, $pfNetworkEquipment);
             break;
         case 'Printer':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'Printer');
             }
             $input['have_ethernet'] = '1';
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'Printer', $item->getID(), 'NetworkPortEthernet', 1);
             $pfPrinter = new PluginFusioninventoryPrinter();
             $input = $this->_initSpecificInfo('printers_id', $item->getID(), $pfPrinter);
             $this->_updateSNMPInfo($arrayinventory, $input, $pfPrinter);
             break;
     }
 }
 /**
  * Replay dictionnary on one software
  *
  * @param &$new_softs      array containing new softwares already computed
  * @param $res_rule        array of rule results
  * @param $ID                    ID of the software
  * @param $entity                working entity ID
  * @param $name                  softwrae name
  * @param $manufacturer          manufacturer name
  * @param &$soft_ids       array containing replay software need to be dustbined
  **/
 function replayDictionnaryOnOneSoftware(array &$new_softs, array $res_rule, $ID, $entity, $name, $manufacturer, array &$soft_ids)
 {
     global $DB;
     $input["name"] = $name;
     $input["manufacturer"] = $manufacturer;
     $input["entities_id"] = $entity;
     if (empty($res_rule)) {
         $res_rule = $this->processAllRules($input, array(), array());
     }
     $soft = new Software();
     if (isset($res_rules['_ignore_import']) && $res_rules['_ignore_import'] == 1) {
         $soft->putInTrash($ID, __('Software deleted by GLPI dictionary rules'));
         return;
     }
     //Software's name has changed or entity
     if (isset($res_rule["name"]) && $res_rule["name"] != $name || !isset($res_rule["name"]) && isset($res_rule['new_entities_id']) && in_array($res_rule['new_entities_id'], getAncestorsOf('glpi_entities', $entity))) {
         if (isset($res_rule["name"])) {
             $new_name = $res_rule["name"];
         } else {
             $new_name = addslashes($name);
         }
         if (isset($res_rule["manufacturer"]) && $res_rule["manufacturer"]) {
             $manufacturer = $res_rule["manufacturer"];
         } else {
             $manufacturer = addslashes($manufacturer);
         }
         //New software not already present in this entity
         if (!isset($new_softs[$entity][$new_name])) {
             // create new software or restore it from dustbin
             $new_software_id = $soft->addOrRestoreFromTrash($new_name, $manufacturer, $entity, '', true);
             $new_softs[$entity][$new_name] = $new_software_id;
         } else {
             $new_software_id = $new_softs[$entity][$new_name];
         }
         // Move licenses to new software
         $this->moveLicenses($ID, $new_software_id);
     } else {
         $new_software_id = $ID;
         $res_rule["id"] = $ID;
         if (isset($res_rule["manufacturer"]) && $res_rule["manufacturer"]) {
             $res_rule["manufacturers_id"] = Dropdown::importExternal('Manufacturer', $res_rule["manufacturer"]);
             unset($res_rule["manufacturer"]);
         }
         $soft->update($res_rule);
     }
     // Add to software to deleted list
     if ($new_software_id != $ID) {
         $soft_ids[] = $ID;
     }
     //Get all the different versions for a software
     $result = $DB->query("SELECT *\n                            FROM `glpi_softwareversions`\n                            WHERE `softwares_id` = '{$ID}'");
     while ($version = $DB->fetch_assoc($result)) {
         $input["version"] = addslashes($version["name"]);
         $old_version_name = $input["version"];
         if (isset($res_rule["version"]) && $res_rule["version"] != '') {
             $new_version_name = $res_rule["version"];
         } else {
             $new_version_name = $version["name"];
         }
         if ($ID != $new_software_id || $new_version_name != $old_version_name) {
             $this->moveVersions($ID, $new_software_id, $version["id"], $old_version_name, $new_version_name, $entity);
         }
     }
 }
 function executeActions($output, $params)
 {
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-locationrules", "execute action\n");
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "assign":
                     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-locationrules", "value " . $action->fields["value"] . "\n");
                     $output[$action->fields["field"]] = $action->fields["value"];
                     break;
                 case "regex_result":
                     $res = '';
                     if (isset($this->regex_results[0])) {
                         $res .= RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                     } else {
                         $res .= $action->fields["value"];
                     }
                     if ($res != '') {
                         $entities_id = 0;
                         if (isset($_SESSION["plugin_fusioninventory_entity"]) && $_SESSION["plugin_fusioninventory_entity"] > 0) {
                             $entities_id = $_SESSION["plugin_fusioninventory_entity"];
                         }
                         $res = Dropdown::importExternal(getItemTypeForTable(getTableNameForForeignKeyField($action->fields['field'])), $res, $entities_id);
                     }
                     $output[$action->fields["field"]] = $res;
                     break;
             }
         }
     }
     return $output;
 }
 /**
  * @param $ID
  * @param $plugin_ocsinventoryng_ocsservers_id
  * @return array
  */
 static function updateSnmp($ID, $plugin_ocsinventoryng_ocsservers_id)
 {
     global $DB;
     $query = "SELECT * FROM `glpi_plugin_ocsinventoryng_snmpocslinks` \n               WHERE `id` = " . $ID . " \n               AND `plugin_ocsinventoryng_ocsservers_id` = " . $plugin_ocsinventoryng_ocsservers_id;
     $rep = $DB->query($query);
     while ($data = $DB->fetch_array($rep)) {
         $ocsid = $data['ocs_id'];
         $itemtype = $data['itemtype'];
         $items_id = $data['items_id'];
         $linked = $data['linked'];
     }
     $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($plugin_ocsinventoryng_ocsservers_id);
     $ocsSnmp = $ocsClient->getSnmpDevice($ocsid);
     $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($plugin_ocsinventoryng_ocsservers_id);
     $loc_id = 0;
     $dom_id = 0;
     if ($cfg_ocs['importsnmp_location'] && $linked == 0 || $cfg_ocs['linksnmp_location'] && $linked) {
         $loc_id = Dropdown::importExternal('Location', PluginOcsinventoryngOcsServer::encodeOcsDataInUtf8($cfg_ocs['ocs_db_utf8'], $ocsSnmp['META']['LOCATION']));
     }
     if ($cfg_ocs['importsnmp_domain'] && $linked == 0 || $cfg_ocs['linksnmp_domain'] && $linked) {
         $dom_id = Dropdown::importExternal('Domain', PluginOcsinventoryngOcsServer::encodeOcsDataInUtf8($cfg_ocs['ocs_db_utf8'], $ocsSnmp['META']['DOMAIN']));
     }
     if ($itemtype == "Printer") {
         self::addOrUpdatePrinter($plugin_ocsinventoryng_ocsservers_id, $itemtype, $items_id, $ocsSnmp, $loc_id, $dom_id, "update", $linked);
         $now = date("Y-m-d H:i:s");
         $sql = "UPDATE `glpi_plugin_ocsinventoryng_snmpocslinks` SET `last_update` = '" . $now . "' WHERE `id` = " . $ID . ";";
         $DB->query($sql);
         return array('status' => PluginOcsinventoryngOcsServer::SNMP_SYNCHRONIZED);
     } else {
         if ($itemtype == "NetworkEquipment") {
             self::addOrUpdateNetworkEquipment($plugin_ocsinventoryng_ocsservers_id, $itemtype, $items_id, $ocsSnmp, $loc_id, $dom_id, "update", $linked);
             $now = date("Y-m-d H:i:s");
             $sql = "UPDATE `glpi_plugin_ocsinventoryng_snmpocslinks` SET `last_update` = '" . $now . "' WHERE `id` = " . $ID . ";";
             $DB->query($sql);
             return array('status' => PluginOcsinventoryngOcsServer::SNMP_SYNCHRONIZED);
         } else {
             if ($itemtype == "Computer") {
                 self::addOrUpdateComputer($plugin_ocsinventoryng_ocsservers_id, $itemtype, $items_id, $ocsSnmp, $loc_id, $dom_id, "update", $linked);
                 $now = date("Y-m-d H:i:s");
                 $sql = "UPDATE `glpi_plugin_ocsinventoryng_snmpocslinks` SET `last_update` = '" . $now . "' WHERE `id` = " . $ID . ";";
                 $DB->query($sql);
                 return array('status' => PluginOcsinventoryngOcsServer::SNMP_SYNCHRONIZED);
             } else {
                 if ($itemtype == "Peripheral" || $itemtype == "Phone") {
                     self::addOrUpdateOther($plugin_ocsinventoryng_ocsservers_id, $itemtype, $items_id, $ocsSnmp, $loc_id, $dom_id, "update", $linked);
                     $now = date("Y-m-d H:i:s");
                     $sql = "UPDATE `glpi_plugin_ocsinventoryng_snmpocslinks` SET `last_update` = '" . $now . "' WHERE `id` = " . $ID . ";";
                     $DB->query($sql);
                     return array('status' => PluginOcsinventoryngOcsServer::SNMP_SYNCHRONIZED);
                 }
             }
         }
     }
     return array('status' => PluginOcsinventoryngOcsServer::SNMP_NOTUPDATED);
 }
 /**
  * Update an existing preloaded switch with the instance values
  *
  *@return nothing
  **/
 function updateDB()
 {
     global $DB;
     if (array_key_exists('model', $this->ptcdUpdates)) {
         $manufacturer = Dropdown::getDropdownName("glpi_dropdown_manufacturer", $this->getValue('FK_glpi_enterprise'));
         $this->ptcdUpdates['model'] = Dropdown::importExternal("PrinterModel", $this->ptcdUpdates['model'], 0, array('manufacturer' => $manufacturer));
     }
     parent::updateDB();
     // update last_fusioninventory_update even if no other update
     $this->setValue('last_fusioninventory_update', date("Y-m-d H:i:s"));
     $this->oFusionInventory_printer->updateDB();
     // ports
     $this->savePorts();
     // cartridges
     $this->saveCartridges();
     // history
     if (is_null($this->oFusionInventory_printer_history->getValue('ID'))) {
         // update only if counters not already set for today
         $this->oFusionInventory_printer_history->updateDB();
     }
 }
 function import_netdiscovery($p_xml, $agentKey)
 {
     global $DB, $LANG;
     $test = '';
     $p_criteria = array();
     $walks = new PluginFusioninventoryWalk();
     $ptap = new PluginFusioninventoryAgentsProcesses();
     $pta = new PluginFusioninventoryAgents();
     $config_discovery = new PluginFusioninventoryConfig();
     $np = new Netport();
     $ptud = new PluginFusioninventoryUnknownDevice();
     if (isset($p_xml->AGENT->START)) {
         $ptap->updateProcess($p_xml->PROCESSNUMBER, array('start_time_discovery' => date("Y-m-d H:i:s")));
     } else {
         if (isset($p_xml->AGENT->END)) {
             $ptap->updateProcess($p_xml->PROCESSNUMBER, array('end_time_discovery' => date("Y-m-d H:i:s")));
         } else {
             if (isset($p_xml->AGENT->EXIT)) {
                 $ptap->endProcess($p_xml->PROCESSNUMBER, date("Y-m-d H:i:s"));
             } else {
                 if (isset($p_xml->AGENT->NBIP)) {
                     $ptap->updateProcess($p_xml->PROCESSNUMBER, array('discovery_nb_ip' => $p_xml->AGENT->NBIP));
                 }
             }
         }
     }
     if (isset($p_xml->AGENT->AGENTVERSION)) {
         $agent = $pta->InfosByKey($agentKey);
         $agent['fusioninventory_agent_version'] = $p_xml->AGENT->AGENTVERSION;
         $agent['last_agent_update'] = date("Y-m-d H:i:s");
         $pta->update($agent);
     }
     $walkdata = '';
     $count_discovery_devices = 0;
     foreach ($p_xml->DEVICE as $discovery) {
         $count_discovery_devices++;
     }
     $ptap->updateProcess($_SESSION['glpi_plugin_fusioninventory_processnumber'], array('discovery_nb_found' => $count_discovery_devices));
     foreach ($p_xml->DEVICE as $discovery) {
         if ($discovery->MODELSNMP != "") {
             $query = "SELECT *\n                      FROM `glpi_plugin_fusioninventory_model_infos`\n                      WHERE `discovery_key`='" . $discovery->MODELSNMP . "'\n                      LIMIT 0,1;";
             $result = $DB->query($query);
             $data = $DB->fetch_assoc($result);
             $FK_model = $data['ID'];
         } else {
             $FK_model = 0;
         }
         $discovery->MAC = strtolower($discovery->MAC);
         if (empty($FK_model)) {
             $FK_model = 0;
         }
         unset($p_criteria);
         $p_criteria['ip'] = $discovery->IP;
         if (!empty($discovery->NETBIOSNAME)) {
             $p_criteria['name'] = $discovery->NETBIOSNAME;
         } else {
             if (!empty($discovery->SNMPHOSTNAME)) {
                 $p_criteria['name'] = $discovery->SNMPHOSTNAME;
             }
         }
         $p_criteria['serial'] = $discovery->SERIAL;
         $p_criteria['macaddr'] = $discovery->MAC;
         $discovery_criteria = PluginFusioninventoryDiscovery::criteria($p_criteria);
         if (!$discovery_criteria) {
             $ptap->updateProcess($_SESSION['glpi_plugin_fusioninventory_processnumber'], array('discovery_nb_import' => '1'));
             // Add in unknown device
             $ptud->getEmpty();
             if (!empty($discovery->NETBIOSNAME)) {
                 $ptud->fields['name'] = $discovery->NETBIOSNAME;
             } else {
                 if (!empty($discovery->SNMPHOSTNAME)) {
                     $ptud->fields['name'] = $discovery->SNMPHOSTNAME;
                 }
             }
             $ptud->fields['dnsname'] = $discovery->DNSHOSTNAME;
             $ptud->fields['FK_entities'] = $discovery->ENTITY;
             $ptud->fields['serial'] = $discovery->SERIAL;
             $ptud->fields['contact'] = $discovery->USERSESSION;
             if (!empty($discovery->WORKGROUP)) {
                 $ptud->fields['domain'] = Dropdown::importExternal("Domain", $discovery->WORKGROUP, $discovery->ENTITY);
             }
             $ptud->fields['comments'] = $discovery->DESCRIPTION;
             $ptud->fields['type'] = $discovery->TYPE;
             $ptud->fields['FK_model_infos'] = $FK_model;
             $ptud->fields['FK_snmp_connection'] = $discovery->AUTHSNMP;
             if ($discovery->AUTHSNMP != "") {
                 $ptud->fields['snmp'] = 1;
             }
             $ptud->fields['location'] = 0;
             $ptud->fields['deleted'] = 0;
             if ($ptud->fields['domain'] == '') {
                 $ptud->fields['domain'] = 0;
             }
             if ($ptud->fields['type'] == '') {
                 $ptud->fields['type'] = 0;
             }
             if ($ptud->fields['snmp'] == '') {
                 $ptud->fields['snmp'] = 0;
             }
             if ($ptud->fields['FK_model_infos'] == '') {
                 $ptud->fields['FK_model_infos'] = 0;
             }
             if ($ptud->fields['FK_snmp_connection'] == '') {
                 $ptud->fields['FK_snmp_connection'] = 0;
             }
             if ($ptud->fields['accepted'] == '') {
                 $ptud->fields['accepted'] = 0;
             }
             $explodeprocess = explode("/", $_SESSION['glpi_plugin_fusioninventory_processnumber']);
             $ptud->fields['FK_agent'] = intval($explodeprocess[1]);
             $ptud->fields['hub'] = 0;
             $data = $ptud->fields;
             unset($data['ID']);
             $newID = $ptud->add($data);
             unset($data);
             // Add networking_port
             $port_add["on_device"] = $newID;
             $port_add["device_type"] = PLUGIN_FUSIONINVENTORY_MAC_UNKNOWN;
             $port_add["ifaddr"] = $discovery->IP;
             $port_add['ifmac'] = $discovery->MAC;
             $port_add['name'] = $discovery->NETPORTVENDOR;
             $port_ID = $np->add($port_add);
             unset($port_add);
         } else {
             # Update device
             //echo "discovery_criteria :".$discovery_criteria;
             $a_device = explode("||", $discovery_criteria);
             // $a_device[0] == id, $a_device[1] = type
             $ci = new commonitem();
             $ci->getFromDB($a_device[1], $a_device[0]);
             $a_lockable = PluginFusioninventoryLock::getLockFields($a_device[1], $a_device[0]);
             $data = array();
             $data['ID'] = $ci->getField('ID');
             if ($a_device[1] == PLUGIN_FUSIONINVENTORY_MAC_UNKNOWN) {
                 $data['FK_snmp_connection'] = 0;
                 if ($ci->getField('name') && !in_array('name', $a_lockable)) {
                     if (!empty($discovery->NETBIOSNAME)) {
                         $data['name'] = $discovery->NETBIOSNAME;
                     } else {
                         if (!empty($discovery->SNMPHOSTNAME)) {
                             $data['name'] = $discovery->SNMPHOSTNAME;
                         }
                     }
                 }
                 if ($ci->getField('dnsname') && !in_array('dnsname', $a_lockable)) {
                     $data['dnsname'] = $discovery->DNSHOSTNAME;
                 }
                 if ($ci->getField('FK_entities') && !in_array('FK_entities', $a_lockable)) {
                     $data['FK_entities'] = $discovery->ENTITY;
                 }
                 if ($ci->getField('serial') && !in_array('serial', $a_lockable)) {
                     $data['serial'] = $discovery->SERIAL;
                 }
                 if ($ci->getField('contact') && !in_array('contact', $a_lockable)) {
                     $data['contact'] = $discovery->USERSESSION;
                 }
                 if ($ci->getField('domain') && !in_array('domain', $a_lockable)) {
                     $data['domain'] = 0;
                     if (!empty($discovery->WORKGROUP)) {
                         $data['domain'] = Dropdown::importExternal("Domain", $discovery->WORKGROUP, $discovery->ENTITY);
                     }
                 }
                 if ($ci->getField('FK_snmp_connection') && !in_array('FK_snmp_connection', $a_lockable)) {
                     $data['FK_snmp_connection'] = $discovery->AUTHSNMP;
                 }
                 if ($ci->getField('snmp') && !in_array('snmp', $a_lockable)) {
                     $data['snmp'] = 0;
                     if ($discovery->AUTHSNMP != "") {
                         $data['snmp'] = 1;
                     }
                 }
                 $data['type'] = $discovery->TYPE;
                 $explodeprocess = explode("/", $_SESSION['glpi_plugin_fusioninventory_processnumber']);
                 $data['FK_agent'] = intval($explodeprocess[1]);
             }
             if ($ci->getField('FK_model_infos') && !in_array('FK_model_infos', $a_lockable)) {
                 $data['FK_model_infos'] = $FK_model;
             }
             if ($ci->getField('comments') && !in_array('comments', $a_lockable)) {
                 $data['comments'] = $discovery->DESCRIPTION;
             }
             if ($a_device[1] == NETWORKING_TYPE) {
                 if (!in_array('ifaddr', $a_lockable)) {
                     $data["ifaddr"] = $discovery->IP;
                 }
                 if (!in_array('ifmac', $a_lockable)) {
                     $data['ifmac'] = $discovery->MAC;
                 }
             } else {
                 // TODO: manage ports
                 $np = new Netport();
                 $query = "SELECT ID FROM glpi_networking_ports\n                  WHERE (on_device = '" . $a_device[0] . "' AND device_type = '" . $a_device[1] . "')\n                     AND `ifaddr` NOT IN ('', '127.0.0.1')\n                  ORDER BY name, logical_number";
                 if ($result = $DB->query($query)) {
                     if ($DB->numrows($result) == 1) {
                         $data2 = $DB->fetch_assoc($result);
                         $np->getFromDB($data2["ID"]);
                         $port = array();
                         $port['ID'] = $data2["ID"];
                         $port["ifaddr"] = $discovery->IP;
                         $port['ifmac'] = $discovery->MAC;
                         $port['name'] = $discovery->NETPORTVENDOR;
                         $np->update($port);
                     } else {
                         if ($DB->numrows($result) > 1) {
                             $ptae = new PluginFusioninventoryAgentsErrors();
                             $error_input['ID'] = $a_device[0];
                             $error_input['TYPE'] = $a_device[1];
                             $error_input['MESSAGE'] = 'Unable to determine network port of device to update with values : ' . $discovery->IP . '(ip),
                     ' . $discovery->MAC . '(mac), ' . $discovery->NETPORTVENDOR . '(name)';
                             $error_input['agent_type'] = 'NETDISCOVERY';
                             $ptae->addError($error_input);
                         }
                     }
                 }
             }
             $ci->obj->update($data);
             $ptap->updateProcess($_SESSION['glpi_plugin_fusioninventory_processnumber'], array('discovery_nb_exists' => '1'));
         }
     }
 }
 /**
  * Create a new software
  *
  * @param name the software's name
  * @param manufacturer the software's manufacturer
  * @param entity the entity in which the software must be added
  * @param comment
  *
  * @return the software's ID
  **/
 function addSoftware($name, $manufacturer, $entity, $comment = '')
 {
     global $DB, $CFG_GLPI;
     $manufacturer_id = 0;
     if ($manufacturer != '') {
         $manufacturer_id = Dropdown::importExternal('Manufacturer', $manufacturer);
     }
     $sql = "SELECT `id`\n              FROM `glpi_softwares`\n              WHERE `manufacturers_id` = '{$manufacturer_id}'\n                    AND `name` = '{$name}' " . getEntitiesRestrictRequest('AND', 'glpi_softwares', 'entities_id', $entity, true);
     $res_soft = $DB->query($sql);
     if ($soft = $DB->fetch_array($res_soft)) {
         $id = $soft["id"];
     } else {
         $input["name"] = $name;
         $input["manufacturers_id"] = $manufacturer_id;
         $input["entities_id"] = $entity;
         // No comment
         $input["is_helpdesk_visible"] = $CFG_GLPI["default_software_helpdesk_visible"];
         //Process software's category rules
         $softcatrule = new RuleSoftwareCategoryCollection();
         $result = $softcatrule->processAllRules(null, null, $input);
         if (!empty($result) && isset($result["softwarecategories_id"])) {
             $input["softwarecategories_id"] = $result["softwarecategories_id"];
         } else {
             $input["softwarecategories_id"] = 0;
         }
         $id = $this->add($input);
     }
     return $id;
 }
 function createModel($xml, $message)
 {
     global $DB;
     $pfMapping = new PluginFusioninventoryMapping();
     $pfModel = new PluginFusioninventorySnmpmodel();
     $type = (string) $xml->type;
     switch ($type) {
         case '1':
             $type = "Computer";
             break;
         case '2':
             $type = "NetworkEquipment";
             break;
         case '3':
             $type = "Printer";
             break;
     }
     $input = array();
     $input['name'] = (string) $xml->name;
     $input['itemtype'] = $type;
     $input['discovery_key'] = (string) $xml->key;
     //$input['comment']       = Toolbox::clean_cross_side_scripting_deep(
     //                            Toolbox::addslashes_deep((string)$xml->comments));
     $plugin_fusioninventory_snmpmodels_id = $pfModel->add($input);
     $a_devices = array();
     if (isset($xml->devices) && isset($xml->devices->sysdescr)) {
         foreach ($xml->devices->sysdescr as $child) {
             $a_devices[] = (string) $child;
         }
     }
     $pfSnmpmodeldevice = new PluginFusioninventorySnmpmodeldevice();
     $pfSnmpmodeldevice->updateDevicesForModel($plugin_fusioninventory_snmpmodels_id, $a_devices);
     foreach ($xml->oidlist->oidobject as $child) {
         $plugin_fusioninventory_snmpmodelmibobjects_id = 0;
         $plugin_fusioninventory_snmpmodelmiboids_id = 0;
         $oid_port_counter = 0;
         $oid_port_dyn = 0;
         $mapping_type = '';
         $mapping_name = '';
         $vlan = 0;
         $is_active = 1;
         $mappings_id = 0;
         if (isset($child->object)) {
             $plugin_fusioninventory_snmpmodelmibobjects_id = Dropdown::importExternal("PluginFusioninventorySnmpmodelMibObject", $child->object);
         }
         if (isset($child->oid)) {
             $plugin_fusioninventory_snmpmodelmiboids_id = Dropdown::importExternal("PluginFusioninventorySnmpmodelMibOid", $child->oid);
         }
         if (isset($child->portcounter)) {
             $oid_port_counter = $child->portcounter;
         }
         if (isset($child->dynamicport)) {
             $oid_port_dyn = $child->dynamicport;
         }
         if (isset($child->mapping_type)) {
             $mapping_type = '';
             switch ($child->mapping_type) {
                 case '1':
                     $mapping_type = "Computer";
                     break;
                 case '2':
                     $mapping_type = "NetworkEquipment";
                     break;
                 case '3':
                     $mapping_type = "Printer";
                     break;
             }
             if ($mapping_type == '') {
                 $mapping_type = $child->mapping_type;
             }
         }
         if (isset($child->mapping_name)) {
             $mapping_name = $child->mapping_name;
         }
         if (isset($child->vlan)) {
             $vlan = $child->vlan;
         }
         if (isset($child->activation)) {
             $is_active = $child->activation;
         }
         if (isset($mapping_type) and isset($mapping_name)) {
             $a_mappings = $pfMapping->get($mapping_type, $mapping_name);
             $mappings_id = $a_mappings['id'];
         }
         if (!isset($mappings_id) or empty($mappings_id)) {
             $mappings_id = '0';
         }
         $query = "INSERT INTO `glpi_plugin_fusioninventory_snmpmodelmibs`\n             (\n                `plugin_fusioninventory_snmpmodels_id`,\n                `plugin_fusioninventory_snmpmodelmiboids_id`,\n                `plugin_fusioninventory_snmpmodelmibobjects_id`,\n                `oid_port_counter`,\n                `oid_port_dyn`,\n                `plugin_fusioninventory_mappings_id`,\n                `vlan`,\n                `is_active`\n             )\n             VALUES(\n                '" . $plugin_fusioninventory_snmpmodels_id . "',\n                '" . $plugin_fusioninventory_snmpmodelmiboids_id . "',\n                '" . $plugin_fusioninventory_snmpmodelmibobjects_id . "',\n                '" . $oid_port_counter . "',\n                '" . $oid_port_dyn . "',\n                '" . $mappings_id . "',\n                '" . $vlan . "',\n                '" . $is_active . "'\n             );";
         $DB->query($query);
     }
 }
 /**
  *
  * Import peripherals from OCS
  * @since 1.0
  * @param $cfg_ocs OCSNG mode configuration
  * @param $computers_id computer's id in GLPI
  * @param $ocsid computer's id in OCS
  * @param $ocsservers_id OCS server id
  * @param $entity the entity in which the peripheral will be created
  * @param $dohistory record in history link between peripheral and computer
  */
 static function importPeripheral($cfg_ocs, $computers_id, $ocsservers_id, $ocsComputer, $entity, $dohistory)
 {
     global $DB;
     $already_processed = array();
     $p = new Peripheral();
     $conn = new Computer_Item();
     if (isset($ocsComputer["INPUTS"])) {
         if (count($ocsComputer["INPUTS"]) > 0) {
             foreach ($ocsComputer["INPUTS"] as $peripheral) {
                 if ($peripheral["CAPTION"] !== '') {
                     $peripherals[] = $peripheral;
                 }
             }
             if (count($peripherals) > 0) {
                 foreach ($peripherals as $peripheral) {
                     $peripheral = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($peripheral));
                     $periph = array();
                     $periph["name"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $peripheral["CAPTION"]);
                     //Look for a monitor with the same name (and serial if possible) already connected
                     //to this computer
                     $query = "SELECT `p`.`id`, `gci`.`is_deleted`\n                                       FROM `glpi_printers` as `p`, `glpi_computers_items` as `gci`\n                                       WHERE `p`.`id` = `gci`.`items_id`\n                                       AND `gci`.`is_dynamic`='1'\n                                       AND `computers_id`='{$computers_id}'\n                                       AND `itemtype`='Peripheral'\n                                       AND `p`.`name`='" . $periph["name"] . "'";
                     $results = $DB->query($query);
                     $id = false;
                     $lock = false;
                     if ($DB->numrows($results) > 0) {
                         $id = $DB->result($results, 0, 'id');
                         $lock = $DB->result($results, 0, 'is_deleted');
                     }
                     if (!$id) {
                         // Clean peripheral object
                         $p->reset();
                         if ($peripheral["MANUFACTURER"] != "NULL") {
                             $periph["brand"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $peripheral["MANUFACTURER"]);
                         }
                         if ($peripheral["INTERFACE"] != "NULL") {
                             $periph["comment"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $peripheral["INTERFACE"]);
                         }
                         $periph["peripheraltypes_id"] = Dropdown::importExternal('PeripheralType', $peripheral["TYPE"]);
                         $id_periph = 0;
                         if ($cfg_ocs["import_periph"] == 1) {
                             //Config says : manage peripherals as global
                             //check if peripherals already exists in GLPI
                             $periph["is_global"] = 1;
                             $query = "SELECT `id`\n                                           FROM `glpi_peripherals`\n                                           WHERE `name` = '" . $periph["name"] . "'\n                                           AND `is_global` = '1'\n                                           AND `entities_id` = '{$entity}'";
                             $result_search = $DB->query($query);
                             if ($DB->numrows($result_search) > 0) {
                                 //Periph is already in GLPI
                                 //Do not import anything just get periph ID for link
                                 $id_periph = $DB->result($result_search, 0, "id");
                             } else {
                                 $input = $periph;
                                 if ($cfg_ocs["states_id_default"] > 0) {
                                     $input["states_id"] = $cfg_ocs["states_id_default"];
                                 }
                                 $input["entities_id"] = $entity;
                                 $id_periph = $p->add($input);
                             }
                         } else {
                             if ($cfg_ocs["import_periph"] == 2) {
                                 //Config says : manage peripherals as single units
                                 //Import all peripherals as non global.
                                 $input = $periph;
                                 $input["is_global"] = 0;
                                 if ($cfg_ocs["states_id_default"] > 0) {
                                     $input["states_id"] = $cfg_ocs["states_id_default"];
                                 }
                                 $input["entities_id"] = $entity;
                                 $id_periph = $p->add($input);
                             }
                         }
                         if ($id_periph) {
                             $already_processed[] = $id_periph;
                             $conn = new Computer_Item();
                             if ($connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Peripheral', 'items_id' => $id_periph, '_no_history' => !$dohistory, 'is_dynamic' => 1))) {
                                 //Update column "is_deleted" set value to 0 and set status to default
                                 $input = array();
                                 $input["id"] = $id_periph;
                                 $input["is_deleted"] = 0;
                                 $input["entities_id"] = $entity;
                                 if ($cfg_ocs["states_id_default"] > 0) {
                                     $input["states_id"] = $cfg_ocs["states_id_default"];
                                 }
                                 $p->update($input);
                             }
                         }
                     } else {
                         $already_processed[] = $id;
                     }
                 }
             }
         }
     }
     //Look for all peripherals, not locked, not linked to the computer anymore
     $query = "SELECT `id`\n                      FROM `glpi_computers_items`\n                      WHERE `itemtype`='Peripheral'\n                         AND `computers_id`='{$computers_id}'\n                         AND `is_dynamic`='1'\n                         AND `is_deleted`='0'";
     if (!empty($already_processed)) {
         $query .= "AND `items_id` NOT IN (" . implode(',', $already_processed) . ")";
     }
     foreach ($DB->request($query) as $data) {
         // Delete all connexions
         //Get OCS configuration
         $ocs_config = PluginOcsinventoryngOcsServer::getConfig($ocsservers_id);
         //Get the management mode for this device
         $mode = PluginOcsinventoryngOcsServer::getDevicesManagementMode($ocs_config, 'Peripheral');
         $decoConf = $ocs_config["deconnection_behavior"];
         //Change status if :
         // 1 : the management mode IS NOT global
         // 2 : a deconnection's status have been defined
         // 3 : unique with serial
         if ($mode >= 2 && strlen($decoConf) > 0) {
             //Delete periph from glpi
             if ($decoConf == "delete") {
                 $query = "DELETE\n             FROM `glpi_computers_items`\n             WHERE `id`='" . $data['id'] . "'";
                 $result = $DB->query($query);
                 //Put periph in dustbin
             } else {
                 if ($decoConf == "trash") {
                     $query = "UPDATE\n             `glpi_computers_items`\n             SET `is_deleted` = 1\n             WHERE `id`='" . $data['id'] . "'";
                     $result = $DB->query($query);
                 }
             }
         }
         // foreach ($DB->request($query) as $data){
         // Delete all connexions
         // $conn->delete(array('id'             => $data['id'],
         // '_ocsservers_id' => $ocsservers_id), true);
     }
 }
 /**
  * Assign vlans to this port
  *
  *@return nothing
  **/
 function assignVlans()
 {
     global $DB;
     if ($this->connectedPort == '') {
         // no connection to set check existing in DB
         $this->connectedPort = $this->getConnectedPortInDB($this->getValue('ID'));
     }
     $FK_vlans = array();
     foreach ($this->portVlans as $vlan) {
         $FK_vlans[] = Dropdown::importExternal("Vlan", $vlan['number'], 0, array(), $vlan['name']);
     }
     if (count($FK_vlans)) {
         // vlans to add/update
         $ports[] = $this->getValue('ID');
         if ($this->connectedPort != '') {
             $ports[] = $this->connectedPort;
         }
         foreach ($ports as $num => $tmp_port) {
             if ($num == 1) {
                 // connected port
                 $ptpConnected = new PluginFusioninventoryPort();
                 $ptpConnected->load($tmp_port);
                 if ($ptpConnected->fields['device_type'] == NETWORKING_TYPE) {
                     break;
                     // don't update if port on a switch
                 }
             }
             $query = "SELECT *\n                      FROM `glpi_networking_vlan`\n                           LEFT JOIN `glpi_dropdown_vlan`\n                              ON `glpi_networking_vlan`.`FK_vlan`=`glpi_dropdown_vlan`.`ID`\n                      WHERE `FK_port`='{$tmp_port}'";
             if ($result = $DB->query($query)) {
                 if ($DB->numrows($result) == "0") {
                     // this port has no vlan
                     foreach ($FK_vlans as $FK_vlan) {
                         $this->assignVlan($tmp_port, $FK_vlan);
                     }
                 } else {
                     // this port has one or more vlans
                     $vlansDB = array();
                     $vlansDBnumber = array();
                     $vlansToAssign = array();
                     while ($vlanDB = $DB->fetch_assoc($result)) {
                         $vlansDBnumber[] = $vlanDB['name'];
                         $vlansDB[] = array('number' => $vlanDB['name'], 'name' => $vlanDB['comments'], 'ID' => $vlanDB['ID']);
                     }
                     foreach ($this->portVlans as $portVlan) {
                         $vlanInDB = false;
                         $key = '';
                         foreach ($vlansDBnumber as $vlanKey => $vlanDBnumber) {
                             if ($vlanDBnumber == $portVlan['number']) {
                                 $key = $vlanKey;
                             }
                         }
                         if ($key !== '') {
                             unset($vlansDB[$key]);
                             unset($vlansDBnumber[$key]);
                         } else {
                             $vlansToAssign[] = $portVlan;
                         }
                     }
                     foreach ($vlansDB as $vlanToUnassign) {
                         $this->cleanVlan($vlanToUnassign['ID'], $tmp_port);
                     }
                     foreach ($vlansToAssign as $vlanToAssign) {
                         $FK_vlan = Dropdown::importExternal("Vlan", $vlanToAssign['number'], 0, array(), $vlanToAssign['name']);
                         $this->assignVlan($tmp_port, $FK_vlan);
                     }
                 }
             }
         }
     } else {
         // no vlan to add/update --> delete existing
         $query = "SELECT *\n                   FROM `glpi_networking_vlan`\n                   WHERE `FK_port`='" . $this->getValue('ID') . "'";
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result) > 0) {
                 // this port has one or more vlan
                 $this->cleanVlan('', $this->getValue('ID'));
                 if ($this->connectedPort != '') {
                     $ptpConnected = new PluginFusioninventoryPort();
                     $ptpConnected->load($this->connectedPort);
                     if ($ptpConnected->fields['device_type'] != NETWORKING_TYPE) {
                         // don't update vlan on connected port if connected port on a switch
                         $this->cleanVlan('', $this->connectedPort);
                     }
                 }
             }
         }
     }
 }
Exemple #17
0
 /**
  * Create a new printer
  *
  * @param $name         the printer's name (need to be addslashes)
  * @param $manufacturer the printer's manufacturer (need to be addslashes)
  * @param $entity       the entity in which the printer must be added
  * @param $comment      (default '')
  *
  * @return the printer's ID
  **/
 function addPrinter($name, $manufacturer, $entity, $comment = '')
 {
     global $DB, $CFG_GLPI;
     $manufacturer_id = 0;
     if ($manufacturer != '') {
         $manufacturer_id = Dropdown::importExternal('Manufacturer', $manufacturer);
     }
     //If there's a printer in a parent entity with the same name and manufacturer
     $sql = "SELECT `id`\n              FROM `glpi_printers`\n              WHERE `manufacturers_id` = '{$manufacturer_id}'\n                    AND `name` = '{$name}' " . getEntitiesRestrictRequest('AND', 'glpi_printers', 'entities_id', $entity, true);
     $res_printer = $DB->query($sql);
     if ($printer = $DB->fetch_assoc($res_printer)) {
         $id = $printer["id"];
     } else {
         $input["name"] = $name;
         $input["manufacturers_id"] = $manufacturer_id;
         $input["entities_id"] = $entity;
         $id = $this->add($input);
     }
     return $id;
 }
 function replaceids($array)
 {
     global $CFG_GLPI;
     foreach ($array as $key => $value) {
         if (!is_int($key) && ($key == "software" || $key == 'ipaddress' || $key == 'internalport')) {
             // do nothing
         } else {
             //if (is_array($value)) {
             if ((array) $value === $value) {
                 $array[$key] = $this->replaceids($value);
             } else {
                 if (!is_numeric($key) && ($key == "manufacturers_id" || $key == 'bios_manufacturers_id')) {
                     $manufacturer = new Manufacturer();
                     $array[$key] = $manufacturer->processName($value);
                     if ($key == 'bios_manufacturers_id') {
                         $this->foreignkey_itemtype[$key] = getItemTypeForTable(getTableNameForForeignKeyField('manufacturers_id'));
                     } else {
                         if (isset($CFG_GLPI['plugin_fusioninventory_computermanufacturer'][$value])) {
                             $CFG_GLPI['plugin_fusioninventory_computermanufacturer'][$value] = $array[$key];
                         }
                     }
                 }
                 if (!is_numeric($key)) {
                     if ($key == "bios_manufacturers_id") {
                         $array[$key] = Dropdown::importExternal($this->foreignkey_itemtype['manufacturers_id'], $value);
                     } else {
                         if ($key == "locations_id") {
                             $array[$key] = Dropdown::importExternal('Location', $value, $_SESSION["plugin_fusioninventory_entity"]);
                         } else {
                             if (isset($this->foreignkey_itemtype[$key])) {
                                 $array[$key] = Dropdown::importExternal($this->foreignkey_itemtype[$key], $value, $_SESSION["plugin_fusioninventory_entity"]);
                             } else {
                                 if (isForeignKeyField($key) && $key != "users_id") {
                                     $this->foreignkey_itemtype[$key] = getItemTypeForTable(getTableNameForForeignKeyField($key));
                                     if ($key == 'computermodels_id') {
                                         if (isset($CFG_GLPI['plugin_fusioninventory_computermanufacturer'])) {
                                             $manufacturer = current($CFG_GLPI['plugin_fusioninventory_computermanufacturer']);
                                             $array[$key] = Dropdown::importExternal($this->foreignkey_itemtype[$key], $value, $_SESSION["plugin_fusioninventory_entity"], array('manufacturer' => $manufacturer));
                                         } else {
                                             $array[$key] = 0;
                                         }
                                     } else {
                                         $array[$key] = Dropdown::importExternal($this->foreignkey_itemtype[$key], $value, $_SESSION["plugin_fusioninventory_entity"]);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $array;
 }
 /**
  * Update devices with values get by SNMP
  *
  * @param $ID_Device : ID of device
  * @param $type : type of device (NETWORKING_TYPE, PRINTER_TYPE ...)
  * @param $oidsModel : oid list from model SNMP
  * @param $oidvalues : list of values from agent query
  * @param $Array_Object_TypeNameConstant : array with oid => constant in relation with fields to update
  *
  * @return $oidList : array with ports object name and oid
  *
  **/
 static function updateGLPIDevice($ID_Device, $type, $oidsModel, $oidvalues, $Array_Object_TypeNameConstant)
 {
     global $DB, $LANG, $CFG_GLPI, $FUSIONINVENTORY_MAPPING;
     if ($_SESSION['fusioninventory_logs'] == "1") {
         $logs = new PluginFusioninventoryLogs();
     }
     if ($_SESSION['fusioninventory_logs'] == "1") {
         $logs->write("fusioninventory_fullsync", ">>>>>>>>>> Update devices values <<<<<<<<<<", $type, $ID_Device, 1);
     }
     // Update 'last_fusioninventory_update' field
     $query = "UPDATE ";
     if ($type == NETWORKING_TYPE) {
         $query .= "`glpi_plugin_fusioninventory_networking`\n             SET `last_fusioninventory_update`='" . date("Y-m-d H:i:s") . "',\n                 `last_PID_update`='" . $_SESSION['FK_process'] . "'\n             WHERE `FK_networking`='" . $ID_Device . "';";
     }
     if ($type == PRINTER_TYPE) {
         $query .= "`glpi_plugin_fusioninventory_printers`\n             SET `last_fusioninventory_update`='" . date("Y-m-d H:i:s") . "'\n             WHERE `FK_printers`='" . $ID_Device . "';";
     }
     $DB->query($query);
     foreach ($Array_Object_TypeNameConstant as $oid => $link) {
         if (!preg_match("/\\.\$/", $oid)) {
             // SNMPGet ONLY
             if (isset($oidvalues[$oid][""])) {
                 if (isset($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown']) and !empty($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown'])) {
                     $oidvalues[$oid][""] = PluginFusioninventorySNMP::hex_to_string($oidvalues[$oid][""]);
                     if ($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown'] == "glpi_dropdown_model_networking") {
                         $oidvalues[$oid][""] = Dropdown::importExternal("NetworkEquipmentModel", $oidvalues[$oid][""], 0, array("manufacturer" => $oidvalues[$oid][""]));
                     } else {
                         $oidvalues[$oid][""] = Dropdown::importExternal(getItemTypeForTable($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown']), $oidvalues[$oid][""], 0);
                     }
                 }
                 switch ($type) {
                     case NETWORKING_TYPE:
                         $Field = "FK_networking";
                         if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] == "glpi_networking") {
                             $Field = "ID";
                         }
                         break;
                     case PRINTER_TYPE:
                         $Field = "FK_printers";
                         if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] == "glpi_printers") {
                             $Field = "ID";
                         }
                         break;
                 }
                 if ($_SESSION['fusioninventory_logs'] == "1") {
                     $logs->write("fusioninventory_fullsync", $link . " = " . $oidvalues[$oid][""], $type, $ID_Device, 1);
                 }
                 // * Memory
                 if ($link == "ram" or $link == "memory") {
                     $oidvalues[$oid][""] = ceil($oidvalues[$oid][""] / 1024 / 1024);
                     if ($type == PRINTER_TYPE) {
                         $oidvalues[$oid][""] .= " MB";
                     }
                 }
                 if ($link == 'macaddr') {
                     $MacAddress = PluginFusioninventoryIfmac::ifmacwalk_ifmacaddress($oidvalues[$oid][""]);
                     $oidvalues[$oid][""] = $MacAddress;
                 }
                 // Convert hexa in string
                 $oidvalues[$oid][""] = PluginFusioninventorySNMP::hex_to_string($oidvalues[$oid][""]);
                 if (strstr($oidvalues[$oid][""], "noSuchName")) {
                     // NO Update field in GLPI
                 } else {
                     if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] == "glpi_plugin_fusioninventory_printers_cartridges") {
                         // * Printers cartridges
                         $object_name_clean = str_replace("MAX", "", $link);
                         $object_name_clean = str_replace("REMAIN", "", $object_name_clean);
                         if (strstr($link, "MAX")) {
                             $printer_cartridges_max_remain[$object_name_clean]["MAX"] = $oidvalues[$oid][""];
                         }
                         if (strstr($link, "REMAIN")) {
                             $printer_cartridges_max_remain[$object_name_clean]["REMAIN"] = $oidvalues[$oid][""];
                         }
                         if (isset($printer_cartridges_max_remain[$object_name_clean]["MAX"]) and isset($printer_cartridges_max_remain[$object_name_clean]["REMAIN"])) {
                             $pourcentage = ceil(100 * $printer_cartridges_max_remain[$object_name_clean]["REMAIN"] / $printer_cartridges_max_remain[$object_name_clean]["MAX"]);
                             // Test existance of row in MySQl
                             $query_sel = "SELECT *\n                                FROM " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                WHERE " . $Field . "='" . $ID_Device . "'\n                                      AND `object_name`='" . $object_name_clean . "';";
                             $result_sel = $DB->query($query_sel);
                             if ($DB->numrows($result_sel) == "0") {
                                 $queryInsert = "INSERT INTO " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                                 (" . $Field . ",object_name)\n                                     VALUES('" . $ID_Device . "', '" . $object_name_clean . "');";
                                 $DB->query($queryInsert);
                             }
                             $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $pourcentage . "'\n                                  WHERE " . $Field . "='" . $ID_Device . "'\n                                        AND `object_name`='" . $object_name_clean . "';";
                             $DB->query($queryUpdate);
                             unset($printer_cartridges_max_remain[$object_name_clean]["MAX"]);
                             unset($printer_cartridges_max_remain[$object_name_clean]["REMAIN"]);
                         } else {
                             // Test existance of row in MySQl
                             $query_sel = "SELECT *\n                                FROM " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                WHERE " . $Field . "='" . $ID_Device . "'\n                                      AND `object_name`='" . $link . "';";
                             $result_sel = $DB->query($query_sel);
                             if ($DB->numrows($result_sel) == "0") {
                                 $queryInsert = "INSERT INTO " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                                 (" . $Field . ",object_name)\n                                     VALUES('" . $ID_Device . "', '" . $link . "');";
                                 $DB->query($queryInsert);
                             }
                             $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $oidvalues[$oid][""] . "'\n                                  WHERE " . $Field . "='" . $ID_Device . "'\n                                        AND `object_name`='" . $link . "';";
                             $DB->query($queryUpdate);
                         }
                     } else {
                         if (strstr($link, "pagecounter")) {
                             // Detect if the script has wroten a line for the counter today
                             // (if yes, don't touch, else add line)
                             $today = strftime("%Y-%m-%d", time());
                             $query_line = "SELECT *\n                              FROM `glpi_plugin_fusioninventory_printers_history`\n                              WHERE `date` LIKE '" . $today . "%'\n                                    AND `FK_printers`='" . $ID_Device . "';";
                             $result_line = $DB->query($query_line);
                             if ($DB->numrows($result_line) == "0") {
                                 if (empty($oidvalues[$oid][""])) {
                                     $oidvalues[$oid][""] = 0;
                                 }
                                 $queryInsert = "INSERT INTO " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                              (" . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "," . $Field . ", `date`)\n                                  VALUES('" . $oidvalues[$oid][""] . "','" . $ID_Device . "', '" . $today . "');";
                                 $DB->query($queryInsert);
                             } else {
                                 $data_line = $DB->fetch_assoc($result_line);
                                 if ($data_line[$FUSIONINVENTORY_MAPPING[$type][$link]['field']] == "0") {
                                     if (empty($oidvalues[$oid][""])) {
                                         $oidvalues[$oid][""] = 0;
                                     }
                                     $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                     SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $oidvalues[$oid][""] . "'\n                                     WHERE " . $Field . "='" . $ID_Device . "'\n                                           AND `date` LIKE '" . $today . "%';";
                                     $DB->query($queryUpdate);
                                 }
                             }
                         } else {
                             if ($link == "cpuuser" or $link == "cpusystem") {
                                 if ($object_name == "cpuuser") {
                                     $cpu_values['cpuuser'] = $oidvalues[$oid][""];
                                 }
                                 if ($object_name == "cpusystem") {
                                     $cpu_values['cpusystem'] = $oidvalues[$oid][""];
                                 }
                                 if (isset($cpu_values['cpuuser']) and isset($cpu_values['cpusystem'])) {
                                     $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . ($cpu_values['cpuuser'] + $cpu_values['cpusystem']) . "'\n                                  WHERE " . $Field . "='" . $ID_Device . "';";
                                     $DB->query($queryUpdate);
                                     unset($cpu_values);
                                 }
                             } else {
                                 if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] != "") {
                                     if ($FUSIONINVENTORY_MAPPING[$type][$link]['field'] == "cpu" and empty($oidvalues[$oid][""])) {
                                         $SNMPValue = 0;
                                     }
                                     if (strstr($FUSIONINVENTORY_MAPPING[$type][$link]['table'], "glpi_plugin_fusioninventory")) {
                                         $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $oidvalues[$oid][""] . "'\n                  WHERE " . $Field . "='" . $ID_Device . "'";
                                         $DB->query($queryUpdate);
                                     } else {
                                         $commonitem = new commonitem();
                                         $commonitem->setType($type, true);
                                         $tableau[$Field] = $ID_Device;
                                         $tableau[$FUSIONINVENTORY_MAPPING[$type][$link]['field']] = $oidvalues[$oid][""];
                                         $commonitem->obj->update($tableau);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * Add a followup to a existing ticket
  * for an authenticated user
  *
  * @param $params array of options (ticket, content)
  * @param $protocol
  *
  * @return array of hashtable
  **/
 static function methodAddTicketFollowup($params, $protocol)
 {
     if (isset($params['help'])) {
         return array('ticket' => 'integer,mandatory', 'content' => 'string,mandatory', 'users_login' => 'string,optional', 'close' => 'bool,optional', 'reopen' => 'bool,optional', 'source' => 'string,optional', 'private' => 'bool,optional', 'help' => 'bool,optional');
     }
     if (!Session::getLoginUserID()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED);
     }
     $ticket = new Ticket();
     if (isset($params['users_login']) && is_numeric($params['users_login'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'users_login should be a string');
     }
     if (isset($params['users_login']) && is_string($params['users_login'])) {
         $user = new User();
         if (!($users_id = $user->getIdByName($params['users_login']))) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'unable to get users_id with the users_login');
         }
     }
     if (!isset($params['ticket'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'ticket');
     }
     if (!is_numeric($params['ticket'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'ticket');
     }
     if (!$ticket->can($params['ticket'], 'r')) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND);
     }
     if (!$ticket->canAddFollowups()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
     }
     if (in_array($ticket->fields["status"], $ticket->getSolvedStatusArray()) && !$ticket->canApprove()) {
         // Logged user not allowed
         if (isset($users_id)) {
             // If we get the users id
             $approbationSolution = self::checkApprobationSolution($users_id, $ticket);
             if (!$approbationSolution) {
                 return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
             }
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
         }
     }
     if (!isset($params['content'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'content');
     }
     // Source of the ticket, dynamically created
     if (isset($params['source'])) {
         if (empty($params['content'])) {
             return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'source');
         }
         $source = Dropdown::importExternal('RequestType', $params['source']);
     } else {
         $source = Dropdown::importExternal('RequestType', 'WebServices');
     }
     $private = isset($params['private']) && $params['private'] ? 1 : 0;
     $followup = new TicketFollowup();
     $user = 0;
     if (isset($users_id)) {
         $user = $users_id;
     }
     $data = array('tickets_id' => $params['ticket'], 'requesttypes_id' => $source, 'is_private' => $private, 'users_id' => $user, 'content' => addslashes(Toolbox::clean_cross_side_scripting_deep($params["content"])));
     if (isset($params['close'])) {
         if (isset($params['reopen'])) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'can\'t use both reopen and close options');
         }
         if (in_array($ticket->fields["status"], $ticket->getSolvedStatusArray())) {
             $data['add_close'] = 1;
             if (isset($users_id)) {
                 $data['users_id'] = $users_id;
             }
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'close for not solved ticket');
         }
     }
     if (isset($params['reopen'])) {
         if (in_array($ticket->fields['status'], array(Ticket::SOLVED, Ticket::WAITING))) {
             $data['add_reopen'] = 1;
             if (isset($users_id)) {
                 $data['users_id'] = $users_id;
             }
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'reopen for not solved or waiting ticket');
         }
     }
     if (in_array($ticket->fields["status"], $ticket->getSolvedStatusArray()) && !isset($params['close']) && !isset($params['reopen'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'missing reopen/close option for solved ticket');
     }
     if (in_array($ticket->fields["status"], $ticket->getClosedStatusArray())) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'cannot add to a closed ticket');
     }
     if ($followup->add($data)) {
         return self::methodGetTicket(array('ticket' => $params['ticket']), $protocol);
     }
     return self::Error($protocol, WEBSERVICES_ERROR_FAILED, '', self::getDisplayError());
 }
Exemple #21
0
 /**
  * Function that try to load from the SSO server the user information...
  *
  * @since version 0.84
  **/
 function getFromSSO()
 {
     global $DB, $CFG_GLPI;
     $a_field = array();
     foreach ($CFG_GLPI as $key => $value) {
         if (!is_array($value) && !empty($value) && strstr($key, "_ssofield")) {
             $key = str_replace('_ssofield', '', $key);
             $a_field[$key] = $value;
         }
     }
     if (count($a_field) == 0) {
         return true;
     }
     $this->fields['_ruleright_process'] = true;
     foreach ($a_field as $field => $value) {
         if (!isset($_SERVER[$value]) || empty($_SERVER[$value])) {
             switch ($field) {
                 case "title":
                     $this->fields['usertitles_id'] = 0;
                     break;
                 case "category":
                     $this->fields['usercategories_id'] = 0;
                     break;
                 default:
                     $this->fields[$field] = "";
             }
         } else {
             switch ($field) {
                 case "email1":
                 case "email2":
                 case "email3":
                 case "email4":
                     // Manage multivaluable fields
                     if (!preg_match('/count/', $_SERVER[$value])) {
                         $this->fields["_emails"][] = addslashes($_SERVER[$value]);
                     }
                     // Only get them once if duplicated
                     $this->fields["_emails"] = array_unique($this->fields["_emails"]);
                     break;
                 case "language":
                     $language = Config::getLanguage($_SERVER[$value]);
                     if ($language != '') {
                         $this->fields[$field] = $language;
                     }
                     break;
                 case "title":
                     $this->fields['usertitles_id'] = Dropdown::importExternal('UserTitle', addslashes($_SERVER[$value]));
                     break;
                 case "category":
                     $this->fields['usercategories_id'] = Dropdown::importExternal('UserCategory', addslashes($_SERVER[$value]));
                     break;
                 default:
                     $this->fields[$field] = $_SERVER[$value];
                     break;
             }
         }
     }
     ///Only process rules if working on the master database
     if (!$DB->isSlave()) {
         //Instanciate the affectation's rule
         $rule = new RuleRightCollection();
         $this->fields = $rule->processAllRules(array(), Toolbox::stripslashes_deep($this->fields), array('type' => 'SSO', 'email' => $this->fields["_emails"], 'login' => $this->fields["name"]));
         //If rule  action is ignore import
         if (isset($this->fields["_stop_import"])) {
             return false;
         }
     }
     return true;
 }
 /**
  * Import the devices for a computer
  *
  * @param $itemtype integer : item type
  * @param $entity integer : entity of the computer
  * @param $computers_id integer : glpi computer id.
  * @param $ocsid integer : ocs computer id (ID).
  * @param $ocsservers_id integer : ocs server id
  * @param $cfg_ocs array : ocs config
  * @param $import_periph array : already imported periph
  * @param $dohistory boolean : log changes ?
  *
  * @return Nothing (void).
  **/
 static function updatePeripherals($itemtype, $entity, $computers_id, $ocsid, $ocsservers_id, $cfg_ocs, $import_periph, $dohistory)
 {
     global $DB, $DBocs;
     self::checkOCSconnection($ocsservers_id);
     $do_clean = false;
     $connID = 0;
     //Tag for data since 0.70 for the import_monitor array.
     $count_monitor = count($import_periph);
     switch ($itemtype) {
         case 'Monitor':
             if ($cfg_ocs["import_monitor"]) {
                 //Update data in import_monitor array for 0.70
                 if (!in_array(self::IMPORT_TAG_070, $import_periph)) {
                     foreach ($import_periph as $key => $val) {
                         $monitor_tag = $val;
                         //delete old value
                         self::deleteInOcsArray($computers_id, $key, "import_monitor");
                         //search serial when it exists
                         $monitor_serial = "";
                         $query_monitor_id = "SELECT `items_id`\n                                          FROM `glpi_computers_items`\n                                          WHERE `id` = '{$key}'";
                         $result_monitor_id = $DB->query($query_monitor_id);
                         if ($DB->numrows($result_monitor_id) == 1) {
                             //get monitor Id
                             $id_monitor = $DB->result($result_monitor_id, 0, "items_id");
                             $query_monitor_serial = "SELECT `serial`\n                                                 FROM `glpi_monitors`\n                                                 WHERE `id` = '{$id_monitor}'";
                             $result_monitor_serial = $DB->query($query_monitor_serial);
                             //get serial
                             if ($DB->numrows($result_monitor_serial) == 1) {
                                 $monitor_serial = $DB->result($result_monitor_serial, 0, "serial");
                             }
                         }
                         //concat name + serial
                         $monitor_tag .= $monitor_serial;
                         //add new value (serial + name when its possible)
                         self::addToOcsArray($computers_id, array($key => $monitor_tag), "import_monitor");
                         //Update the array with the new value of the monitor
                         $import_periph[$key] = $monitor_tag;
                     }
                     //add the tag for the array version's
                     self::addToOcsArray($computers_id, array(0 => self::IMPORT_TAG_070), "import_monitor");
                 }
                 $do_clean = true;
                 $m = new Monitor();
                 $query = "SELECT DISTINCT `CAPTION`, `MANUFACTURER`, `DESCRIPTION`, `SERIAL`, `TYPE`\n                         FROM `monitors`\n                         WHERE `HARDWARE_ID` = '{$ocsid}'";
                 $result = $DBocs->query($query);
                 $lines = array();
                 $checkserial = true;
                 // First pass - check if all serial present
                 if ($DBocs->numrows($result) > 0) {
                     while ($line = $DBocs->fetch_array($result)) {
                         if (empty($line["SERIAL"])) {
                             $checkserial = false;
                         }
                         $lines[] = clean_cross_side_scripting_deep(addslashes_deep($line));
                     }
                 }
                 if (count($lines) > 0 && ($cfg_ocs["import_monitor"] <= 2 || $checkserial)) {
                     foreach ($lines as $line) {
                         $mon = array();
                         $mon["name"] = $line["CAPTION"];
                         if (empty($line["CAPTION"]) && !empty($line["MANUFACTURER"])) {
                             $mon["name"] = $line["MANUFACTURER"];
                         }
                         if (empty($line["CAPTION"]) && !empty($line["TYPE"])) {
                             if (!empty($line["MANUFACTURER"])) {
                                 $mon["name"] .= " ";
                             }
                             $mon["name"] .= $line["TYPE"];
                         }
                         $mon["serial"] = $line["SERIAL"];
                         $checkMonitor = $mon["name"];
                         if (!empty($mon["serial"])) {
                             $checkMonitor .= $mon["serial"];
                         }
                         if (!empty($mon["name"])) {
                             $id = array_search(stripslashes($checkMonitor), $import_periph);
                         }
                         if ($id === false) {
                             // Clean monitor object
                             $m->reset();
                             $mon["manufacturers_id"] = Dropdown::importExternal('Manufacturer', $line["MANUFACTURER"]);
                             if ($cfg_ocs["import_monitor_comment"]) {
                                 $mon["comment"] = $line["DESCRIPTION"];
                             }
                             $id_monitor = 0;
                             if ($cfg_ocs["import_monitor"] == 1) {
                                 //Config says : manage monitors as global
                                 //check if monitors already exists in GLPI
                                 $mon["is_global"] = 1;
                                 $query = "SELECT `id`\n                                     FROM `glpi_monitors`\n                                     WHERE `name` = '" . $mon["name"] . "'\n                                           AND `is_global` = '1'\n                                           AND `entities_id` = '{$entity}'";
                                 $result_search = $DB->query($query);
                                 if ($DB->numrows($result_search) > 0) {
                                     //Periph is already in GLPI
                                     //Do not import anything just get periph ID for link
                                     $id_monitor = $DB->result($result_search, 0, "id");
                                 } else {
                                     $input = $mon;
                                     if ($cfg_ocs["states_id_default"] > 0) {
                                         $input["states_id"] = $cfg_ocs["states_id_default"];
                                     }
                                     $input["entities_id"] = $entity;
                                     $id_monitor = $m->add($input);
                                 }
                             } else {
                                 if ($cfg_ocs["import_monitor"] >= 2) {
                                     //Config says : manage monitors as single units
                                     //Import all monitors as non global.
                                     $mon["is_global"] = 0;
                                     // Try to find a monitor with the same serial.
                                     if (!empty($mon["serial"])) {
                                         $query = "SELECT `id`\n                                        FROM `glpi_monitors`\n                                        WHERE `serial` LIKE '%" . $mon["serial"] . "%'\n                                              AND `is_global` = '0'\n                                              AND `entities_id` = '{$entity}'";
                                         $result_search = $DB->query($query);
                                         if ($DB->numrows($result_search) == 1) {
                                             //Monitor founded
                                             $id_monitor = $DB->result($result_search, 0, "id");
                                         }
                                     }
                                     //Search by serial failed, search by name
                                     if ($cfg_ocs["import_monitor"] == 2 && !$id_monitor) {
                                         //Try to find a monitor with no serial, the same name and not already connected.
                                         if (!empty($mon["name"])) {
                                             $query = "SELECT `glpi_monitors`.`id`\n                                           FROM `glpi_monitors`\n                                           LEFT JOIN `glpi_computers_items`\n                                                ON (`glpi_computers_items`.`itemtype`='Monitor'\n                                                    AND `glpi_computers_items`.`items_id`\n                                                            =`glpi_monitors`.`id`)\n                                           WHERE `serial` = ''\n                                                 AND `name` = '" . $mon["name"] . "'\n                                                 AND `is_global` = '0'\n                                                 AND `entities_id` = '{$entity}'\n                                                 AND `glpi_computers_items`.`computers_id` IS NULL";
                                             $result_search = $DB->query($query);
                                             if ($DB->numrows($result_search) == 1) {
                                                 $id_monitor = $DB->result($result_search, 0, "id");
                                             }
                                         }
                                     }
                                     if (!$id_monitor) {
                                         $input = $mon;
                                         if ($cfg_ocs["states_id_default"] > 0) {
                                             $input["states_id"] = $cfg_ocs["states_id_default"];
                                         }
                                         $input["entities_id"] = $entity;
                                         $id_monitor = $m->add($input);
                                     }
                                 }
                             }
                             // ($cfg_ocs["import_monitor"] >= 2)
                             if ($id_monitor) {
                                 //Import unique : Disconnect monitor on other computer done in Connect function
                                 $conn = new Computer_Item();
                                 $connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Monitor', 'items_id' => $id_monitor, '_no_history' => !$dohistory));
                                 if (!in_array(self::IMPORT_TAG_070, $import_periph)) {
                                     self::addToOcsArray($computers_id, array(0 => self::IMPORT_TAG_070), "import_monitor");
                                 }
                                 if ($connID > 0) {
                                     // sanity check - Add can fail
                                     self::addToOcsArray($computers_id, array($connID => $checkMonitor), "import_monitor");
                                 }
                                 $count_monitor++;
                                 //Update column "is_deleted" set value to 0 and set status to default
                                 $input = array();
                                 $old = new Monitor();
                                 if ($old->getFromDB($id_monitor)) {
                                     if ($old->fields["is_deleted"]) {
                                         $input["is_deleted"] = 0;
                                     }
                                     if ($cfg_ocs["states_id_default"] > 0 && $old->fields["states_id"] != $cfg_ocs["states_id_default"]) {
                                         $input["states_id"] = $cfg_ocs["states_id_default"];
                                     }
                                     if (empty($old->fields["name"]) && !empty($mon["name"])) {
                                         $input["name"] = $mon["name"];
                                     }
                                     if (empty($old->fields["serial"]) && !empty($mon["serial"])) {
                                         $input["serial"] = $mon["serial"];
                                     }
                                     if (count($input)) {
                                         $input["id"] = $id_monitor;
                                         $input['entities_id'] = $entity;
                                         $m->update($input);
                                     }
                                 }
                             }
                         } else {
                             // found in array
                             unset($import_periph[$id]);
                         }
                     }
                     // end foreach
                 }
                 if (in_array(self::IMPORT_TAG_070, $import_periph)) {
                     //unset the version Tag
                     unset($import_periph[0]);
                 }
             }
             break;
         case 'Printer':
             if ($cfg_ocs["import_printer"]) {
                 $do_clean = true;
                 $query = "SELECT *\n                         FROM `printers`\n                         WHERE `HARDWARE_ID` = '{$ocsid}'";
                 $result = $DBocs->query($query);
                 $p = new Printer();
                 if ($DBocs->numrows($result) > 0) {
                     while ($line = $DBocs->fetch_array($result)) {
                         $line = clean_cross_side_scripting_deep(addslashes_deep($line));
                         $print = array();
                         // TO TEST : PARSE NAME to have real name.
                         if (!seems_utf8($line["NAME"])) {
                             $print["name"] = encodeInUtf8($line["NAME"]);
                         } else {
                             $print["name"] = $line["NAME"];
                         }
                         if (empty($print["name"])) {
                             $print["name"] = $line["DRIVER"];
                         }
                         $management_process = $cfg_ocs["import_printer"];
                         //Params for the dictionnary
                         $params['name'] = $print['name'];
                         $params['manufacturer'] = "";
                         $params['DRIVER'] = $line['DRIVER'];
                         $params['PORT'] = $line['PORT'];
                         if (!empty($print["name"])) {
                             $rulecollection = new RuleDictionnaryPrinterCollection();
                             $res_rule = addslashes_deep($rulecollection->processAllRules($params, array(), array()));
                             if (!isset($res_rule["_ignore_ocs_import"]) || !$res_rule["_ignore_ocs_import"]) {
                                 foreach ($res_rule as $key => $value) {
                                     if ($value != '' && $value[0] != '_') {
                                         $print[$key] = $value;
                                     }
                                 }
                                 //                            if (isset($res_rule['is_global'])) {
                                 //                               logDebug($res_rule);
                                 //                            }
                                 if (isset($res_rule['is_global'])) {
                                     if (!$res_rule['is_global']) {
                                         $management_process = 2;
                                     } else {
                                         $management_process = 1;
                                     }
                                 }
                                 if (!in_array(stripslashes($print["name"]), $import_periph)) {
                                     // Clean printer object
                                     $p->reset();
                                     $print["comment"] = $line["PORT"] . "\r\n" . $line["DRIVER"];
                                     self::analizePrinterPorts($print, $line["PORT"]);
                                     $id_printer = 0;
                                     if ($management_process == 1) {
                                         //Config says : manage printers as global
                                         //check if printers already exists in GLPI
                                         $print["is_global"] = MANAGEMENT_GLOBAL;
                                         $query = "SELECT `id`\n                                           FROM `glpi_printers`\n                                           WHERE `name` = '" . $print["name"] . "'\n                                                 AND `is_global` = '1'\n                                                 AND `entities_id` = '{$entity}'";
                                         $result_search = $DB->query($query);
                                         if ($DB->numrows($result_search) > 0) {
                                             //Periph is already in GLPI
                                             //Do not import anything just get periph ID for link
                                             $id_printer = $DB->result($result_search, 0, "id");
                                         } else {
                                             $input = $print;
                                             if ($cfg_ocs["states_id_default"] > 0) {
                                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                                             }
                                             $input["entities_id"] = $entity;
                                             //                                     if (isset($res_rule['is_global'])) {
                                             //                                        logDebug("global",$input);
                                             //                                     }
                                             $id_printer = $p->add($input);
                                         }
                                     } else {
                                         if ($management_process == 2) {
                                             //Config says : manage printers as single units
                                             //Import all printers as non global.
                                             $input = $print;
                                             $input["is_global"] = MANAGEMENT_UNITARY;
                                             if ($cfg_ocs["states_id_default"] > 0) {
                                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                                             }
                                             $input["entities_id"] = $entity;
                                             //                                  if (isset($res_rule['is_global'])) {
                                             //                                     logDebug("unitary",$input);
                                             //                                  }
                                             $id_printer = $p->add($input);
                                         }
                                     }
                                     if ($id_printer) {
                                         $conn = new Computer_Item();
                                         $connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Printer', 'items_id' => $id_printer, '_no_history' => !$dohistory));
                                         if ($connID > 0) {
                                             // sanity check - Add can fail
                                             self::addToOcsArray($computers_id, array($connID => $print["name"]), "import_printer");
                                         }
                                         //Update column "is_deleted" set value to 0 and set status to default
                                         $input = array();
                                         $input["id"] = $id_printer;
                                         $input["is_deleted"] = 0;
                                         $input["entities_id"] = $entity;
                                         if ($cfg_ocs["states_id_default"] > 0) {
                                             $input["states_id"] = $cfg_ocs["states_id_default"];
                                         }
                                         $p->update($input);
                                     }
                                 } else {
                                     $id = array_search(stripslashes($print["name"]), $import_periph);
                                     unset($import_periph[$id]);
                                 }
                             }
                         }
                     }
                 }
             }
             break;
         case 'Peripheral':
             if ($cfg_ocs["import_periph"]) {
                 $do_clean = true;
                 $p = new Peripheral();
                 $query = "SELECT DISTINCT `CAPTION`, `MANUFACTURER`, `INTERFACE`, `TYPE`\n                         FROM `inputs`\n                         WHERE `HARDWARE_ID` = '{$ocsid}'\n                               AND `CAPTION` <> ''";
                 $result = $DBocs->query($query);
                 if ($DBocs->numrows($result) > 0) {
                     while ($line = $DBocs->fetch_array($result)) {
                         $line = clean_cross_side_scripting_deep(addslashes_deep($line));
                         $periph = array();
                         if (!seems_utf8($line["CAPTION"])) {
                             $periph["name"] = encodeInUtf8($line["CAPTION"]);
                         } else {
                             $periph["name"] = $line["CAPTION"];
                         }
                         if (!in_array(stripslashes($periph["name"]), $import_periph)) {
                             // Clean peripheral object
                             $p->reset();
                             if ($line["MANUFACTURER"] != "NULL") {
                                 $periph["brand"] = $line["MANUFACTURER"];
                             }
                             if ($line["INTERFACE"] != "NULL") {
                                 $periph["comment"] = $line["INTERFACE"];
                             }
                             $periph["peripheraltypes_id"] = Dropdown::importExternal('PeripheralType', $line["TYPE"]);
                             $id_periph = 0;
                             if ($cfg_ocs["import_periph"] == 1) {
                                 //Config says : manage peripherals as global
                                 //check if peripherals already exists in GLPI
                                 $periph["is_global"] = 1;
                                 $query = "SELECT `id`\n                                     FROM `glpi_peripherals`\n                                     WHERE `name` = '" . $periph["name"] . "'\n                                           AND `is_global` = '1'\n                                           AND `entities_id` = '{$entity}'";
                                 $result_search = $DB->query($query);
                                 if ($DB->numrows($result_search) > 0) {
                                     //Periph is already in GLPI
                                     //Do not import anything just get periph ID for link
                                     $id_periph = $DB->result($result_search, 0, "id");
                                 } else {
                                     $input = $periph;
                                     if ($cfg_ocs["states_id_default"] > 0) {
                                         $input["states_id"] = $cfg_ocs["states_id_default"];
                                     }
                                     $input["entities_id"] = $entity;
                                     $id_periph = $p->add($input);
                                 }
                             } else {
                                 if ($cfg_ocs["import_periph"] == 2) {
                                     //Config says : manage peripherals as single units
                                     //Import all peripherals as non global.
                                     $input = $periph;
                                     $input["is_global"] = 0;
                                     if ($cfg_ocs["states_id_default"] > 0) {
                                         $input["states_id"] = $cfg_ocs["states_id_default"];
                                     }
                                     $input["entities_id"] = $entity;
                                     $id_periph = $p->add($input);
                                 }
                             }
                             if ($id_periph) {
                                 $conn = new Computer_Item();
                                 if ($connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Peripheral', 'items_id' => $id_periph, '_no_history' => !$dohistory))) {
                                     self::addToOcsArray($computers_id, array($connID => $periph["name"]), "import_peripheral");
                                     //Update column "is_deleted" set value to 0 and set status to default
                                     $input = array();
                                     $input["id"] = $id_periph;
                                     $input["is_deleted"] = 0;
                                     $input["entities_id"] = $entity;
                                     if ($cfg_ocs["states_id_default"] > 0) {
                                         $input["states_id"] = $cfg_ocs["states_id_default"];
                                     }
                                     $p->update($input);
                                 }
                             }
                         } else {
                             $id = array_search(stripslashes($periph["name"]), $import_periph);
                             unset($import_periph[$id]);
                         }
                     }
                 }
             }
             break;
     }
     // Disconnect Unexisting Items not found in OCS
     if ($do_clean && count($import_periph)) {
         $conn = new Computer_Item();
         foreach ($import_periph as $key => $val) {
             switch ($itemtype) {
                 case 'Monitor':
                     // Only if sync done
                     if ($cfg_ocs["import_monitor"] <= 2 || $checkserial) {
                         $conn->delete(array('id' => $key, '_ocsservers_id' => $ocsservers_id));
                         self::deleteInOcsArray($computers_id, $key, "import_monitor");
                     }
                     break;
                 case 'Printer':
                     $conn->delete(array('id' => $key, '_ocsservers_id' => $ocsservers_id));
                     self::deleteInOcsArray($computers_id, $key, "import_printer");
                     break;
                 case 'Peripheral':
                     $conn->delete(array('id' => $key, '_ocsservers_id' => $ocsservers_id));
                     self::deleteInOcsArray($computers_id, $key, "import_peripheral");
                     break;
                 default:
                     $conn->delete(array('id' => $key, '_ocsservers_id' => $ocsservers_id));
             }
         }
     }
 }