/** * Check delete / purge on a template of printer */ public function testPrinterTemplate() { $printer = new Printer(); // Create $id[0] = $printer->add(array('name' => "Printer 1", 'entities_id' => 0, 'is_template' => 1)); $this->assertGreaterThan(0, $id[0], "Fail to create Printer Template"); $this->assertTrue($printer->getFromDB($id[0]), "Fail: can't read Template"); $this->assertEquals(0, $printer->fields['is_deleted'], "Fail: is_deleted set"); $this->assertEquals(1, $printer->fields['is_template'], "Fail: is_template not set"); // Delete (= purge) $this->assertTrue($printer->delete(array('id' => $id[0]), 0), "Fail: can't delete Template"); $this->assertFalse($printer->getFromDB($id[0]), "Fail: can read Template (deleted)"); }
/** * @covers Printer::delete * @covers Printer::restore */ public function testDelete() { $obj = new Printer(); $this->assertTrue($obj->maybeDeleted()); // Add $id = $obj->add(['name' => __METHOD__]); $this->assertGreaterThan(0, $id); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(0, $obj->getField('is_deleted')); $this->assertEquals(0, $obj->isDeleted()); // Delete $this->assertTrue($obj->delete(['id' => $id], 0)); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(1, $obj->getField('is_deleted')); $this->assertEquals(1, $obj->isDeleted()); // Restore $this->assertTrue($obj->restore(['id' => $id], 0)); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(0, $obj->getField('is_deleted')); $this->assertEquals(0, $obj->isDeleted()); // Purge $this->assertTrue($obj->delete(['id' => $id], 1)); $this->assertFalse($obj->getFromDB($id)); }
if (!isset($_GET["id"])) { $_GET["id"] = ""; } if (!isset($_GET["sort"])) { $_GET["sort"] = ""; } if (!isset($_GET["order"])) { $_GET["order"] = ""; } if (!isset($_GET["withtemplate"])) { $_GET["withtemplate"] = ""; } $print = new Printer(); if (isset($_POST["add"])) { $print->check(-1, 'w', $_POST); if ($newID = $print->add($_POST)) { Event::log($newID, "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][20] . " " . $_POST["name"] . "."); } glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_POST["delete"])) { $print->check($_POST["id"], 'd'); $print->delete($_POST); Event::log($_POST["id"], "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][22]); $print->redirectToList(); } else { if (isset($_POST["restore"])) { $print->check($_POST["id"], 'd'); $print->restore($_POST); Event::log($_POST["id"], "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][23]); $print->redirectToList();
/** Generate bigdump : generate items for an entity * * @param $ID_entity entity ID **/ function generate_entity($ID_entity) { global $MAX, $DB, $percent, $FIRST, $LAST, $MAX_KBITEMS_BY_CAT, $MAX_DISK, $DOCUMENTS, $NET_PORT, $NET_LOC; regenerateTreeCompleteName("glpi_entities"); $current_year = date("Y"); // DOMAIN $items = array("SP2MI", "CAMPUS"," IUT86", "PRESIDENCE", "CEAT", "D'omaine"); $dp = new Domain(); $FIRST["domain"] = getMaxItem("glpi_domains")+1; for ($i=0 ; $i<$MAX['domain'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "domain $ID_entity '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'comment' => "comment $val"))); } $LAST["domain"] = getMaxItem("glpi_domains"); // STATUS $items = array("Reparation", "En stock", "En fonction", "Retour SAV", "En attente d'"); $dp = new State(); $FIRST["state"] = getMaxItem("glpi_states")+1; for ($i=0 ; $i<$MAX['state'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "State $ID_entity '$i"; } $state_id = $dp->add(toolbox::addslashes_deep(array('name' => $val, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'comment' => "comment $val"))); // generate sub status for ($j=0 ; $j<$MAX['state'] ; $j++) { $val2 = "Sub $val $j"; $dp->add(toolbox::addslashes_deep(array('name' => $val2, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'states_id' => $state_id, 'comment' => "comment $val"))); } } $LAST["state"] = getMaxItem("glpi_states"); // glpi_groups $FIRST["groups"] = getMaxItem("glpi_groups")+1; $group = new Group(); for ($i=0 ; $i<$MAX['groups'] ; $i++) { $gID = $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "group d'$i", 'comment' => "comment group d'$i", 'is_assign' => 0))); // Generate sub group for ($j=0 ; $j<$MAX['groups'] ; $j++) { $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "subgroup d'$j", 'comment' => "comment subgroup d'$j of group $i", 'groups_id' => $gID, 'is_assign' => 0))); } } $LAST["groups"] = getMaxItem("glpi_groups"); $FIRST["techgroups"] = $LAST["groups"]+1; for ($i=0 ; $i<$MAX['groups'] ; $i++) { $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "tech group d'$i", 'comment' => "comment tech group d'$i"))); } $LAST["techgroups"] = getMaxItem("glpi_groups"); regenerateTreeCompleteName("glpi_groups"); // glpi_users $FIRST["users_sadmin"] = getMaxItem("glpi_users")+1; $user = new User(); $gu = new Group_User(); for ($i=0 ; $i<$MAX['users_sadmin'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "sadmin$i-$ID_entity", 'password' => "sadmin'$i", 'password2' => "sadmin'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "sadmin '$i name", 'firstname' => "sadmin '$i firstname", 'comment' => "comment' $i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 4, '_entities_id' => $ID_entity, '_is_recursive' => 1 ))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']))); } $LAST["users_sadmin"] = getMaxItem("glpi_users"); $FIRST["users_admin"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_admin'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "admin$i-$ID_entity", 'password' => "admin'$i", 'password2' => "admin'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "admin$i 'name", 'firstname' => "admin$i 'firstname", 'comment' => "comment '$i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 3, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']), 'is_manager' => 1, 'is_delegate' => 1)); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']), 'is_manager' => 1, 'is_delegate' => 1)); } $LAST["users_admin"] = getMaxItem("glpi_users"); $FIRST["users_normal"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_normal'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "normal$i-$ID_entity", 'password' => "normal'$i", 'password2' => "normal'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "normal$i 'name", 'firstname' => "normal$i 'firstname", 'comment' => "comment '$i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 2, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']))); } $LAST["users_normal"] = getMaxItem("glpi_users"); $FIRST["users_postonly"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_postonly'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "postonly$i-$ID_entity", 'password' => "postonly'$i", 'password2' => "postonly'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "postonly$i 'name", 'firstname' => "postonly$i 'firstname", 'comment' => "comment' $i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 1, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); } $LAST["users_postonly"] = getMaxItem("glpi_users"); $FIRST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories")+1; $kbc = new KnowbaseItemCategory(); for ($i=0 ; $i<max(1,pow($MAX['kbcategories'],1/3)) ; $i++) { $newID = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity ' categorie $i", 'comment' => "comment ' categorie $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $j++) { $newID2 = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity s-categorie '$j", 'comment' => "comment s-categorie '$j", 'knowbaseitemcategories_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $k++) { $newID2 = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity ss-categorie' $k", 'comment' => "comment ss-categorie' $k", 'knowbaseitemcategories_id' => $newID2))); } } } $query = "OPTIMIZE TABLE `glpi_knowbaseitemcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_knowbaseitemcategories"); $LAST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories"); // LOCATIONS $added = 0; $FIRST["locations"] = getMaxItem("glpi_locations")+1; $loc = new Location(); for ($i=0 ; $i<pow($MAX['locations'],1/5)&&$added<$MAX['locations'] ; $i++) { $added++; $newID = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "location' $i", 'comment' => "comment 'location $i", 'building' => "building $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) { $added++; $newID2 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "s-location '$j", 'comment' => "comment s-location '$j", 'building' => "building $i", 'room' => "stage '$j", 'locations_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $k++) { $added++; $newID3 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ss-location '$k", 'comment' => "comment ss-location' $k", 'building' => "building $i", 'room' => "part' $k", 'locations_id' => $newID2))); for ($l=0 ; $l<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $l++) { $added++; $newID4 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "sss-location' $l", 'comment' => "comment sss-location' $l", 'building' => "building $i", 'room' => "room' $l", 'locations_id' => $newID3))); for ($m=0 ; $m<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $m++) { $added++; $newID5 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ssss-location' $m", 'comment' => "comment ssss-location' $m", 'building' => "building $i", 'room' => "room' $l-$m", 'locations_id' => $newID4))); } } } } } $query = "OPTIMIZE TABLE `glpi_locations`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_locations"); $LAST["locations"]=getMaxItem("glpi_locations"); // Task categories $added = 0; $FIRST["taskcategory"] = getMaxItem("glpi_taskcategories")+1; $tc = new TaskCategory(); for ($i=0 ; $i<pow($MAX['taskcategory'],1/5)&&$added<$MAX['taskcategory'] ; $i++) { $added++; $newID = $tc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ent$ID_entity taskcategory' $i", 'comment' => "comment ent$ID_entity taskcategory' $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) { $newID2 = $tc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ent$ID_entity taskcategory' $i", 'comment' => "comment ent$ID_entity taskcategory' $i", 'taskcategories_id' => $newID))); $added++; } } $query = "OPTIMIZE TABLE `glpi_taskcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_taskcategories"); $LAST["taskcategory"] = getMaxItem("glpi_taskcategories"); $ic = new ItilCategory(); // Specific ticket categories $newID = $ic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "category for entity' $ID_entity", 'comment' => "comment category for entity' $ID_entity", 'users_id' => mt_rand($FIRST['users_sadmin'],$LAST['users_admin']), 'groups_id' => mt_rand($FIRST['techgroups'],$LAST['techgroups']), 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1))); for ($i=0 ; $i<max(1,pow($MAX['tracking_category'],1/3)) ; $i++) { $ic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "scategory for entity' $ID_entity", 'comment' => "comment scategory for entity' $ID_entity", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']), 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1, 'itilcategories_id' => $newID))); } regenerateTreeCompleteName("glpi_itilcategories"); $FIRST["solutiontypes"] = getMaxItem("glpi_solutiontypes")+1; $items = array("d'après KB"); $st = new SolutionType(); for ($i=0 ; $i<$MAX['solutiontypes'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de solution ' $i"; } $st->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val", 'entities_id' => $ID_entity, 'is_recursive' => 1))); } $LAST["solutiontypes"] = getMaxItem("glpi_solutiontypes"); $FIRST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates")+1; $nb_items = mt_rand(0,$MAX['solutiontemplates']); $st = new SolutionTemplate(); for ($i=0 ; $i<$nb_items ; $i++) { $st-> add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "solution' $i-$ID_entity", 'content' => "content solution' $i-$ID_entity", 'solutiontypes_id' => mt_rand(0,$MAX['solutiontypes']), 'comment' => "comment solution' $i-$ID_entity"))); } $LAST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates"); // Add Specific questions $k = 0; $FIRST["kbitems"] = getMaxItem("glpi_knowbaseitems")+1; $ki = new KnowbaseItem(); $eki = new Entity_KnowbaseItem(); for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) { $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT); for ($j=0 ; $j<$nb ; $j++) { $k++; $newID = $ki->add(toolbox::addslashes_deep( array('knowbaseitemcategories_id' => $i, 'name' => "Entity' $ID_entity Question $k", 'answer' => "Answer' $k".Toolbox::getRandomString(50), 'is_faq' => mt_rand(0,1), 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin'])))); $eki->add(array('entities_id' => $ID_entity, 'knowbaseitems_id' => $newID, 'is_recursive' => 0)); } } // Add global questions for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) { $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT); for ($j=0 ; $j<$nb ; $j++) { $k++; $newID = $ki->add(toolbox::addslashes_deep( array('knowbaseitemcategories_id' => $i, 'name' => "Entity' $ID_entity Recursive Question $k", 'answer' => "Answer' $k".Toolbox::getRandomString(50), 'is_faq' => mt_rand(0,1), 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin'])))); $eki->add(array('entities_id' => $ID_entity, 'knowbaseitems_id' => $newID, 'is_recursive' => 1)); } } $LAST["kbitems"] = getMaxItem("glpi_knowbaseitems"); // Ajout documents specific $FIRST["document"] = getMaxItem("glpi_documents")+1; $doc = new Document(); for ($i=0 ; $i<$MAX['document'] ; $i++) { $link = ""; if (mt_rand(0,100)<50) { $link = "http://linktodoc/doc$i"; } $docID = $doc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "document' $i-$ID_entity", 'documentcategories_id' => mt_rand(1,$MAX['rubdocs']), 'comment' => "commen't $i", 'link' => $link, 'notepad' => "notes document' $i"))); $DOCUMENTS[$docID] = $ID_entity."-0"; } // Global ones for ($i=0 ; $i<$MAX['document']/2 ; $i++) { $link = ""; if (mt_rand(0,100)<50) { $link = "http://linktodoc/doc$i"; } $docID = $doc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive document' $i-$ID_entity", 'documentcategories_id' => mt_rand(1,$MAX['rubdocs']), 'comment' => "comment' $i", 'link' => $link, 'notepad' => "notes document' $i"))); $DOCUMENTS[$docID] = $ID_entity."-1"; } $LAST["document"] = getMaxItem("glpi_documents"); // Ajout budgets specific $FIRST["budget"] = getMaxItem("glpi_budgets")+1; $b = new Budget(); for ($i=0 ; $i<$MAX['budget'] ; $i++) { $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans $b->add(toolbox::addslashes_deep( array('name' => "budget' $i-$ID_entity", 'entities_id' => $ID_entity, 'is_recusive' => 0, 'comment' => "comment' $i-$ID_entity", 'begin_date' => date("Y-m-d",intval($date1)), 'end_date' => date("Y-m-d",intval($date2))))); } $LAST["budget"] = getMaxItem("glpi_budgets"); // GLobal ones for ($i=0 ; $i<$MAX['document']/2 ; $i++) { $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans $b->add(toolbox::addslashes_deep( array('name' => "Recursive budget' $i-$ID_entity", 'entities_id' => $ID_entity, 'is_recusive' => 1, 'comment' => "comment' $i-$ID_entity", 'begin_date' => date("Y-m-d",intval($date1)), 'end_date' => date("Y-m-d",intval($date2))))); } $LAST["document"] = getMaxItem("glpi_documents"); // glpi_suppliers $items = array("DELL", "IBM", "ACER", "Microsoft", "Epson", "Xerox", "Hewlett Packard", "Nikon", "Targus", "LG", "Samsung", "Lexmark"); $FIRST["enterprises"] = getMaxItem("glpi_suppliers")+1; $ent = new Supplier(); // Global ones for ($i=0 ; $i<$MAX['enterprises']/2 ; $i++) { if (isset($items[$i])) { $val = "Recursive ".$items[$i]; } else { $val = "Recursive enterprise_".$i."_ID_entity"; } $entID = $ent->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive' $val-$ID_entity", 'suppliertypes_id' => mt_rand(1,$MAX['enttype']), 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'website' => "http://www.$val.com/", 'fax' => "fax $i", 'email' => "info@ent$i.com", 'notepad' => "notes enterprises' $i"))); addDocuments('Supplier', $entID); } // Specific ones for ($i=0 ; $i<$MAX['enterprises'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "enterprise_".$i."_ID_entity"; } $entID = $ent->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "'$val-$ID_entity", 'suppliertypes_id' => mt_rand(1,$MAX['enttype']), 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'website' => "http://www.$val.com/", 'fax' => "fax $i", 'email' => "info@ent$i.com", 'notepad' => "notes supplier' $i", 'comment' => "comment supplier' $i"))); addDocuments('Supplier', $entID); } $LAST["enterprises"] = getMaxItem("glpi_suppliers"); // Ajout contracts $FIRST["contract"] = getMaxItem("glpi_contracts")+1; $c = new Contract(); $cs = new Contract_Supplier(); $cc = new ContractCost(); // Specific for ($i=0 ; $i<$MAX['contract'] ; $i++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $contractID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "contract' $i-$ID_entity", 'num' => "num' $i", 'contracttypes_id' => mt_rand(1,$MAX['contract_type']), 'begin_date' => $date, 'duration' => mt_rand(1,36), 'notice' => mt_rand(1,3), 'periodicity' => mt_rand(1,36), 'billing' => mt_rand(1,36), 'comment' => "comment' $i", 'accounting_number' => "compta num' $i", 'renewal' => 1))); addDocuments('Contract', $contractID); // Add an enterprise $cs->add(array('contracts_id' => $contractID, 'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"]))); // Add a cost $cc->add(toolbox::addslashes_deep( array('contracts_id' => $contractID, 'cost' => mt_rand(100,10000), 'name' => "Initial 'cost", 'begin_date' => $date, 'budgets_id' => mt_rand($FIRST['budget'], $LAST['budget'])))); } for ($i=0 ; $i<$MAX['contract']/2 ; $i++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $contractID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive contract' $i-$ID_entity", 'num' => "num' $i", 'cost' => mt_rand(100,10000), 'contracttypes_id' => mt_rand(1,$MAX['contract_type']), 'begin_date' => $date, 'duration' => mt_rand(1,36), 'notice' => mt_rand(1,3), 'periodicity' => mt_rand(1,36), 'billing' => mt_rand(1,36), 'comment' => "comment' $i", 'accounting_number' => "compta num' $i", 'renewal' => 1))); addDocuments('Contract', $contractID); // Add an enterprise $cs->add(array('contracts_id' => $contractID, 'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"]))); } $LAST["contract"] = getMaxItem("glpi_contracts"); // Ajout contacts $prenoms = array("Jean", "John", "Louis", "Pierre", "Auguste", "Albert", "Julien", "Guillaume", "Bruno", "Maurice", "Francois", "Laurent", "Richard", "Henri", "Clement", "d'avy"); $noms = array("Dupont", "Smith", "Durand", "Martin", "Dubois", "Dufour", "Dupin", "Duval", "Petit", "Grange", "Bernard", "Bonnet", "Richard", "Leroy", "Dumont", "Fontaine", "d'orleans"); $FIRST["contacts"] = getMaxItem("glpi_contacts")+1; $c = new Contact(); $cs = new Contact_Supplier(); for ($i=0 ; $i<$MAX['contacts'] ; $i++) { if (isset($noms[$i])) { $val = $noms[$i]; } else { $val = "name $i"; } if (isset($prenoms[$i])) { $val2 = $prenoms[$i]; } else { $val2 = "firstname $i"; } $contactID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "$val-$ID_entity", 'firstname' => $val2, 'contacttypes_id' => mt_rand(1,$MAX['contact_type']), 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'phone' => "phone $i", 'phone2' => "phone2 $i", 'mobile' => "mobile $i", 'fax' => "fax $i", 'email' => "email $i", 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'comment' => "Comment' $i"))); // Link with enterprise $cs->add(array('contacts_id' => $contactID, 'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises']))); } for ($i=0 ; $i<$MAX['contacts']/2 ; $i++) { if (isset($items[$i])) { $val = "Recursive ".$items[$i]; } else { $val = "Recursive contact $i"; } $contactID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "$val'-$ID_entity", 'contacttypes_id' => mt_rand(1,$MAX['contact_type']), 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'phone' => "phone $i", 'phone2' => "phone2 $i", 'mobile' => "mobile $i", 'fax' => "fax $i", 'email' => "email $i", 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'comment' => "Comment' $i"))); // Link with enterprise $cs->add(array('contacts_id' => $contactID, 'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises']))); } $LAST["contacts"] = getMaxItem("glpi_contacts"); // TYPE DE CONSOMMABLES $FIRST["type_of_consumables"] = getMaxItem("glpi_consumableitems")+1; $ci = new Consumableitem(); for ($i=0 ; $i<$MAX['type_of_consumables'] ; $i++) { $consID = $ci->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => mt_rand(0,1), 'name' => "consumable type' $i", 'ref' => "ref d' $i", 'locations_id' => mt_rand($FIRST["locations"], $LAST['locations']), 'consumableitemtypes_id' => mt_rand(0,$MAX['consumable_type']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'users_id_tech' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id_tech' => mt_rand($FIRST["groups"], $LAST["groups"]), 'comment' => "comment' $i", 'notepad' => "notes consumableitem' $i", 'alarm_threshold' => mt_rand(0,10)))); addDocuments('ConsumableItem', $consID); // AJOUT INFOCOMS addInfocoms('ConsumableItem', $consID, $ID_entity); // Ajout consommable en stock $c = new Consumable(); for ($j=0 ; $j<mt_rand(0,$MAX['consumables_stock']) ; $j++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'consumableitems_id' => $consID, 'date_in' => $date)); // AJOUT INFOCOMS addInfocoms('Consumable', $ID, $ID_entity); } // Ajout consommable donne for ($j=0 ; $j<mt_rand(0,$MAX['consumables_given']) ; $j++) { $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'consumableitems_id' => $consID, 'date_in' => $date, 'date_out' => date("Y-m-d"))); // AJOUT INFOCOMS addInfocoms('Consumable', $ID, $ID_entity); } } $LAST["type_of_consumables"] = getMaxItem("glpi_consumableitems"); // TYPE DE CARTOUCHES $FIRST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems")+1; $ct = new CartridgeItem(); for ($i=0 ; $i<$MAX['type_of_cartridges'] ; $i++) { $cartID = $ct->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => mt_rand(0,1), 'name' => "cartridge ' type $i", 'ref' => "ref '$i", 'locations_id' => mt_rand($FIRST["locations"], $LAST['locations']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'users_id_tech' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id_tech' => mt_rand($FIRST["groups"], $LAST["groups"]), 'comment' => "comment '$i", 'notepad' => "notes cartridgeitem '$i", 'alarm_threshold' => mt_rand(0,10)))); addDocuments('CartridgeItem', $cartID); // AJOUT INFOCOMS addInfocoms('CartridgeItem', $cartID, $ID_entity); $c = new Cartridge(); $cipm = new CartridgeItem_PrinterModel(); // Ajout cartouche en stock for ($j=0 ; $j<mt_rand(0,$MAX['cartridges_stock']) ; $j++) { $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $cartID, 'date_in' => $date)); // AJOUT INFOCOMS addInfocoms('Cartridge', $ID, $ID_entity); } // Assoc printer type to cartridge type $cipm->add(array('cartridgeitems_id' => $cartID, 'printermodels_id' => mt_rand(1,$MAX['type_printers']), )); } $LAST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems"); // Networking $NET_LOC = array(); $FIRST["networking"] = getMaxItem("glpi_networkequipments")+1; $FIRST["printers"] = getMaxItem("glpi_printers")+1; $ne = new NetworkEquipment(); $p = new Printer(); $np = new Netpoint(); $c = new Cartridge(); foreach ($DB->request('glpi_locations') as $data) { $i = $data["id"]; $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $infoIP = getNextIP(); $domainID = mt_rand($FIRST['domain'],$LAST['domain']); $networkID = mt_rand(1,$MAX['network']); // insert networking $netwID = $ne->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "networking '$i-$ID_entity", 'ram' => mt_rand(32,256), 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact '$i", 'contact_num' => "num '$i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment '$i", 'locations_id' => $i, 'domains_id' => $domainID, 'networks_id' => $networkID, 'networkequipmenttypes_id' => mt_rand(1,$MAX['type_networking']), 'networkequipmentmodels_id' => mt_rand(1,$MAX['model_networking']), 'networkequipmentfirmwares_id' => mt_rand(1,$MAX['firmware']), 'manufacturers_id' => mt_rand(1,$MAX['enterprises']), 'mac' => getNextMAC(), 'ip' => $infoIP["ip"], 'notepad' => "notes networking '$i", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); $NET_LOC[$data['id']] = $netwID; addDocuments('NetworkEquipment', $netwID); addContracts('NetworkEquipment', $netwID); // AJOUT INFOCOMS addInfocoms('NetworkEquipment', $netwID, $ID_entity); // Link with father addNetworkEthernetPort('NetworkEquipment', $netwID, $ID_entity, $i); // Ajout imprimantes reseaux : 1 par loc + connexion d un matos reseau + ajout de cartouches // Add trackings addTracking('NetworkEquipment', $netwID, $ID_entity); $typeID = mt_rand(1,$MAX['type_printers']); $modelID = mt_rand(1,$MAX['model_printers']); $recur = mt_rand(0,1); $printID = $p->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recur, 'name' => "printer of loc '$i", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact '$i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'have_serial' => mt_rand(0,1), 'have_parallel' => mt_rand(0,1), 'have_usb' => mt_rand(0,1), 'have_wifi' => mt_rand(0,1), 'have_ethernet' => mt_rand(0,1), 'comment' => "comment' $i", 'memory_size' => mt_rand(0,128), 'locations_id' => $i, 'domains_id' => $domainID, 'networks_id' => $networkID, 'printertypes_id' => $typeID, 'printermodels_id' => $modelID, 'manufacturers_id' => mt_rand(1,$MAX['enterprises']), 'is_global' => 1, 'notepad' => "notes printers '$i", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Printer', $printID); addContracts('Printer', $printID); // Add trackings addTracking('Printer', $printID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Printer', $printID, $ID_entity, $recur); // Add Cartouches // Get compatible cartridge $query = "SELECT `cartridgeitems_id` FROM `glpi_cartridgeitems_printermodels` WHERE `printermodels_id` = '$typeID'"; $result2 = $DB->query($query) or die("PB REQUETE ".$query); if ($DB->numrows($result2)>0) { $ctypeID = $DB->result($result2,0,0) or die (" PB RESULT ".$query); $printed = 0; $oldnb = mt_rand(1,$MAX['cartridges_by_printer']); $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = time(); $inter = abs(round(($date2-$date1)/$oldnb)); // Add old cartridges for ($j=0 ; $j<$oldnb ; $j++) { $printed += mt_rand(0,5000); $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date1+$j*$inter), 'date_out' => date("Y-m-d",$date1+($j+1)*$inter), 'pages' => $printed)); } // Add current cartridges $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => $date, 'date_use' => date("Y-m-d",$date2))); } $iface = mt_rand(1,$MAX['iface']); // Add networking ports addNetworkEthernetPort('Printer', $printID, $ID_entity, $i); } unset($NET_LOC); $LAST["networking"] = getMaxItem("glpi_networkequipments"); //////////// INVENTORY // glpi_computers $FIRST["computers"] = getMaxItem("glpi_computers")+1; $FIRST["monitors"] = getMaxItem("glpi_monitors")+1; $FIRST["phones"] = getMaxItem("glpi_phones")+1; $FIRST["peripherals"] = getMaxItem("glpi_peripherals")+1; $c = new Computer(); $mon = new Monitor(); $cdevmb = new Item_DeviceMotherBoard(); $cdevproc = new Item_DeviceProcessor(); $cdevmem = new Item_DeviceMemory(); $cdevhd = new Item_DeviceHardDrive(); $cdevnc = new Item_DeviceNetworkCard(); $cdevdr = new Item_DeviceDrive(); $cdevcon = new Item_DeviceControl(); $cdevgc = new Item_DeviceGraphicCard(); $cdevsc = new Item_DeviceSoundCard(); $cdevpci = new Item_DevicePci(); $cdevcase = new Item_DeviceCase(); $cdevps = new Item_DevicePowerSupply(); $cdisk = new ComputerDisk(); $np = new Netpoint(); $ci = new Computer_Item(); $phone = new Phone(); $print = new Printer(); $periph = new Peripheral(); $cart = new Cartridge(); for ($i=0 ; $i<$MAX['computers'] ; $i++) { $loc = mt_rand($FIRST["locations"],$LAST['locations']); $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $userID = mt_rand($FIRST['users_normal'],$LAST['users_postonly']); $groupID = mt_rand($FIRST["groups"],$LAST["groups"]); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $domainID = mt_rand($FIRST['domain'],$LAST['domain']); $networkID = mt_rand(1,$MAX['network']); $compID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "computer ' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'operatingsystems_id' => mt_rand(1,$MAX['os']), 'operatingsystemversions_id' => mt_rand(1,$MAX['os_version']), 'operatingsystemservicepacks_id' => mt_rand(1,$MAX['os_sp']), 'os_license_number' => "os sn $i", 'os_licenseid' => "os id $i", 'autoupdatesystems_id' => mt_rand(1,$MAX['os_sp']), 'locations_id' => $loc, 'domains_id' => $domainID, 'networks_id' => $networkID, 'computertypes_id' => mt_rand(1,$MAX['type_computers']), 'computermodels_id' => mt_rand(1,$MAX['model']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'is_global' => 1, 'notepad' => "notes computer '$i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0), 'uuid' => Toolbox::getRandomString(30) ))); addDocuments('Computer', $compID); addContracts('Computer', $compID); $NET_PORT['Computer'][$compID] = 0; // Add trackings addTracking('Computer', $compID, $ID_entity); // Add reservation addReservation('Computer', $compID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Computer', $compID, $ID_entity); // ADD DEVICE $cdevmb->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $max = mt_rand(1,4); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevproc->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $max = mt_rand(1,4); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevmem->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $max = mt_rand(1,2); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevhd->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $cdevnc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15), 'mac' => getNextMAC())); $cdevdr->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevcon->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevgc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevsc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $max = mt_rand(1,4); for($nb = 0; $nb<$max; $nb++) { $cdevpci->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); } $cdevcase->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial'=> Toolbox::getRandomString(15))); $max = mt_rand(1,2); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevps->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } // insert disk $nb_disk = mt_rand(1,$MAX_DISK); for ($j=1 ; $j<=$nb_disk ; $j++) { $totalsize = mt_rand(10000,1000000); $freesize = mt_rand(0,$totalsize); $cdisk->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'computers_id' => $compID, 'name' => "disk '$j", 'device' => "/dev/disk$j", 'mountpoint' => "/mnt/disk$j", 'filesystems_id' => mt_rand(1,10), 'totalsize' => $totalsize, 'freesize' => $freesize))); } // Add networking ports addNetworkEthernetPort('Computer', $compID, $ID_entity, $loc); // Ajout d'un ecran sur l'ordi $monID = $mon->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "monitor' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'size' => mt_rand(14,22), 'have_micro' => mt_rand(0,1), 'have_speaker' => mt_rand(0,1), 'have_subd' => mt_rand(0,1), 'have_bnc' => mt_rand(0,1), 'have_dvi' => mt_rand(0,1), 'have_pivot' => mt_rand(0,1), 'have_hdmi' => mt_rand(0,1), 'have_displayport' => mt_rand(0,1), 'locations_id' => $loc, 'monitortypes_id' => mt_rand(1,$MAX['type_monitors']), 'monitormodels_id' => mt_rand(1,$MAX['model_monitors']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes monitor' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Monitor', $monID); addContracts('Monitor', $monID); // Add trackings addTracking('Monitor', $monID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Monitor', $monID, $ID_entity); $ci->add(array('itemtype' => 'Monitor', 'items_id' => $monID, 'computers_id' => $compID, )); // Ajout d'un telephhone avec l'ordi $telID = $phone->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "phone' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'firmware' => Toolbox::getRandomString(10), 'brand' => "brand' $i", 'phonepowersupplies_id' => mt_rand(0,$MAX['phone_power']), 'number_line' => Toolbox::getRandomString(10), 'have_headset' => mt_rand(0,1), 'have_hp' => mt_rand(0,1), 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_phones']), 'phonemodels_id' => mt_rand(1,$MAX['model_phones']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes phone' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Phone', $telID); addContracts('Phone', $telID); // Add trackings addTracking('Phone', $telID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Phone', $telID, $ID_entity); $ci->add(array('itemtype' => 'Phone', 'items_id' => $telID, 'computers_id' => $compID)); // Ajout des periphs externes en connection directe while (mt_rand(0,100)<$percent['peripherals']) { $periphID = $periph->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "periph of comp' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'brand' => "brand' $i", 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_peripherals']), 'phonemodels_id' => mt_rand(1,$MAX['model_peripherals']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes peripheral' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Peripheral', $periphID); addContracts('Peripheral', $periphID); // Add trackings addTracking('Peripheral', $periphID, $ID_entity); // Add connection $ci->add(array('itemtype' => 'Peripheral', 'items_id' => $periphID, 'computers_id' => $compID)); } // Ajout d'une imprimante connection directe pour X% des computers + ajout de cartouches if (mt_rand(0,100)<=$percent['printer']) { // Add printer $typeID = mt_rand(1,$MAX['type_printers']); $modelID = mt_rand(1,$MAX['model_printers']); $printID = $p->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "printer of comp' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'have_serial' => mt_rand(0,1), 'have_parallel' => mt_rand(0,1), 'have_usb' => mt_rand(0,1), 'have_wifi' => mt_rand(0,1), 'have_ethernet' => mt_rand(0,1), 'comment' => "comment' $i", 'memory_size' => mt_rand(0,128), 'locations_id' => $loc, 'domains_id' => $domainID, 'networks_id' => $networkID, 'printertypes_id' => $typeID, 'printermodels_id' => $modelID, 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes printers '$i", 'users_id' => mt_rand($FIRST['users_postonly'], $LAST['users_postonly']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Printer', $printID); addContracts('Printer', $printID); // Add trackings addTracking('Printer', $printID, $ID_entity); // Add connection $ci->add(array('itemtype' => 'Printer', 'items_id' => $printID, 'computers_id' => $compID)); // AJOUT INFOCOMS addInfocoms('Printer', $printID, $ID_entity); // Add Cartouches // Get compatible cartridge $query = "SELECT `cartridgeitems_id` FROM `glpi_cartridgeitems_printermodels` WHERE `printermodels_id` = '$typeID'"; $result = $DB->query($query) or die("PB REQUETE ".$query); if ($DB->numrows($result)>0) { $ctypeID = $DB->result($result,0,0) or die (" PB RESULT ".$query); $printed = 0; $oldnb = mt_rand(1,$MAX['cartridges_by_printer']); $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = time(); $inter = round(($date2-$date1)/$oldnb); // Add old cartridges for ($j=0 ; $j<$oldnb ; $j++) { $printed += mt_rand(0,5000); $cart->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date1+$j*$inter), 'date_out' => date("Y-m-d",$date1+($j+1)*$inter), 'pages' => $printed)); } // Add current cartridges $cart->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date2))); } } } $LAST["computers"] = getMaxItem("glpi_computers"); $LAST["monitors"] = getMaxItem("glpi_monitors"); $LAST["phones"] = getMaxItem("glpi_phones"); // Add global peripherals $periph = new Peripheral(); $ci = new Computer_Item(); for ($i=0 ; $i<$MAX['global_peripherals'] ; $i++) { $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $periphID = $periph->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "periph '$i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'brand' => "brand' $i", 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_peripherals']), 'phonemodels_id' => mt_rand(1,$MAX['model_peripherals']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'is_global' => 1, 'notepad' => "notes peripheral' $i", 'users_id' => mt_rand($FIRST['users_normal'], $LAST['users_normal']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Peripheral', $periphID); addContracts('Peripheral', $periphID); // Add trackings addTracking('Peripheral', $periphID, $ID_entity); // Add reservation addReservation('Peripheral', $periphID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Peripheral', $periphID, $ID_entity); // Add connections $val = mt_rand(1,$MAX['connect_for_peripherals']); for ($j=1 ; $j<$val ; $j++) { $ci->add(array('itemtype' => 'Peripheral', 'items_id' => $periphID, 'computers_id' => mt_rand($FIRST["computers"],$LAST['computers']))); } } $LAST["peripherals"] = getMaxItem("glpi_peripherals"); $FIRST["software"] = getMaxItem("glpi_softwares")+1; // Ajout logiciels + licences associees a divers PCs $items = array(array("Open'Office", "1.1.4", "2.0", "2.0.1"), array("Microsoft Office", "95", "97", "XP", "2000", "2003", "2007"), array("Acrobat Reader", "6.0", "7.0", "7.04"), array("Gimp", "2.0", "2.2"), array("InkScape", "0.4")); $soft = new Software(); $softvers = new SoftwareVersion(); $softlic = new SoftwareLicense(); $csv = new Computer_SoftwareVersion(); $csl = new Computer_SoftwareLicense(); for ($i=0 ; $i<$MAX['software'] ; $i++) { if (isset($items[$i])) { $name = $items[$i][0]; } else { $name = "software '$i"; } $loc = mt_rand(1,$MAX['locations']); $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $recursive = mt_rand(0,1); $softID = $soft->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'name' => $name, 'comment' => "comment '$i", 'locations_id' => $loc, 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes software '$i", 'users_id' => mt_rand($FIRST['users_admin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'is_helpdesk_visible' => 1, 'softwarecategories_id' => mt_rand(1,$MAX['softwarecategory']) ))); addDocuments('Software', $softID); addContracts('Software', $softID); // Add trackings addTracking('Software', $softID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Software', $softID, $ID_entity); // Add versions $FIRST["version"] = getMaxItem("glpi_softwareversions")+1; if (isset($items[$i])) { $val2 = count($items[$i]); } else { $val2 = mt_rand(1,$MAX['softwareversions']+1); } for ($j=1 ; $j<=$val2 ; $j++) { if (isset($items[$i])) { $version = $items[$i][mt_rand(1,count($items[$i])-1)]; } else { $version = "$j.0"; } $os = mt_rand(1,$MAX['os']); $versID = $softvers->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'softwares_id' => $softID, 'name' => $version, 'comment' => "comment '$version", 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0), 'operatingsystems_id' => $os))); $val3 = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall'])); $comp_id = mt_rand($FIRST["computers"], $LAST['computers']); for ($k=0 ; $k<$val3 ; $k++) { $comp_id++; if ($comp_id>$LAST["computers"]) { $comp_id = $FIRST["computers"]; } $csv->add(array('computers_id' => $comp_id, 'softwareversions_id' => $versID)); } } $LAST["version"] = getMaxItem("glpi_softwareversions"); // Add licenses $val2 = mt_rand(1,$MAX['softwarelicenses']); for ($j=0 ; $j<$val2 ; $j++) { $softwareversions_id_buy = mt_rand($FIRST["version"],$LAST["version"]); $softwareversions_id_use = mt_rand($softwareversions_id_buy,$LAST["version"]); $nbused = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall'])); $licID = $softlic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'softwares_id' => $softID, 'number' => $nbused, 'softwarelicensetypes_id' => mt_rand(1,$MAX['licensetype']), 'name' => "license '$j", 'serial' => "serial $j", 'otherserial' => "otherserial $j", 'comment' => "comment license '$j", 'softwareversions_id_buy' => $softwareversions_id_buy, 'softwareversions_id_use' => $softwareversions_id_use))); $comp_id = mt_rand($FIRST["computers"], $LAST['computers']); for ($k=0 ; $k<$nbused ; $k++) { $comp_id++; if ($comp_id>$LAST["computers"]) { $comp_id = $FIRST["computers"]; } $csl->add(array('computers_id' => $comp_id, 'softwarelicenses_id' => $licID)); } } } $LAST["software"] = getMaxItem("glpi_softwares"); }
/** * * Import printers 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 printer will be created * @param $dohistory record in history link between printer and computer */ static function importPrinter($cfg_ocs, $computers_id, $ocsservers_id, $ocsid, $entity, $dohistory) { global $PluginOcsinventoryngDBocs, $DB; self::checkOCSconnection($ocsservers_id); if ($cfg_ocs["import_printer"]) { $already_processed = array(); $conn = new Computer_Item(); $query = "SELECT*\n FROM `printers`\n WHERE `HARDWARE_ID` = '{$ocsid}'"; $result = $PluginOcsinventoryngDBocs->query($query); $p = new Printer(); if ($PluginOcsinventoryngDBocs->numrows($result) > 0) { while ($line = $PluginOcsinventoryngDBocs->fetch_array($result)) { $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line)); $print = array(); // TO TEST : PARSE NAME to have real name. $print['name'] = self::encodeOcsDataInutf8($cfg_ocs["ocs_db_utf8"], $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 = Toolbox::addslashes_deep($rulecollection->processAllRules(Toolbox::stripslashes_deep($params), array(), array())); if (!isset($res_rule["_ignore_import"]) || !$res_rule["_ignore_import"]) { foreach ($res_rule as $key => $value) { if ($value != '' && $value[0] != '_') { $print[$key] = $value; } } if (isset($res_rule['is_global'])) { if (!$res_rule['is_global']) { $management_process = 2; } else { $management_process = 1; } } //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`='Printer'\n AND `p`.`name`='" . $print["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 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"); $already_processed[] = $id_printer; } else { $input = $print; if ($cfg_ocs["states_id_default"] > 0) { $input["states_id"] = $cfg_ocs["states_id_default"]; } $input["entities_id"] = $entity; $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; $input['is_dynamic'] = 1; $id_printer = $p->add($input); } } if ($id_printer) { $already_processed[] = $id_printer; $conn = new Computer_Item(); $connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Printer', 'items_id' => $id_printer, '_no_history' => !$dohistory, 'is_dynamic' => 1)); //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 { $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`='Printer'\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); } } }
/** * @test */ public function PrinterToInventoryWithoutIP() { self::restore_database(); $printer = new Printer(); $networkport = new NetworkPort(); $networkName = new NetworkName(); $pfPrinter = new PluginFusioninventoryPrinter(); $pfTask = new PluginFusioninventoryTask(); $pfTaskjob = new PluginFusioninventoryTaskjob(); $computer = new Computer(); $pfAgent = new PluginFusioninventoryAgent(); $communication = new PluginFusioninventoryCommunication(); // Create computers + agents $input = array('entities_id' => 0, 'name' => 'computer1'); $computers_id = $computer->add($input); $input = array('entities_id' => 0, 'name' => 'computer1', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer1', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id); $pfAgent->add($input); // Create printer $input = array('name' => 'printer 001', 'entities_id' => 0); $printers_id = $printer->add($input); // Add port $networkports_id = $networkport->add(array('itemtype' => 'Printer', 'instantiation_type' => 'NetworkPortEthernet', 'items_id' => $printers_id, 'entities_id' => 0)); $networknames_id = $networkName->add(array('entities_id' => 0, 'itemtype' => 'NetworkPort', 'items_id' => $networkports_id)); $input = array('printers_id' => 1, 'plugin_fusioninventory_configsecurities_id' => 2); $pfPrinter->add($input); // Add task // create task $input = array('entities_id' => 0, 'name' => 'network inventory', 'is_active' => 1); $tasks_id = $pfTask->add($input); // create taskjob $input = array('plugin_fusioninventory_tasks_id' => $tasks_id, 'entities_id' => 0, 'name' => 'inventory', 'method' => 'networkinventory', 'targets' => '[{"Printer":"' . $printers_id . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"1"}]'); $pfTaskjob->add($input); PluginFusioninventoryTask::cronTaskscheduler(); $data = $pfTask->getJoblogs(array(1)); // Task is prepared // Agent will get data $communication->getTaskAgent(1); $message = $communication->getMessage(); $json = json_encode($message); $array = json_decode($json, TRUE); $ref = array(); $this->assertEquals($ref, $array, 'XML of SNMP inventory task'); }
/** * @test */ public function NewPrinterFromNetdiscovery() { global $DB; $DB->connect(); $pfCNetworkDiscovery = new PluginFusioninventoryCommunicationNetworkDiscovery(); $GLPIlog = new GLPIlogs(); $networkName = new NetworkName(); $iPAddress = new IPAddress(); $_SESSION['SOURCE_XMLDEVICE'] = array('AUTHSNMP' => '1', 'DESCRIPTION' => 'Photosmart D7200 series', 'ENTITY' => '0', 'FIRMWARE' => '', 'IP' => '192.168.20.100', 'MAC' => '00:21:5a:0b:bb:c4', 'MANUFACTURER' => 'Hewlett-Packard', 'MODEL' => '', 'MODELSNMP' => 'Printer0093', 'NETBIOSNAME' => 'HP00215A0BBBC4', 'SERIAL' => 'MY89AQG0V9050N', 'SNMPHOSTNAME' => 'HP0BBBC4', 'TYPE' => 'PRINTER'); $printer = new Printer(); $printers_id = $printer->add(array('serial' => 'MY89AQG0V9050N', 'entities_id' => 0)); $printer->getFromDB($printers_id); $pfCNetworkDiscovery->importDevice($printer); $GLPIlog->testSQLlogs(); $GLPIlog->testPHPlogs(); $printer->getFromDB($printers_id); $this->assertEquals('HP0BBBC4', $printer->fields['name'], 'Name must be updated'); $a_printerextends = getAllDatasFromTable('glpi_plugin_fusioninventory_printers', "`printers_id`='" . $printers_id . "'"); $this->assertEquals('1', count($a_printerextends), 'May have one printer extend line for this printer'); $a_printerextend = current($a_printerextends); $this->assertEquals('1', $a_printerextend['plugin_fusioninventory_configsecurities_id'], 'SNMPauth may be with id 1'); $this->assertEquals('Photosmart D7200 series', $a_printerextend['sysdescr'], 'Sysdescr not updated correctly'); // Check mac $networkPort = new NetworkPort(); $a_ports = $networkPort->find("`itemtype`='Printer' AND `items_id`='" . $printers_id . "'"); $this->assertEquals('1', count($a_ports), 'May have one network port'); $a_port = current($a_ports); $this->assertEquals('00:21:5a:0b:bb:c4', $a_port['mac'], 'Mac address'); // check ip $a_networknames = $networkName->find("`itemtype`='NetworkPort'\n AND `items_id`='" . $a_port['id'] . "'"); $this->assertEquals('1', count($a_networknames), 'May have one networkname'); $a_networkname = current($a_networknames); $a_ipaddresses = $iPAddress->find("`itemtype`='NetworkName'\n AND `items_id`='" . $a_networkname['id'] . "'"); $this->assertEquals('1', count($a_ipaddresses), 'May have one IP address'); $a_ipaddress = current($a_ipaddresses); $this->assertEquals('192.168.20.100', $a_ipaddress['name'], 'IP address'); }
/** * Function to import discovered device * * @param $items_id id of the device to import * * @return nothing * **/ function import($items_id, $Import = 0, $NoImport = 0) { global $DB; $NetworkPort = new NetworkPort(); $a_NetworkPorts = $NetworkPort->find("`items_id` = '" . $items_id . "'\n AND `itemtype` = 'PluginFusioninventoryUnmanaged'"); $this->getFromDB($items_id); $this->fields = Toolbox::addslashes_deep($this->fields); $data = array(); switch ($this->fields['item_type']) { case 'Printer': $Printer = new Printer(); $data["entities_id"] = $this->fields["entities_id"]; if (!empty($this->fields["name"])) { $data["name"] = $this->fields["name"]; } $data["locations_id"] = $this->fields["locations_id"]; $data["serial"] = $this->fields["serial"]; $data["otherserial"] = $this->fields["otherserial"]; $data["contact"] = $this->fields["contact"]; $data["domain"] = $this->fields["domain"]; $data["comment"] = $this->fields["comment"]; $data["is_dynamic"] = 1; $printer_id = $Printer->add($data); foreach ($a_NetworkPorts as $data_Port) { $data_Port['items_id'] = $printer_id; $data_Port['itemtype'] = $Printer->getType(); $NetworkPort->update($data_Port); } // Import SNMP $pfPrinter = new PluginFusioninventoryPrinter(); $_SESSION['glpi_plugins_fusinvsnmp_table'] = "glpi_plugin_fusioninventory_printers"; $query = "SELECT *\n FROM `glpi_plugin_fusioninventory_printers`\n WHERE `printers_id`='" . $printer_id . "' "; $result = $DB->query($query); $data = array(); if ($DB->numrows($result) > 0) { $data = $DB->fetch_assoc($result); } $data['sysdescr'] = $this->fields['sysdescr']; $data['plugin_fusioninventory_configsecurities_id'] = $this->fields['plugin_fusioninventory_configsecurities_id']; if ($DB->numrows($result) == 0) { $data['printers_id'] = $printer_id; $pfPrinter->add($data); } else { $pfPrinter->update($data); } $this->deleteFromDB($items_id, 1); $Import++; break; case 'NetworkEquipment': $NetworkEquipment = new NetworkEquipment(); $data["entities_id"] = $this->fields["entities_id"]; if (!empty($this->fields["name"])) { $data["name"] = $this->fields["name"]; } $data["locations_id"] = $this->fields["locations_id"]; $data["serial"] = $this->fields["serial"]; $data["otherserial"] = $this->fields["otherserial"]; $data["contact"] = $this->fields["contact"]; $data["domain"] = $this->fields["domain"]; $data["comment"] = $this->fields["comment"]; $data["is_dynamic"] = 1; // $data_Port = current($a_NetworkPorts); // $data["ip"] = $data_Port["ip"]; // $data["mac"] = $data_Port["mac"]; $NetworkEquipment_id = $NetworkEquipment->add($data); foreach ($a_NetworkPorts as $data_Port) { $data_Port['items_id'] = $NetworkEquipment_id; $data_Port['itemtype'] = $NetworkEquipment->getType(); $NetworkPort->update($data_Port); } $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment(); $_SESSION['glpi_plugins_fusinvsnmp_table'] = "glpi_plugin_fusioninventory_networkequipments"; $query = "SELECT *\n FROM `glpi_plugin_fusioninventory_networkequipments`\n WHERE `networkequipments_id`='" . $NetworkEquipment_id . "' "; $result = $DB->query($query); $data = array(); if ($DB->numrows($result) > 0) { $data = $DB->fetch_assoc($result); } $data['sysdescr'] = $this->fields['sysdescr']; $data['plugin_fusioninventory_configsecurities_id'] = $this->fields['plugin_fusioninventory_configsecurities_id']; if ($DB->numrows($result) == 0) { $data['networkequipments_id'] = $NetworkEquipment_id; $pfNetworkEquipment->add($data); } else { $pfNetworkEquipment->update($data); } $this->deleteFromDB($items_id, 1); $Import++; break; case 'Peripheral': $Peripheral = new Peripheral(); $data["entities_id"] = $this->fields["entities_id"]; if (!empty($this->fields["name"])) { $data["name"] = $this->fields["name"]; } $data["locations_id"] = $this->fields["locations_id"]; $data["serial"] = $this->fields["serial"]; $data["otherserial"] = $this->fields["otherserial"]; $data["contact"] = $this->fields["contact"]; $data["comment"] = $this->fields["comment"]; $data["is_dynamic"] = 1; $Peripheral_id = $Peripheral->add($data); foreach ($a_NetworkPorts as $data_Port) { $data_Port['items_id'] = $Peripheral_id; $data_Port['itemtype'] = $Peripheral->getType(); $NetworkPort->update($data_Port); } $this->deleteFromDB($items_id, 1); $Import++; break; case 'Computer': $Computer = new Computer(); $data["entities_id"] = $this->fields["entities_id"]; if (!empty($this->fields["name"])) { $data["name"] = $this->fields["name"]; } $data["locations_id"] = $this->fields["locations_id"]; $data["serial"] = $this->fields["serial"]; $data["otherserial"] = $this->fields["otherserial"]; $data["contact"] = $this->fields["contact"]; $data["domain"] = $this->fields["domain"]; $data["comment"] = $this->fields["comment"]; $data["is_dynamic"] = 1; $Computer_id = $Computer->add($data); foreach ($a_NetworkPorts as $data_Port) { $data_Port['items_id'] = $Computer_id; $data_Port['itemtype'] = $Computer->getType(); $NetworkPort->update($data_Port); } $this->deleteFromDB($items_id, 1); $Import++; break; case 'Phone': $Phone = new Phone(); $data["entities_id"] = $this->fields["entities_id"]; $data["name"] = $this->fields["name"]; $data["locations_id"] = $this->fields["locations_id"]; $data["serial"] = $this->fields["serial"]; $data["otherserial"] = $this->fields["otherserial"]; $data["contact"] = $this->fields["contact"]; $data["comment"] = $this->fields["comment"]; $data["is_dynamic"] = 1; $phone_id = $Phone->add($data); foreach ($a_NetworkPorts as $data_Port) { $data_Port['items_id'] = $phone_id; $data_Port['itemtype'] = $Phone->getType(); $NetworkPort->update($data_Port); } $this->deleteFromDB($items_id, 1); $Import++; break; default: $NoImport++; break; } return array($Import, $NoImport); }
/** * Update computer data * * @global type $DB * * @param php array $a_computerinventory all data from the agent * @param integer $computers_id id of the computer * @param boolean $no_history set true if not want history * * @return nothing */ function updateComputer($a_computerinventory, $computers_id, $no_history, $setdynamic = 0) { global $DB, $CFG_GLPI; $computer = new Computer(); $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer(); $item_DeviceProcessor = new Item_DeviceProcessor(); $deviceProcessor = new DeviceProcessor(); $item_DeviceMemory = new Item_DeviceMemory(); $deviceMemory = new DeviceMemory(); $computerVirtualmachine = new ComputerVirtualMachine(); $computerDisk = new ComputerDisk(); $item_DeviceControl = new Item_DeviceControl(); $item_DeviceHardDrive = new Item_DeviceHardDrive(); $item_DeviceDrive = new Item_DeviceDrive(); $item_DeviceGraphicCard = new Item_DeviceGraphicCard(); $item_DeviceNetworkCard = new Item_DeviceNetworkCard(); $item_DeviceSoundCard = new Item_DeviceSoundCard(); $networkPort = new NetworkPort(); $networkName = new NetworkName(); $iPAddress = new IPAddress(); $ipnetwork = new IPNetwork(); $pfInventoryComputerAntivirus = new PluginFusioninventoryInventoryComputerAntivirus(); $pfConfig = new PluginFusioninventoryConfig(); $pfComputerLicenseInfo = new PluginFusioninventoryComputerLicenseInfo(); $computer_Item = new Computer_Item(); $monitor = new Monitor(); $printer = new Printer(); $peripheral = new Peripheral(); // $pfInventoryComputerStorage = new PluginFusioninventoryInventoryComputerStorage(); // $pfInventoryComputerStorage_Storage = // new PluginFusioninventoryInventoryComputerStorage_Storage(); $computer->getFromDB($computers_id); $a_lockable = PluginFusioninventoryLock::getLockFields('glpi_computers', $computers_id); // * Computer $db_computer = array(); $db_computer = $computer->fields; $computerName = $a_computerinventory['Computer']['name']; $a_ret = PluginFusioninventoryToolbox::checkLock($a_computerinventory['Computer'], $db_computer, $a_lockable); $a_computerinventory['Computer'] = $a_ret[0]; $input = $a_computerinventory['Computer']; $input['id'] = $computers_id; $history = TRUE; if ($no_history) { $history = FALSE; } $input['_no_history'] = $no_history; PluginFusioninventoryInventoryComputerInventory::addDefaultStateIfNeeded($input); $computer->update($input, !$no_history); $this->computer = $computer; // * Computer fusion (ext) $db_computer = array(); if ($no_history === FALSE) { $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercomputers`\n WHERE `computers_id` = '{$computers_id}'\n LIMIT 1"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { foreach ($data as $key => $value) { $data[$key] = Toolbox::addslashes_deep($value); } $db_computer = $data; } } if (count($db_computer) == '0') { // Add $a_computerinventory['fusioninventorycomputer']['computers_id'] = $computers_id; $pfInventoryComputerComputer->add($a_computerinventory['fusioninventorycomputer'], array(), FALSE); } else { // Update if (!empty($db_computer['serialized_inventory'])) { $setdynamic = 0; } $idtmp = $db_computer['id']; unset($db_computer['id']); unset($db_computer['computers_id']); $a_ret = PluginFusioninventoryToolbox::checkLock($a_computerinventory['fusioninventorycomputer'], $db_computer); $a_computerinventory['fusioninventorycomputer'] = $a_ret[0]; $db_computer = $a_ret[1]; $input = $a_computerinventory['fusioninventorycomputer']; $input['id'] = $idtmp; $input['_no_history'] = $no_history; $pfInventoryComputerComputer->update($input, !$no_history); } // Put all link item dynamic (in case of update computer not yet inventoried with fusion) if ($setdynamic == 1) { $this->setDynamicLinkItems($computers_id); } // * Processors if ($pfConfig->getValue("component_processor") != 0) { $db_processors = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_deviceprocessors`.`id`, `designation`,\n `frequency`, `frequence`, `frequency_default`,\n `serial`, `manufacturers_id`, `glpi_items_deviceprocessors`.`nbcores`,\n `glpi_items_deviceprocessors`.`nbthreads`\n FROM `glpi_items_deviceprocessors`\n LEFT JOIN `glpi_deviceprocessors`\n ON `deviceprocessors_id`=`glpi_deviceprocessors`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $db_processors[$idtmp] = Toolbox::addslashes_deep($data); } } if (count($db_processors) == 0) { foreach ($a_computerinventory['processor'] as $a_processor) { $this->addProcessor($a_processor, $computers_id, $no_history); } } else { // Check all fields from source: 'designation', 'serial', 'manufacturers_id', // 'frequence' foreach ($a_computerinventory['processor'] as $key => $arrays) { $frequence = $arrays['frequence']; unset($arrays['frequence']); unset($arrays['frequency']); unset($arrays['frequency_default']); foreach ($db_processors as $keydb => $arraydb) { $frequencedb = $arraydb['frequence']; unset($arraydb['frequence']); unset($arraydb['frequency']); unset($arraydb['frequency_default']); if ($arrays == $arraydb) { $a_criteria = $deviceProcessor->getImportCriteria(); $criteriafrequence = $a_criteria['frequence']; $compare = explode(':', $criteriafrequence); if ($frequence > $frequencedb - $compare[1] && $frequence < $frequencedb + $compare[1]) { unset($a_computerinventory['processor'][$key]); unset($db_processors[$keydb]); break; } } } } if (count($a_computerinventory['processor']) == 0 and count($db_processors) == 0) { // Nothing to do } else { if (count($db_processors) != 0) { // Delete processor in DB foreach ($db_processors as $idtmp => $data) { $item_DeviceProcessor->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['processor']) != 0) { foreach ($a_computerinventory['processor'] as $a_processor) { $this->addProcessor($a_processor, $computers_id, $no_history); } } } } } // * Memories if ($pfConfig->getValue("component_memory") != 0) { $db_memories = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_devicememories`.`id`, `designation`, `size`,\n `frequence`, `serial`, `devicememorytypes_id`,\n `glpi_items_devicememories`.`busID`\n FROM `glpi_items_devicememories`\n LEFT JOIN `glpi_devicememories` ON `devicememories_id`=`glpi_devicememories`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $db_memories[$idtmp] = $data1; } } if (count($db_memories) == 0) { foreach ($a_computerinventory['memory'] as $a_memory) { $this->addMemory($a_memory, $computers_id, $no_history); } } else { // Check all fields from source: 'designation', 'serial', 'size', // 'devicememorytypes_id', 'frequence' foreach ($a_computerinventory['memory'] as $key => $arrays) { $frequence = $arrays['frequence']; unset($arrays['frequence']); foreach ($db_memories as $keydb => $arraydb) { $frequencedb = $arraydb['frequence']; unset($arraydb['frequence']); if ($arrays == $arraydb) { $a_criteria = $deviceMemory->getImportCriteria(); $criteriafrequence = $a_criteria['frequence']; $compare = explode(':', $criteriafrequence); if ($frequence > $frequencedb - $compare[1] && $frequence < $frequencedb + $compare[1]) { unset($a_computerinventory['memory'][$key]); unset($db_memories[$keydb]); break; } } } } if (count($a_computerinventory['memory']) == 0 and count($db_memories) == 0) { // Nothing to do } else { if (count($db_memories) != 0) { // Delete memory in DB foreach ($db_memories as $idtmp => $data) { $item_DeviceMemory->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['memory']) != 0) { foreach ($a_computerinventory['memory'] as $a_memory) { $this->addMemory($a_memory, $computers_id, $no_history); } } } } } // * Hard drive if ($pfConfig->getValue("component_harddrive") != 0) { $db_harddrives = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_deviceharddrives`.`id`, `serial`,\n `capacity`\n FROM `glpi_items_deviceharddrives`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $data2 = array_map('strtolower', $data1); $db_harddrives[$idtmp] = $data2; } } if (count($db_harddrives) == 0) { foreach ($a_computerinventory['harddrive'] as $a_harddrive) { $this->addHardDisk($a_harddrive, $computers_id, $no_history); } } else { foreach ($a_computerinventory['harddrive'] as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); foreach ($db_harddrives as $keydb => $arraydb) { if ($arrayslower['serial'] == $arraydb['serial']) { if ($arraydb['capacity'] == 0 and $arrayslower['capacity'] > 0) { $input = array('id' => $keydb, 'capacity' => $arrayslower['capacity']); $item_DeviceHardDrive->update($input); } unset($a_computerinventory['harddrive'][$key]); unset($db_harddrives[$keydb]); break; } } } if (count($a_computerinventory['harddrive']) == 0 and count($db_harddrives) == 0) { // Nothing to do } else { if (count($db_harddrives) != 0) { // Delete hard drive in DB foreach ($db_harddrives as $idtmp => $data) { $item_DeviceHardDrive->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['harddrive']) != 0) { foreach ($a_computerinventory['harddrive'] as $a_harddrive) { $this->addHardDisk($a_harddrive, $computers_id, $no_history); } } } } } // * drive if ($pfConfig->getValue("component_drive") != 0) { $db_drives = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_devicedrives`.`id`, `serial`,\n `glpi_devicedrives`.`designation`\n FROM `glpi_items_devicedrives`\n LEFT JOIN `glpi_devicedrives` ON `devicedrives_id`=`glpi_devicedrives`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $data2 = array_map('strtolower', $data1); $db_drives[$idtmp] = $data2; } } if (count($db_drives) == 0) { foreach ($a_computerinventory['drive'] as $a_drive) { $this->addDrive($a_drive, $computers_id, $no_history); } } else { foreach ($a_computerinventory['drive'] as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); if ($arrayslower['serial'] == '') { foreach ($db_drives as $keydb => $arraydb) { if ($arrayslower['designation'] == $arraydb['designation']) { unset($a_computerinventory['drive'][$key]); unset($db_drives[$keydb]); break; } } } else { foreach ($db_drives as $keydb => $arraydb) { if ($arrayslower['serial'] == $arraydb['serial']) { unset($a_computerinventory['drive'][$key]); unset($db_drives[$keydb]); break; } } } } if (count($a_computerinventory['drive']) == 0 and count($db_drives) == 0) { // Nothing to do } else { if (count($db_drives) != 0) { // Delete drive in DB foreach ($db_drives as $idtmp => $data) { $item_DeviceDrive->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['drive']) != 0) { foreach ($a_computerinventory['drive'] as $a_drive) { $this->addDrive($a_drive, $computers_id, $no_history); } } } } } // * Graphiccard if ($pfConfig->getValue("component_graphiccard") != 0) { $db_graphiccards = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_devicegraphiccards`.`id`, `designation`, `memory`\n FROM `glpi_items_devicegraphiccards`\n LEFT JOIN `glpi_devicegraphiccards`\n ON `devicegraphiccards_id`=`glpi_devicegraphiccards`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['designation'])) { $data['designation'] = Toolbox::addslashes_deep($data['designation']); } $data['designation'] = trim(strtolower($data['designation'])); $db_graphiccards[$idtmp] = $data; } } if (count($db_graphiccards) == 0) { foreach ($a_computerinventory['graphiccard'] as $a_graphiccard) { $this->addGraphicCard($a_graphiccard, $computers_id, $no_history); } } else { // Check all fields from source: 'designation', 'memory' foreach ($a_computerinventory['graphiccard'] as $key => $arrays) { $arrays['designation'] = strtolower($arrays['designation']); foreach ($db_graphiccards as $keydb => $arraydb) { if ($arrays == $arraydb) { unset($a_computerinventory['graphiccard'][$key]); unset($db_graphiccards[$keydb]); break; } } } if (count($a_computerinventory['graphiccard']) == 0 and count($db_graphiccards) == 0) { // Nothing to do } else { if (count($db_graphiccards) != 0) { // Delete graphiccard in DB foreach ($db_graphiccards as $idtmp => $data) { $item_DeviceGraphicCard->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['graphiccard']) != 0) { foreach ($a_computerinventory['graphiccard'] as $a_graphiccard) { $this->addGraphicCard($a_graphiccard, $computers_id, $no_history); } } } } } // * networkcard if ($pfConfig->getValue("component_networkcard") != 0) { $db_networkcards = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_devicenetworkcards`.`id`, `designation`, `mac`,\n `manufacturers_id`\n FROM `glpi_items_devicenetworkcards`\n LEFT JOIN `glpi_devicenetworkcards`\n ON `devicenetworkcards_id`=`glpi_devicenetworkcards`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['designation'])) { $data['designation'] = Toolbox::addslashes_deep($data['designation']); } $data['designation'] = trim(strtolower($data['designation'])); $db_networkcards[$idtmp] = $data; } } if (count($db_networkcards) == 0) { foreach ($a_computerinventory['networkcard'] as $a_networkcard) { $this->addNetworkCard($a_networkcard, $computers_id, $no_history); } } else { // Check all fields from source: 'designation', 'mac' foreach ($a_computerinventory['networkcard'] as $key => $arrays) { $arrays['designation'] = strtolower($arrays['designation']); foreach ($db_networkcards as $keydb => $arraydb) { if ($arrays == $arraydb) { unset($a_computerinventory['networkcard'][$key]); unset($db_networkcards[$keydb]); break; } } } if (count($a_computerinventory['networkcard']) == 0 and count($db_networkcards) == 0) { // Nothing to do } else { if (count($db_networkcards) != 0) { // Delete networkcard in DB foreach ($db_networkcards as $idtmp => $data) { $item_DeviceNetworkCard->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['networkcard']) != 0) { foreach ($a_computerinventory['networkcard'] as $a_networkcard) { $this->addNetworkCard($a_networkcard, $computers_id, $no_history); } } } } } // * Sound if ($pfConfig->getValue("component_soundcard") != 0) { $db_soundcards = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_devicesoundcards`.`id`, `designation`, `comment`,\n `manufacturers_id` FROM `glpi_items_devicesoundcards`\n LEFT JOIN `glpi_devicesoundcards`\n ON `devicesoundcards_id`=`glpi_devicesoundcards`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $db_soundcards[$idtmp] = $data1; } } if (count($db_soundcards) == 0) { foreach ($a_computerinventory['soundcard'] as $a_soundcard) { $this->addSoundCard($a_soundcard, $computers_id, $no_history); } } else { // Check all fields from source: 'designation', 'memory', 'manufacturers_id' foreach ($a_computerinventory['soundcard'] as $key => $arrays) { // $arrayslower = array_map('strtolower', $arrays); $arrayslower = $arrays; foreach ($db_soundcards as $keydb => $arraydb) { if ($arrayslower == $arraydb) { unset($a_computerinventory['soundcard'][$key]); unset($db_soundcards[$keydb]); break; } } } if (count($a_computerinventory['soundcard']) == 0 and count($db_soundcards) == 0) { // Nothing to do } else { if (count($db_soundcards) != 0) { // Delete soundcard in DB foreach ($db_soundcards as $idtmp => $data) { $item_DeviceSoundCard->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['soundcard']) != 0) { foreach ($a_computerinventory['soundcard'] as $a_soundcard) { $this->addSoundCard($a_soundcard, $computers_id, $no_history); } } } } } // * Controllers if ($pfConfig->getValue("component_control") != 0) { $db_controls = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_items_devicecontrols`.`id`, `interfacetypes_id`,\n `manufacturers_id`, `designation` FROM `glpi_items_devicecontrols`\n LEFT JOIN `glpi_devicecontrols` ON `devicecontrols_id`=`glpi_devicecontrols`.`id`\n WHERE `items_id` = '{$computers_id}'\n AND `itemtype`='Computer'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $data2 = array_map('strtolower', $data1); $db_controls[$idtmp] = $data2; } } if (count($db_controls) == 0) { foreach ($a_computerinventory['controller'] as $a_control) { $this->addControl($a_control, $computers_id, $no_history); } } else { // Check all fields from source: foreach ($a_computerinventory['controller'] as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); foreach ($db_controls as $keydb => $arraydb) { if ($arrayslower == $arraydb) { unset($a_computerinventory['controller'][$key]); unset($db_controls[$keydb]); break; } } } if (count($a_computerinventory['controller']) == 0 and count($db_controls) == 0) { // Nothing to do } else { if (count($db_controls) != 0) { // Delete controller in DB foreach ($db_controls as $idtmp => $data) { $item_DeviceControl->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['controller']) != 0) { foreach ($a_computerinventory['controller'] as $a_control) { $this->addControl($a_control, $computers_id, $no_history); } } } } } // * Software if ($pfConfig->getValue("import_software") != 0) { $entities_id = 0; if (count($a_computerinventory['software']) > 0) { $a_softfirst = current($a_computerinventory['software']); if (isset($a_softfirst['entities_id'])) { $entities_id = $a_softfirst['entities_id']; } } $db_software = array(); if ($no_history === FALSE) { $query = "SELECT `glpi_computers_softwareversions`.`id` as sid,\n `glpi_softwares`.`name`,\n `glpi_softwareversions`.`name` AS version,\n `glpi_softwares`.`manufacturers_id`,\n `glpi_softwareversions`.`entities_id`,\n `glpi_computers_softwareversions`.`is_template_computer`,\n `glpi_computers_softwareversions`.`is_deleted_computer`\n FROM `glpi_computers_softwareversions`\n LEFT JOIN `glpi_softwareversions`\n ON (`glpi_computers_softwareversions`.`softwareversions_id`\n = `glpi_softwareversions`.`id`)\n LEFT JOIN `glpi_softwares`\n ON (`glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`)\n WHERE `glpi_computers_softwareversions`.`computers_id` = '{$computers_id}'\n AND `glpi_computers_softwareversions`.`is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['sid']; unset($data['sid']); if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['name'])) { $data['name'] = Toolbox::addslashes_deep($data['name']); } if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['version'])) { $data['version'] = Toolbox::addslashes_deep($data['version']); } $comp_key = strtolower($data['name']) . "\$\$\$\$" . strtolower($data['version']) . "\$\$\$\$" . $data['manufacturers_id'] . "\$\$\$\$" . $data['entities_id']; $db_software[$comp_key] = $idtmp; } } $lastSoftwareid = 0; $lastSoftwareVid = 0; /* * Schema * * LOCK software * 1/ Add all software * RELEASE software * * LOCK softwareversion * 2/ Add all software versions * RELEASE softwareversion * * 3/ add version to computer * */ if (count($db_software) == 0) { // there are no software associated with computer $nb_unicity = count(FieldUnicity::getUnicityFieldsConfig("Software", $entities_id)); $options = array(); if ($nb_unicity == 0) { $options['disable_unicity_check'] = TRUE; } $a_softwareInventory = array(); $a_softwareVersionInventory = array(); $lastSoftwareid = $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid); $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwares`\n SET `value`='1'"; $CFG_GLPI["use_log_in_files"] = FALSE; while (!$DB->query($queryDBLOCK)) { usleep(100000); } $CFG_GLPI["use_log_in_files"] = TRUE; $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid); foreach ($a_computerinventory['software'] as $a_software) { if (!isset($this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']])) { $this->addSoftware($a_software, $options); } } $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwares`\n WHERE `value`='1'"; $DB->query($queryDBLOCK); $lastSoftwareVid = $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid); $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwareversions`\n SET `value`='1'"; $CFG_GLPI["use_log_in_files"] = FALSE; while (!$DB->query($queryDBLOCK)) { usleep(100000); } $CFG_GLPI["use_log_in_files"] = TRUE; $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid); foreach ($a_computerinventory['software'] as $a_software) { $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']]; if (!isset($this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id])) { $this->addSoftwareVersion($a_software, $softwares_id); } } $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwareversions`\n WHERE `value`='1'"; $DB->query($queryDBLOCK); $a_toinsert = array(); foreach ($a_computerinventory['software'] as $a_software) { $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']]; $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id]; $a_tmp = array('computers_id' => $computers_id, 'softwareversions_id' => $softwareversions_id, 'is_dynamic' => 1, 'entities_id' => $a_software['entities_id']); $a_toinsert[] = "('" . implode("','", $a_tmp) . "')"; } if (count($a_toinsert) > 0) { $this->addSoftwareVersionsComputer($a_toinsert); if (!$no_history) { foreach ($a_computerinventory['software'] as $a_software) { $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']]; $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id]; $changes[0] = '0'; $changes[1] = ""; $changes[2] = $a_software['name'] . " - " . sprintf(__('%1$s (%2$s)'), $a_software['version'], $softwareversions_id); $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_INSTALL_SOFTWARE); $changes[0] = '0'; $changes[1] = ""; $changes[2] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id); $this->addPrepareLog($softwareversions_id, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_INSTALL_SOFTWARE); } } } } else { foreach ($a_computerinventory['software'] as $key => $arrayslower) { if (isset($db_software[$key])) { unset($a_computerinventory['software'][$key]); unset($db_software[$key]); } } if (count($a_computerinventory['software']) == 0 && count($db_software) == 0) { // Nothing to do } else { if (count($db_software) > 0) { // Delete softwares in DB $a_delete = array(); foreach ($db_software as $idtmp) { $this->computer_SoftwareVersion->getFromDB($idtmp); $this->softwareVersion->getFromDB($this->computer_SoftwareVersion->fields['softwareversions_id']); // $this->computer_SoftwareVersion->delete(array('id'=>$idtmp, '_no_history'=> TRUE), FALSE); if (!$no_history) { $changes[0] = '0'; $changes[1] = addslashes($this->computer_SoftwareVersion->getHistoryNameForItem1($this->softwareVersion, 'delete')); $changes[2] = ""; $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_UNINSTALL_SOFTWARE); $changes[0] = '0'; $changes[1] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id); $changes[2] = ""; $this->addPrepareLog($idtmp, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_UNINSTALL_SOFTWARE); } } $query = "DELETE FROM `glpi_computers_softwareversions` " . "WHERE `id` IN ('" . implode("', '", $db_software) . "')"; $DB->query($query); } if (count($a_computerinventory['software']) > 0) { $nb_unicity = count(FieldUnicity::getUnicityFieldsConfig("Software", $entities_id)); $options = array(); if ($nb_unicity == 0) { $options['disable_unicity_check'] = TRUE; } $lastSoftwareid = $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid); $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwares`\n SET `value`='1'"; $CFG_GLPI["use_log_in_files"] = FALSE; while (!$DB->query($queryDBLOCK)) { usleep(100000); } $CFG_GLPI["use_log_in_files"] = TRUE; $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid); foreach ($a_computerinventory['software'] as $a_software) { if (!isset($this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']])) { $this->addSoftware($a_software, $options); } } $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwares`\n WHERE `value`='1'"; $DB->query($queryDBLOCK); $lastSoftwareVid = $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid); $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwareversions`\n SET `value`='1'"; $CFG_GLPI["use_log_in_files"] = FALSE; while (!$DB->query($queryDBLOCK)) { usleep(100000); } $CFG_GLPI["use_log_in_files"] = TRUE; $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid); foreach ($a_computerinventory['software'] as $a_software) { $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']]; if (!isset($this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id])) { $this->addSoftwareVersion($a_software, $softwares_id); } } $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwareversions`\n WHERE `value`='1'"; $DB->query($queryDBLOCK); $a_toinsert = array(); foreach ($a_computerinventory['software'] as $a_software) { $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']]; $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id]; $a_tmp = array('computers_id' => $computers_id, 'softwareversions_id' => $softwareversions_id, 'is_dynamic' => 1, 'entities_id' => $a_software['entities_id']); $a_toinsert[] = "('" . implode("','", $a_tmp) . "')"; } $this->addSoftwareVersionsComputer($a_toinsert); if (!$no_history) { foreach ($a_computerinventory['software'] as $a_software) { $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']]; $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id]; $changes[0] = '0'; $changes[1] = ""; $changes[2] = $a_software['name'] . " - " . sprintf(__('%1$s (%2$s)'), $a_software['version'], $softwareversions_id); $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_INSTALL_SOFTWARE); $changes[0] = '0'; $changes[1] = ""; $changes[2] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id); $this->addPrepareLog($softwareversions_id, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_INSTALL_SOFTWARE); } } } } } } // * Virtualmachines if ($pfConfig->getValue("import_vm") == 1) { $db_computervirtualmachine = array(); if ($no_history === FALSE) { $query = "SELECT `id`, `name`, `uuid`, `virtualmachinesystems_id`\n FROM `glpi_computervirtualmachines`\n WHERE `computers_id` = '{$computers_id}'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $db_computervirtualmachine[$idtmp] = $data1; } } $simplecomputervirtualmachine = array(); if (isset($a_computerinventory['virtualmachine'])) { foreach ($a_computerinventory['virtualmachine'] as $key => $a_computervirtualmachine) { $a_field = array('name', 'uuid', 'virtualmachinesystems_id'); foreach ($a_field as $field) { if (isset($a_computervirtualmachine[$field])) { $simplecomputervirtualmachine[$key][$field] = $a_computervirtualmachine[$field]; } } } } foreach ($simplecomputervirtualmachine as $key => $arrays) { foreach ($db_computervirtualmachine as $keydb => $arraydb) { if ($arrays == $arraydb) { $input = array(); $input['id'] = $keydb; if (isset($a_computerinventory['virtualmachine'][$key]['vcpu'])) { $input['vcpu'] = $a_computerinventory['virtualmachine'][$key]['vcpu']; } if (isset($a_computerinventory['virtualmachine'][$key]['ram'])) { $input['ram'] = $a_computerinventory['virtualmachine'][$key]['ram']; } if (isset($a_computerinventory['virtualmachine'][$key]['virtualmachinetypes_id'])) { $input['virtualmachinetypes_id'] = $a_computerinventory['virtualmachine'][$key]['virtualmachinetypes_id']; } if (isset($a_computerinventory['virtualmachine'][$key]['virtualmachinestates_id'])) { $input['virtualmachinestates_id'] = $a_computerinventory['virtualmachine'][$key]['virtualmachinestates_id']; } $computerVirtualmachine->update($input, !$no_history); unset($simplecomputervirtualmachine[$key]); unset($a_computerinventory['virtualmachine'][$key]); unset($db_computervirtualmachine[$keydb]); break; } } } if (count($a_computerinventory['virtualmachine']) == 0 && count($db_computervirtualmachine) == 0) { // Nothing to do } else { if (count($db_computervirtualmachine) != 0) { // Delete virtualmachine in DB foreach ($db_computervirtualmachine as $idtmp => $data) { $computerVirtualmachine->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['virtualmachine']) != 0) { foreach ($a_computerinventory['virtualmachine'] as $a_virtualmachine) { $a_virtualmachine['computers_id'] = $computers_id; $computerVirtualmachine->add($a_virtualmachine, array(), !$no_history); } } } } if ($pfConfig->getValue("create_vm") == 1) { // Create VM based on information of section VIRTUALMACHINE $pfAgent = new PluginFusioninventoryAgent(); // Use ComputerVirtualMachine::getUUIDRestrictRequest to get existant // vm in computer list $computervm = new Computer(); if (isset($a_computerinventory['virtualmachine_creation']) && is_array($a_computerinventory['virtualmachine_creation'])) { foreach ($a_computerinventory['virtualmachine_creation'] as $a_vm) { // Define location of physical computer (host) $a_vm['locations_id'] = $computer->fields['locations_id']; if (isset($a_vm['uuid']) && $a_vm['uuid'] != '') { $query = "SELECT * FROM `glpi_computers`\n WHERE `uuid` " . ComputerVirtualMachine::getUUIDRestrictRequest($a_vm['uuid']) . "\n LIMIT 1"; // TODO: Add entity search $result = $DB->query($query); $computers_vm_id = 0; while ($data = $DB->fetch_assoc($result)) { $computers_vm_id = $data['id']; } if ($computers_vm_id == 0) { // Add computer $a_vm['entities_id'] = $computer->fields['entities_id']; $computers_vm_id = $computervm->add($a_vm, array(), !$no_history); // Manage networks $this->manageNetworkPort($a_vm['networkport'], $computers_vm_id, FALSE); } else { if ($pfAgent->getAgentWithComputerid($computers_vm_id) === FALSE) { // Update computer $a_vm['id'] = $computers_vm_id; $computervm->update($a_vm, !$no_history); // Manage networks $this->manageNetworkPort($a_vm['networkport'], $computers_vm_id, FALSE); } } } } } } // * ComputerDisk if ($pfConfig->getValue("import_volume") != 0) { $db_computerdisk = array(); if ($no_history === FALSE) { $query = "SELECT `id`, `name`, `device`, `mountpoint`\n FROM `glpi_computerdisks`\n WHERE `computers_id` = '" . $computers_id . "'\n AND `is_dynamic`='1'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $data2 = array_map('strtolower', $data1); $db_computerdisk[$idtmp] = $data2; } } $simplecomputerdisk = array(); foreach ($a_computerinventory['computerdisk'] as $key => $a_computerdisk) { $a_field = array('name', 'device', 'mountpoint'); foreach ($a_field as $field) { if (isset($a_computerdisk[$field])) { $simplecomputerdisk[$key][$field] = $a_computerdisk[$field]; } } } foreach ($simplecomputerdisk as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); foreach ($db_computerdisk as $keydb => $arraydb) { if ($arrayslower == $arraydb) { $input = array(); $input['id'] = $keydb; if (isset($a_computerinventory['computerdisk'][$key]['filesystems_id'])) { $input['filesystems_id'] = $a_computerinventory['computerdisk'][$key]['filesystems_id']; } $input['totalsize'] = $a_computerinventory['computerdisk'][$key]['totalsize']; $input['freesize'] = $a_computerinventory['computerdisk'][$key]['freesize']; $input['_no_history'] = TRUE; $computerDisk->update($input, FALSE); unset($simplecomputerdisk[$key]); unset($a_computerinventory['computerdisk'][$key]); unset($db_computerdisk[$keydb]); break; } } } if (count($a_computerinventory['computerdisk']) == 0 and count($db_computerdisk) == 0) { // Nothing to do } else { if (count($db_computerdisk) != 0) { // Delete computerdisk in DB foreach ($db_computerdisk as $idtmp => $data) { $computerDisk->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['computerdisk']) != 0) { foreach ($a_computerinventory['computerdisk'] as $a_computerdisk) { $a_computerdisk['computers_id'] = $computers_id; $a_computerdisk['is_dynamic'] = 1; $a_computerdisk['_no_history'] = $no_history; $computerDisk->add($a_computerdisk, array(), !$no_history); } } } } // * Networkports if ($pfConfig->getValue("component_networkcard") != 0) { // Get port from unmanaged device if exist $this->manageNetworkPort($a_computerinventory['networkport'], $computers_id, $no_history); } // * Antivirus $db_antivirus = array(); if ($no_history === FALSE) { $query = "SELECT `id`, `name`, `version`\n FROM `glpi_plugin_fusioninventory_inventorycomputerantiviruses`\n WHERE `computers_id` = '{$computers_id}'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $data2 = array_map('strtolower', $data1); $db_antivirus[$idtmp] = $data2; } } $simpleantivirus = array(); foreach ($a_computerinventory['antivirus'] as $key => $a_antivirus) { $a_field = array('name', 'version'); foreach ($a_field as $field) { if (isset($a_antivirus[$field])) { $simpleantivirus[$key][$field] = $a_antivirus[$field]; } } } foreach ($simpleantivirus as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); foreach ($db_antivirus as $keydb => $arraydb) { if ($arrayslower == $arraydb) { $input = array(); $input = $a_computerinventory['antivirus'][$key]; $input['id'] = $keydb; $pfInventoryComputerAntivirus->update($input, !$no_history); unset($simpleantivirus[$key]); unset($a_computerinventory['antivirus'][$key]); unset($db_antivirus[$keydb]); break; } } } if (count($a_computerinventory['antivirus']) == 0 and count($db_antivirus) == 0) { // Nothing to do } else { if (count($db_antivirus) != 0) { foreach ($db_antivirus as $idtmp => $data) { $pfInventoryComputerAntivirus->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['antivirus']) != 0) { foreach ($a_computerinventory['antivirus'] as $a_antivirus) { $a_antivirus['computers_id'] = $computers_id; $pfInventoryComputerAntivirus->add($a_antivirus, array(), !$no_history); } } } // * Licenseinfo $db_licenseinfo = array(); if ($no_history === FALSE) { $query = "SELECT `id`, `name`, `fullname`, `serial`\n FROM `glpi_plugin_fusioninventory_computerlicenseinfos`\n WHERE `computers_id` = '{$computers_id}'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data1 = Toolbox::addslashes_deep($data); $data2 = array_map('strtolower', $data1); $db_licenseinfo[$idtmp] = $data2; } } foreach ($a_computerinventory['licenseinfo'] as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); foreach ($db_licenseinfo as $keydb => $arraydb) { if ($arrayslower == $arraydb) { unset($a_computerinventory['licenseinfo'][$key]); unset($db_licenseinfo[$keydb]); break; } } } if (count($a_computerinventory['licenseinfo']) == 0 and count($db_licenseinfo) == 0) { // Nothing to do } else { if (count($db_licenseinfo) != 0) { foreach ($db_licenseinfo as $idtmp => $data) { $pfComputerLicenseInfo->delete(array('id' => $idtmp), 1); } } if (count($a_computerinventory['licenseinfo']) != 0) { foreach ($a_computerinventory['licenseinfo'] as $a_licenseinfo) { $a_licenseinfo['computers_id'] = $computers_id; $pfComputerLicenseInfo->add($a_licenseinfo, array(), !$no_history); } } } // * Batteries /* Standby, see ticket http://forge.fusioninventory.org/issues/1907 $db_batteries = array(); if ($no_history === FALSE) { $query = "SELECT `id`, `name`, `serial` FROM `glpi_plugin_fusioninventory_inventorycomputerbatteries` WHERE `computers_id` = '$computers_id'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['id']; unset($data['id']); $data = Toolbox::addslashes_deep($data); $data = array_map('strtolower', $data); $db_batteries[$idtmp] = $data; } } $simplebatteries = array(); foreach ($a_computerinventory['batteries'] as $key=>$a_batteries) { $a_field = array('name', 'serial'); foreach ($a_field as $field) { if (isset($a_batteries[$field])) { $simplebatteries[$key][$field] = $a_batteries[$field]; } } } foreach ($simplebatteries as $key => $arrays) { $arrayslower = array_map('strtolower', $arrays); foreach ($db_batteries as $keydb => $arraydb) { if ($arrayslower == $arraydb) { $input = array(); $input = $a_computerinventory['batteries'][$key]; $input['id'] = $keydb; $pfInventoryComputerBatteries->update($input); unset($simplebatteries[$key]); unset($a_computerinventory['batteries'][$key]); unset($db_batteries[$keydb]); break; } } } if (count($a_computerinventory['batteries']) == 0 AND count($db_batteries) == 0) { // Nothing to do } else { if (count($db_batteries) != 0) { foreach ($db_batteries as $idtmp => $data) { $pfInventoryComputerBatteries->delete(array('id'=>$idtmp), 1); } } if (count($a_computerinventory['batteries']) != 0) { foreach($a_computerinventory['batteries'] as $a_batteries) { $a_batteries['computers_id'] = $computers_id; $pfInventoryComputerBatteries->add($a_batteries, array(), FALSE); } } } */ $entities_id = $_SESSION["plugin_fusioninventory_entity"]; // * Monitors $rule = new PluginFusioninventoryInventoryRuleImportCollection(); $a_monitors = array(); foreach ($a_computerinventory['monitor'] as $key => $arrays) { $input = array(); $input['itemtype'] = "Monitor"; $input['name'] = $arrays['name']; $input['serial'] = $arrays['serial']; $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE)); if (isset($data['found_equipment'])) { if ($data['found_equipment'][0] == 0) { // add monitor $arrays['entities_id'] = $entities_id; $a_monitors[] = $monitor->add($arrays); } else { $a_monitors[] = $data['found_equipment'][0]; } } } $db_monitors = array(); $query = "SELECT `glpi_monitors`.`id`,\n `glpi_computers_items`.`id` as link_id\n FROM `glpi_computers_items`\n LEFT JOIN `glpi_monitors` ON `items_id`=`glpi_monitors`.`id`\n WHERE `itemtype`='Monitor'\n AND `computers_id`='" . $computers_id . "'\n AND `entities_id`='" . $entities_id . "'\n AND `glpi_computers_items`.`is_dynamic`='1'\n AND `glpi_monitors`.`is_global`='0'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['link_id']; unset($data['link_id']); $db_monitors[$idtmp] = $data['id']; } if (count($db_monitors) == 0) { foreach ($a_monitors as $monitors_id) { $input = array(); $input['computers_id'] = $computers_id; $input['itemtype'] = 'Monitor'; $input['items_id'] = $monitors_id; $input['is_dynamic'] = 1; $input['_no_history'] = $no_history; $computer_Item->add($input, array(), !$no_history); } } else { // Check all fields from source: foreach ($a_monitors as $key => $monitors_id) { foreach ($db_monitors as $keydb => $monits_id) { if ($monitors_id == $monits_id) { unset($a_monitors[$key]); unset($db_monitors[$keydb]); break; } } } if (count($a_monitors) == 0 and count($db_monitors) == 0) { // Nothing to do } else { if (count($db_monitors) != 0) { // Delete monitors links in DB foreach ($db_monitors as $idtmp => $monits_id) { $computer_Item->delete(array('id' => $idtmp), 1); } } if (count($a_monitors) != 0) { foreach ($a_monitors as $key => $monitors_id) { $input = array(); $input['computers_id'] = $computers_id; $input['itemtype'] = 'Monitor'; $input['items_id'] = $monitors_id; $input['is_dynamic'] = 1; $input['_no_history'] = $no_history; $computer_Item->add($input, array(), !$no_history); } } } } // * Printers $rule = new PluginFusioninventoryInventoryRuleImportCollection(); $a_printers = array(); foreach ($a_computerinventory['printer'] as $key => $arrays) { $input = array(); $input['itemtype'] = "Printer"; $input['name'] = $arrays['name']; $input['serial'] = $arrays['serial']; $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE)); if (isset($data['found_equipment'])) { if ($data['found_equipment'][0] == 0) { // add printer $arrays['entities_id'] = $entities_id; $a_printers[] = $printer->add($arrays); } else { $a_printers[] = $data['found_equipment'][0]; } } } $db_printers = array(); $query = "SELECT `glpi_printers`.`id`, `glpi_computers_items`.`id` as link_id\n FROM `glpi_computers_items`\n LEFT JOIN `glpi_printers` ON `items_id`=`glpi_printers`.`id`\n WHERE `itemtype`='Printer'\n AND `computers_id`='" . $computers_id . "'\n AND `entities_id`='" . $entities_id . "'\n AND `glpi_computers_items`.`is_dynamic`='1'\n AND `glpi_printers`.`is_global`='0'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['link_id']; unset($data['link_id']); $db_printers[$idtmp] = $data['id']; } if (count($db_printers) == 0) { foreach ($a_printers as $printers_id) { $input['entities_id'] = $entities_id; $input['computers_id'] = $computers_id; $input['itemtype'] = 'Printer'; $input['items_id'] = $printers_id; $input['is_dynamic'] = 1; $input['_no_history'] = $no_history; $computer_Item->add($input, array(), !$no_history); } } else { // Check all fields from source: foreach ($a_printers as $key => $printers_id) { foreach ($db_printers as $keydb => $prints_id) { if ($printers_id == $prints_id) { unset($a_printers[$key]); unset($db_printers[$keydb]); break; } } } if (count($a_printers) == 0 and count($db_printers) == 0) { // Nothing to do } else { if (count($db_printers) != 0) { // Delete printers links in DB foreach ($db_printers as $idtmp => $data) { $computer_Item->delete(array('id' => $idtmp), 1); } } if (count($a_printers) != 0) { foreach ($a_printers as $printers_id) { $input['entities_id'] = $entities_id; $input['computers_id'] = $computers_id; $input['itemtype'] = 'Printer'; $input['items_id'] = $printers_id; $input['is_dynamic'] = 1; $input['_no_history'] = $no_history; $computer_Item->add($input, array(), !$no_history); } } } } // * Peripheral $rule = new PluginFusioninventoryInventoryRuleImportCollection(); $a_peripherals = array(); foreach ($a_computerinventory['peripheral'] as $key => $arrays) { $input = array(); $input['itemtype'] = "Peripheral"; $input['name'] = $arrays['name']; $input['serial'] = $arrays['serial']; $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE)); if (isset($data['found_equipment'])) { if ($data['found_equipment'][0] == 0) { // add peripheral $arrays['entities_id'] = $entities_id; $a_peripherals[] = $peripheral->add($arrays); } else { $a_peripherals[] = $data['found_equipment'][0]; } } } $db_peripherals = array(); $query = "SELECT `glpi_peripherals`.`id`, `glpi_computers_items`.`id` as link_id\n FROM `glpi_computers_items`\n LEFT JOIN `glpi_peripherals` ON `items_id`=`glpi_peripherals`.`id`\n WHERE `itemtype`='Peripheral'\n AND `computers_id`='" . $computers_id . "'\n AND `entities_id`='" . $entities_id . "'\n AND `glpi_computers_items`.`is_dynamic`='1'\n AND `glpi_peripherals`.`is_global`='0'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $idtmp = $data['link_id']; unset($data['link_id']); $db_peripherals[$idtmp] = $data['id']; } if (count($db_peripherals) == 0) { foreach ($a_peripherals as $peripherals_id) { $input = array(); $input['computers_id'] = $computers_id; $input['itemtype'] = 'Peripharal'; $input['items_id'] = $peripherals_id; $input['is_dynamic'] = 1; $input['_no_history'] = $no_history; $computer_Item->add($input, array(), !$no_history); } } else { // Check all fields from source: foreach ($a_peripherals as $key => $peripherals_id) { foreach ($db_peripherals as $keydb => $periphs_id) { if ($peripherals_id == $periphs_id) { unset($a_peripherals[$key]); unset($db_peripherals[$keydb]); break; } } } if (count($a_peripherals) == 0 and count($db_peripherals) == 0) { // Nothing to do } else { if (count($db_peripherals) != 0) { // Delete peripherals links in DB foreach ($db_peripherals as $idtmp => $data) { $computer_Item->delete(array('id' => $idtmp), 1); } } if (count($a_peripherals) != 0) { foreach ($a_peripherals as $peripherals_id) { $input = array(); $input['computers_id'] = $computers_id; $input['itemtype'] = 'Peripharal'; $input['items_id'] = $peripherals_id; $input['is_dynamic'] = 1; $input['_no_history'] = $no_history; $computer_Item->add($input, array(), !$no_history); } } } } // * storage // Manage by uuid to correspond with GLPI data // $db_storage = array(); // if ($no_history === FALSE) { // $query = "SELECT `id`, `uuid` FROM ". // "`glpi_plugin_fusioninventory_inventorycomputerstorages` // WHERE `computers_id` = '$computers_id'"; // $result = $DB->query($query); // while ($data = $DB->fetch_assoc($result)) { // $idtmp = $data['id']; // unset($data['id']); // $data = Toolbox::addslashes_deep($data); // $data = array_map('strtolower', $data); // $db_storage[$idtmp] = $data; // } // } // if (count($db_storage) == 0) { // $a_links = array(); // $a_uuid = array(); // foreach ($a_computerinventory['storage'] as $a_storage) { // $a_storage['computers_id'] = $computers_id; // $insert_id = $pfInventoryComputerStorage->add($a_storage); // if (isset($a_storage['uuid'])) { // $a_uuid[$a_storage['uuid']] = $insert_id; // if (isset($a_storage['uuid_link'])) { // if (is_array($a_storage['uuid_link'])) { // $a_links[$insert_id] = $a_storage['uuid_link']; // } else { // $a_links[$insert_id][] = $a_storage['uuid_link']; // } // } // } // } // foreach ($a_links as $id=>$data) { // foreach ($data as $num=>$uuid) { // $a_links[$id][$num] = $a_uuid[$uuid]; // } // } // foreach ($a_links as $id=>$data) { // foreach ($data as $id2) { // $input = array(); // $input['plugin_fusioninventory_inventorycomputerstorages_id_1'] = $id; // $input['plugin_fusioninventory_inventorycomputerstorages_id_2'] = $id2; // $pfInventoryComputerStorage_Storage->add($input); // } // } // } else { // // Check only field *** from source: // // } $this->addLog(); }
/** * @test */ public function PrinterDiscoveryImport() { global $DB, $PF_CONFIG; $DB->connect(); $a_inventory = array('AUTHSNMP' => '1', 'DESCRIPTION' => 'Brother NC-6400h, Firmware Ver.1.11 (06.12.20),MID 84UZ92', 'ENTITY' => '0', 'FIRMWARE' => '', 'IP' => '10.36.4.29', 'MAC' => '00:80:77:d9:51:c3', 'MANUFACTURER' => 'Brother', 'MODEL' => '', 'MODELSNMP' => 'Printer0442', 'NETBIOSNAME' => 'UH4DLPT01', 'SERIAL' => 'E8J596100', 'SNMPHOSTNAME' => 'UH4DLPT01', 'TYPE' => 'PRINTER'); $pfCommunicationNetworkDiscovery = new PluginFusioninventoryCommunicationNetworkDiscovery(); $printer = new Printer(); $printer->add(array('entities_id' => '0', 'serial' => 'E8J596100')); $_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] = 1; $_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = '1'; $_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'Printer'; $_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = 0; $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = ''; $pfCommunicationNetworkDiscovery->sendCriteria($a_inventory); $a_printers = $printer->find(); $this->assertEquals(1, count($a_printers), 'May have only one Printer'); $a_printer = current($a_printers); $this->assertEquals('UH4DLPT01', $a_printer['name'], 'Hostname of printer may be updated'); }
/** * Check right on Recursive object */ public function testPrinter() { global $DB; $DB->connect(); $ent0 = $this->sharedFixture['entity'][0]; $ent1 = $this->sharedFixture['entity'][1]; $ent2 = $this->sharedFixture['entity'][2]; $printer = new Printer(); $id[0] = $printer->add(array('name' => "Printer 1", 'entities_id' => $ent0, 'is_recursive' => 0)); $this->assertGreaterThan(0, $id[0], "Fail to create Printer 1"); $id[1] = $printer->add(array('name' => "Printer 2", 'entities_id' => $ent0, 'is_recursive' => 1)); $this->assertGreaterThan(0, $id[1], "Fail to create Printer 2"); $id[2] = $printer->add(array('name' => "Printer 3", 'entities_id' => $ent1, 'is_recursive' => 1)); $this->assertGreaterThan(0, $id[2], "Fail to create Ptiner 3"); $id[3] = $printer->add(array('name' => "Printer 4", 'entities_id' => $ent2)); $this->assertGreaterThan(0, $id[3], "Fail to create Printer 4"); // Super admin Session::changeProfile(4); $this->assertEquals(4, $_SESSION['glpiactiveprofile']['id']); $this->assertEquals(31, $_SESSION['glpiactiveprofile']['printer']); // See all $this->assertTrue(Session::changeActiveEntities("all")); $this->assertTrue($printer->can($id[0], READ), "Fail can read Printer 1"); $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); $this->assertTrue($printer->can($id[2], READ), "Fail can read Printer 3"); $this->assertTrue($printer->can($id[3], READ), "Fail can read Printer 4"); $this->assertTrue($printer->canEdit($id[0]), "Fail can write Printer 1"); $this->assertTrue($printer->canEdit($id[1]), "Fail can write Printer 2"); $this->assertTrue($printer->canEdit($id[2]), "Fail can write Printer 3"); $this->assertTrue($printer->canEdit($id[3]), "Fail can write Printer 4"); // See only in main entity $this->assertTrue(Session::changeActiveEntities($ent0)); $this->assertTrue($printer->can($id[0], READ), "Fail can read Printer 1"); $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); $this->assertFalse($printer->can($id[2], READ), "Fail can't read Printer 3"); $this->assertFalse($printer->can($id[3], READ), "Fail can't read Printer 1"); $this->assertTrue($printer->canEdit($id[0]), "Fail can write Printer 1"); $this->assertTrue($printer->canEdit($id[1]), "Fail can write Printer 2"); $this->assertFalse($printer->canEdit($id[2]), "Fail can't write Printer 1"); $this->assertFalse($printer->canEdit($id[3]), "Fail can't write Printer 1"); // See only in child entity 1 + parent if recursive $this->assertTrue(Session::changeActiveEntities($ent1)); $this->assertFalse($printer->can($id[0], READ), "Fail can't read Printer 1"); $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); $this->assertTrue($printer->can($id[2], READ), "Fail can read Printer 3"); $this->assertFalse($printer->can($id[3], READ), "Fail can't read Printer 4"); $this->assertFalse($printer->canEdit($id[0]), "Fail can't write Printer 1"); $this->assertFalse($printer->canEdit($id[1]), "Fail can't write Printer 2"); $this->assertTrue($printer->canEdit($id[2]), "Fail can write Printer 2"); $this->assertFalse($printer->canEdit($id[3]), "Fail can't write Printer 2"); // See only in child entity 2 + parent if recursive $this->assertTrue(Session::changeActiveEntities($ent2)); $this->assertFalse($printer->can($id[0], READ), "Fail can't read Printer 1"); $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); $this->assertFalse($printer->can($id[2], READ), "Fail can't read Printer 3"); $this->assertTrue($printer->can($id[3], READ), "Fail can read Printer 4"); $this->assertFalse($printer->canEdit($id[0]), "Fail can't write Printer 1"); $this->assertFalse($printer->canEdit($id[1]), "Fail can't write Printer 2"); $this->assertFalse($printer->canEdit($id[2]), "Fail can't write Printer 3"); $this->assertTrue($printer->canEdit($id[3]), "Fail can write Printer 4"); }
/** * @covers Printer::deleteByCriteria * @covers Printer::restore */ public function testDeleteByCriteria() { $obj = new Printer(); $this->assertTrue($obj->maybeDeleted()); // Add $id = $obj->add(['name' => __METHOD__, 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true)]); $this->assertGreaterThan(0, $id); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(0, $obj->getField('is_deleted')); $this->assertEquals(0, $obj->isDeleted()); $nb_before = countElementsInTable('glpi_logs', "itemtype = 'Printer'\n AND items_id = '{$id}'"); // DeleteByCriteria without history $this->assertTrue($obj->deleteByCriteria(['name' => __METHOD__], 0, 0)); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(1, $obj->getField('is_deleted')); $this->assertEquals(1, $obj->isDeleted()); $nb_after = countElementsInTable('glpi_logs', "itemtype = 'Printer'\n AND items_id = '{$id}'"); $this->assertEquals($nb_before, $nb_after); // Restore $this->assertTrue($obj->restore(['id' => $id], 0)); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(0, $obj->getField('is_deleted')); $this->assertEquals(0, $obj->isDeleted()); $nb_before = countElementsInTable('glpi_logs', "itemtype = 'Printer'\n AND items_id = '{$id}'"); // DeleteByCriteria with history $this->assertTrue($obj->deleteByCriteria(['name' => __METHOD__], 0, 1)); $this->assertTrue($obj->getFromDB($id)); $this->assertEquals(1, $obj->getField('is_deleted')); $this->assertEquals(1, $obj->isDeleted()); $nb_after = countElementsInTable('glpi_logs', "itemtype = 'Printer'\n AND items_id = '{$id}'"); $this->assertEquals($nb_before + 1, $nb_after); }
/** * * Import printers from OCS * @since 1.0 * @param $cfg_ocs OCSNG mode configuration * @param $computers_id computer's id in GLPI * @param $ocsservers_id OCS server id * @param $ocsComputer * @param $entity the entity in which the printer will be created * @internal param computer $ocsid 's id in OCS */ static function importPrinter($cfg_ocs, $computers_id, $ocsservers_id, $ocsComputer, $entity) { global $DB, $CFG_GLPI; $already_processed = array(); $conn = new Computer_Item(); $p = new Printer(); foreach ($ocsComputer as $printer) { $printer = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($printer)); $print = array(); // TO TEST : PARSE NAME to have real name. $print['name'] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $printer['NAME']); if (empty($print["name"])) { $print["name"] = $printer["DRIVER"]; } $management_process = $cfg_ocs["import_printer"]; //Params for the dictionnary $params['name'] = $print['name']; $params['manufacturer'] = ""; $params['DRIVER'] = $printer['DRIVER']; $params['PORT'] = $printer['PORT']; if (!empty($print["name"])) { $rulecollection = new RuleDictionnaryPrinterCollection(); $res_rule = Toolbox::addslashes_deep($rulecollection->processAllRules(Toolbox::stripslashes_deep($params), array(), array())); if (!isset($res_rule["_ignore_import"]) || !$res_rule["_ignore_import"]) { foreach ($res_rule as $key => $value) { if ($value != '' && $value[0] != '_') { $print[$key] = $value; } } if (isset($res_rule['is_global'])) { if (!$res_rule['is_global']) { $management_process = 2; } else { $management_process = 1; } } //Look for a printer 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`\n AND `computers_id`='{$computers_id}'\n AND `itemtype`='Printer'\n AND `p`.`name`='" . $print["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 printer object $p->reset(); $print["comment"] = $printer["PORT"] . "\r\n" . $printer["DRIVER"]; self::analizePrinterPorts($print, $printer["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' "; if ($CFG_GLPI['transfers_id_auto'] < 1) { $query .= " 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"); $already_processed[] = $id_printer; } else { $input = $print; if ($cfg_ocs["states_id_default"] > 0) { $input["states_id"] = $cfg_ocs["states_id_default"]; } $input["entities_id"] = $entity; $id_printer = $p->add($input, array(), $cfg_ocs['history_printer']); } } 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; $input['is_dynamic'] = 1; $id_printer = $p->add($input, array(), $cfg_ocs['history_printer']); } } if ($id_printer) { $already_processed[] = $id_printer; $conn = new Computer_Item(); $connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Printer', 'items_id' => $id_printer, 'is_dynamic' => 1), array(), $cfg_ocs['history_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, $cfg_ocs['history_printer']); } } else { $already_processed[] = $id; } } } } //Look for all printers, not locked, not linked to the computer anymore $query = "SELECT `id`\n FROM `glpi_computers_items`\n WHERE `itemtype`='Printer'\n AND `computers_id`='{$computers_id}'\n AND `is_dynamic`\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 = self::getConfig($ocsservers_id); //Get the management mode for this device $mode = self::getDevicesManagementMode($ocs_config, 'Printer'); $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'] . "'"; $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'] . "'"; $DB->query($query); } } } // foreach ($DB->request($query) as $data){ // Delete all connexions // $conn->delete(array('id' => $data['id'], // '_ocsservers_id' => $ocsservers_id), 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)); } } } }