/** * @covers Computer::post_updateItem */ public function testTypeName() { global $CFG_GLPI; $computer = getItemByTypeName('Computer', '_test_pc01'); $savecomp = $computer->fields; $saveconf = $CFG_GLPI; $printer = getItemByTypeName('Printer', '_test_printer_all'); // Create the link $link = new Computer_Item(); $in = ['computers_id' => $computer->getField('id'), 'itemtype' => $printer->getType(), 'items_id' => $printer->getID()]; $this->assertGreaterThan(0, $link->add($in)); // Change the computer $CFG_GLPI['is_contact_autoupdate'] = 1; $CFG_GLPI['is_user_autoupdate'] = 1; $CFG_GLPI['is_group_autoupdate'] = 1; $CFG_GLPI['state_autoupdate_mode'] = -1; $CFG_GLPI['is_location_autoupdate'] = 1; $in = ['id' => $computer->getField('id'), 'contact' => $this->getUniqueString(), 'contact_num' => $this->getUniqueString(), 'users_id' => $this->getUniqueInteger(), 'groups_id' => $this->getUniqueInteger(), 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger()]; $this->assertTrue($computer->update($in)); $this->assertTrue($computer->getFromDB($computer->getID())); $this->assertTrue($printer->getFromDB($printer->getID())); foreach ($in as $k => $v) { // Check the computer new values $this->assertEquals($v, $computer->getField($k), $k); // Check the printer and test propagation occurs $this->assertEquals($v, $printer->getField($k), $k); } // Change the computer again $CFG_GLPI['is_contact_autoupdate'] = 0; $CFG_GLPI['is_user_autoupdate'] = 0; $CFG_GLPI['is_group_autoupdate'] = 0; $CFG_GLPI['state_autoupdate_mode'] = 0; $CFG_GLPI['is_location_autoupdate'] = 0; $in2 = ['id' => $computer->getField('id'), 'contact' => $this->getUniqueString(), 'contact_num' => $this->getUniqueString(), 'users_id' => $this->getUniqueInteger(), 'groups_id' => $this->getUniqueInteger(), 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger()]; $this->assertTrue($computer->update($in2)); $this->assertTrue($computer->getFromDB($computer->getID())); $this->assertTrue($printer->getFromDB($printer->getID())); foreach ($in2 as $k => $v) { // Check the computer new values $this->assertEquals($v, $computer->getField($k), $k); // Check the printer and test propagation DOES NOT occurs $this->assertEquals($in[$k], $printer->getField($k), $k); } // Restore state $computer->update($savecomp); // Restore configuration $CFG_GLPI = $saveconf; }
case 4: Infocom::showForItem($periph); Contract::showAssociated($periph); break; case 5: Document::showAssociated($periph); break; case 6: Ticket::showListForItem('Peripheral', $_POST["id"]); break; case 7: Link::showForItem('Peripheral', $_POST["id"]); break; case 10: showNotesForm($_POST['target'], 'Peripheral', $_POST["id"]); break; case 11: Reservation::showForItem('Peripheral', $_POST["id"]); break; case 12: Log::showForItem($periph); break; default: if (!Plugin::displayAction($periph, $_REQUEST['glpi_tab'])) { Computer_Item::showForItem($periph); NetworkPort::showForItem('Peripheral', $_POST["id"], $_POST["withtemplate"]); } } } } ajaxFooter();
/** * @see CommonDBTM::getSpecificMassiveActions() **/ function getSpecificMassiveActions($checkitem = NULL) { $actions = parent::getSpecificMassiveActions($checkitem); if (static::canUpdate()) { Computer_Item::getMassiveActionsForItemtype($actions, __CLASS__, 0, $checkitem); MassiveAction::getAddTransferList($actions); } return $actions; }
break; case 4: Infocom::showForItem($monitor); Contract::showAssociated($monitor); break; case 5: Document::showAssociated($monitor, $_POST["withtemplate"]); break; case 6: Ticket::showListForItem('Monitor', $_POST["id"]); break; case 7: Link::showForItem('Monitor', $_POST["id"]); break; case 10: showNotesForm($_POST['target'], 'Monitor', $_POST["id"]); break; case 11: Reservation::showForItem('Monitor', $_POST["id"]); break; case 12: Log::showForItem($monitor); break; default: if (!Plugin::displayAction($monitor, $_REQUEST['glpi_tab'])) { Computer_Item::showForItem($monitor); } } } } ajaxFooter();
static function uninstall($type, $model_id, $tab_ids, $location) { global $UNINSTALL_DIRECT_CONNECTIONS_TYPE; //Get the model $model = new PluginUninstallModel(); $model->getConfig($model_id); //Then destroy all the connexions $transfer = new Transfer(); $transfer->getFromDB($model->fields["transfers_id"]); echo "<div class='center'>"; echo "<table class='tab_cadre_fixe'><tr><th>" . __('Uninstall', 'uninstall') . "</th></tr>"; echo "<tr class='tab_bg_2'><td>"; $count = 0; $tot = count($tab_ids[$type]); Html::createProgressBar(__('Please wait, uninstallation is running...', 'uninstall')); foreach ($tab_ids[$type] as $id => $value) { $count++; $item = new $type(); $item->getFromDB($id); //First clean object and change location and status if needed $entity = $item->fields["entities_id"]; $input = array(); $input["id"] = $id; $input["entities_id"] = $entity; $fields = array(); //Hook to perform actions before item is being uninstalled $item->fields['_uninstall_event'] = $model->getID(); $item->fields['_action'] = 'uninstall'; Plugin::doHook("plugin_uninstall_before", $item); //--------------------// //Direct connections // //------------------// if (in_array($type, $UNINSTALL_DIRECT_CONNECTIONS_TYPE)) { $conn = new Computer_Item(); $conn->deleteByCriteria(array('computers_id' => $id), true); } //--------------------// //-- Common fields --// //------------------// //RAZ contact and contactnumber if ($item->isField('contact') && $model->fields["raz_contact"] == 1) { $fields["contact"] = ''; if ($item->isField('contact_num')) { $fields["contact_num"] = ''; } } //RAZ user if ($model->fields["raz_user"] == 1 && $item->isField('users_id')) { $fields["users_id"] = 0; } //RAZ status if ($model->fields["states_id"] > 0 && $item->isField('states_id')) { $fields["states_id"] = $model->fields["states_id"]; } //RAZ machine's name if ($item->isField('name') && $model->fields["raz_name"] == 1) { $fields["name"] = ''; } if ($item->isField('locations_id')) { if ($location == '') { $location = 0; } switch ($location) { case -1: break; default: $fields["locations_id"] = $location; break; } } if ($item->isField('groups_id')) { $nbgroup = countElementsInTableForEntity("glpi_groups", $entity, "`id`='" . $item->fields['groups_id'] . "'"); if ($model->fields["groups_id"] > -1 && $nbgroup == 1) { // If a new group is defined and if the group is accessible in the object's entity $fields["groups_id"] = $model->fields["groups_id"]; } } //------------------------------// //-- Computer specific fields --// //------------------------------// if ($type == 'Computer') { //RAZ all OS related informations if ($model->fields["raz_os"] == 1) { $fields["operatingsystems_id"] = 0; $fields["operatingsystemversions_id"] = 0; $fields["operatingsystemservicepacks_id"] = 0; $fields["os_licenseid"] = ''; $fields["os_license_number"] = ''; $fields["autoupdatesystems_id"] = 0; } $plug = new Plugin(); if ($plug->isActivated('ocsinventoryng')) { if ($item->fields["is_dynamic"] && ($model->fields["remove_from_ocs"] || $model->fields["delete_ocs_link"])) { $input["is_dynamic"] = 0; } } if ($item->isField('domains_id') && $model->fields["raz_domain"]) { $fields["domains_id"] = 0; } //RAZ network if ($item->isField('networks_id') && $model->fields["raz_network"] == 1) { $fields["networks_id"] = 0; } } //RAZ IPs from all the network cards if ($model->fields["raz_ip"] == 1) { self::razPortInfos($type, $id); // For NetworkEquiment if ($item->isField('ip')) { $fields['ip'] = ''; } if ($item->isField('mac')) { $fields['mac'] = ''; } } foreach ($fields as $name => $value) { if (!($item->getField($name) != NOT_AVAILABLE) || $item->getField($name) != $value) { $input[$name] = $value; } } $item->dohistory = true; $item->update($input); if ($model->fields["raz_budget"] == 1) { $infocom_id = self::getInfocomPresentForDevice($type, $id); if ($infocom_id > 0) { $infocom = new InfoCom(); $tmp["id"] = $infocom_id; $tmp["budgets_id"] = 0; $infocom->dohistory = false; $infocom->update($tmp); } } //Delete machine from glpi_ocs_link if ($type == 'Computer') { //Delete computer's volumes self::purgeComputerVolumes($id); if ($model->fields["raz_history"] == 1) { //Delete history related to software self::deleteHistory($id, false); } else { if ($model->fields["raz_soft_history"] == 1) { //Delete history related to software self::deleteHistory($id, true); } } $plug = new Plugin(); if ($plug->isActivated('ocsinventoryng')) { //Delete computer from OCS if ($model->fields["remove_from_ocs"] == 1) { self::deleteComputerInOCSByGlpiID($id); } //Delete link in glpi_ocs_link if ($model->fields["delete_ocs_link"] || $model->fields["remove_from_ocs"]) { self::deleteOcsLink($id); } } //Should never happend that transfer_id = 0, but just in case if ($model->fields["transfers_id"] > 0) { $transfer->moveItems(array($type => array($id => $id)), $entity, $transfer->fields); } } if ($model->fields['raz_fusioninventory'] == 1) { self::deleteFusionInventoryLink($type, $id); } //Plugin hook after uninstall Plugin::doHook("plugin_uninstall_after", $item); Html::changeProgressBarPosition($count, $tot + 1); } //Add line in machine's history to say that machine was uninstalled self::addUninstallLog($type, $id); Html::changeProgressBarPosition($count, $tot, __('Uninstallation successful', 'uninstall')); echo "</td></tr>"; echo "</table></div>"; }
$monitor->restore($_POST); Event::log($_POST["id"], "monitors", 4, "inventory", sprintf(__('%s restores an item'), $_SESSION["glpiname"])); $monitor->redirectToList(); } else { if (isset($_POST["purge"])) { $monitor->check($_POST["id"], 'd'); $monitor->delete($_POST, 1); Event::log($_POST["id"], "monitors", 4, "inventory", sprintf(__('%s purges an item'), $_SESSION["glpiname"])); $monitor->redirectToList(); } else { if (isset($_POST["update"])) { $monitor->check($_POST["id"], 'w'); $monitor->update($_POST); Event::log($_POST["id"], "monitors", 4, "inventory", sprintf(__('%s updates an item'), $_SESSION["glpiname"])); Html::back(); } else { if (isset($_POST["unglobalize"])) { $monitor->check($_POST["id"], 'w'); Computer_Item::unglobalizeItem($monitor); Event::log($_POST["id"], "monitors", 4, "inventory", sprintf(__('%s sets unitary management'), $_SESSION["glpiname"])); Html::redirect($CFG_GLPI["root_doc"] . "/front/monitor.form.php?id=" . $_POST["id"]); } else { Html::header(Monitor::getTypeName(2), $_SERVER['PHP_SELF'], "inventory", "monitor"); $monitor->showForm($_GET["id"], array('withtemplate' => $_GET["withtemplate"])); Html::footer(); } } } } } }
/** * @param $type * @param $model_id * @param $tab_ids * @param $location **/ static function replace($type, $model_id, $tab_ids, $location) { global $DB, $CFG_GLPI, $PLUGIN_HOOKS; $model = new PluginUninstallModel(); $model->getConfig($model_id); $overwrite = $model->fields["overwrite"]; echo "<div class='center'>"; echo "<table class='tab_cadre_fixe'><tr><th>" . __('Replacement', 'uninstall') . "</th></tr>"; echo "<tr class='tab_bg_2'><td>"; $count = 0; $tot = count($tab_ids); Html::createProgressBar(__('Please wait, replacement is running...', 'uninstall')); foreach ($tab_ids as $olditem_id => $newitem_id) { $count++; $olditem = new $type(); $olditem->getFromDB($olditem_id); $newitem = new $type(); $newitem->getFromDB($newitem_id); //Hook to perform actions before item is being replaced $olditem->fields['_newid'] = $newitem_id; $olditem->fields['_uninstall_event'] = $model_id; $olditem->fields['_action'] = 'replace'; Plugin::doHook("plugin_uninstall_replace_before", $olditem); // Retrieve informations //States if ($model->fields['states_id'] != 0) { $olditem->update(array('id' => $olditem_id, 'states_id' => $model->fields['states_id']), false); } // METHOD REPLACEMENT 1 : Archive if ($model->fields['replace_method'] == self::METHOD_PURGE) { $name_out = str_shuffle(Toolbox::getRandomString(5) . time()); $plugin = new Plugin(); if ($plugin->isActivated('PDF')) { // USE PDF EXPORT $plugin->load('pdf', true); include_once GLPI_ROOT . "/lib/ezpdf/class.ezpdf.php"; //Get all item's tabs $tab = array_keys($olditem->defineTabs()); //Tell PDF to also export item's main tab, and in first position array_unshift($tab, "_main_"); $itempdf = new $PLUGIN_HOOKS['plugin_pdf'][$type]($olditem); $out = $itempdf->generatePDF(array($olditem_id), $tab, 1, false); $name_out .= ".pdf"; } else { //TODO Which datas ? Add Defaults... $out = __('Replacement', 'uninstall') . "\r\n"; $datas = $olditem->fields; unset($datas['comment']); foreach ($datas as $k => $v) { $out .= $k . ";"; } $out .= "\r\n"; foreach ($datas as $k => $v) { $out .= $v . ";"; } // USE CSV EXPORT $name_out .= ".csv"; } // Write document $out_file = GLPI_DOC_DIR . "/_uploads/" . $name_out; $open_file = fopen($out_file, 'a'); fwrite($open_file, $out); fclose($open_file); // Compute comment text $comment = __('This document is the archive of this replaced item', 'uninstall') . " " . self::getCommentsForReplacement($olditem, false, false); // Create & Attach new document to current item $doc = new Document(); $input = array('name' => addslashes(__('Archive of old material', 'uninstall')), 'upload_file' => $name_out, 'comment' => addslashes($comment), 'add' => __('Add'), 'entities_id' => $newitem->getEntityID(), 'is_recursive' => $newitem->isRecursive(), 'link' => "", 'documentcategories_id' => 0, 'items_id' => $olditem_id, 'itemtype' => $type); //Attached the document to the old item, to generate an accurate name $document_added = $doc->add($input); //Attach the document to the new item, once the document's name is correct $docItem = new Document_Item(); $docItemId = $docItem->add(array('documents_id' => $document_added, 'itemtype' => $type, 'items_id' => (int) $newitem_id)); } // General Informations - NAME if ($model->fields["replace_name"]) { if ($overwrite || empty($newitem->fields['name'])) { $newitem->update(array('id' => $newitem_id, 'name' => $olditem->getField('name')), false); } } $data['id'] = $newitem->getID(); // General Informations - SERIAL if ($model->fields["replace_serial"]) { if ($overwrite || empty($newitem->fields['serial'])) { $newitem->update(array('id' => $newitem_id, 'serial' => $olditem->getField('serial')), false); } } // General Informations - OTHERSERIAL if ($model->fields["replace_otherserial"]) { if ($overwrite || empty($newitem->fields['otherserial'])) { $newitem->update(array('id' => $newitem_id, 'otherserial' => $olditem->getField('otherserial')), false); } } // Documents if ($model->fields["replace_documents"] && in_array($type, $CFG_GLPI["document_types"])) { $doc_item = new Document_Item(); foreach (self::getAssociatedDocuments($olditem) as $document) { $doc_item->update(array('id' => $document['assocID'], 'itemtype' => $type, 'items_id' => $newitem_id), false); } } // Contracts if ($model->fields["replace_contracts"] && in_array($type, $CFG_GLPI["contract_types"])) { $contract_item = new Contract_Item(); foreach (self::getAssociatedContracts($olditem) as $contract) { $contract_item->update(array('id' => $contract['id'], 'itemtype' => $type, 'items_id' => $newitem_id), false); } } // Infocoms if ($model->fields["replace_infocoms"] && in_array($type, $CFG_GLPI["infocom_types"])) { $infocom = new Infocom(); if ($overwrite) { // Delete current Infocoms of new item if ($infocom->getFromDBforDevice($type, $newitem_id)) { //Do not log infocom deletion in the new item's history $infocom->dohistory = false; $infocom->deleteFromDB(1); } } // Update current Infocoms of old item if ($infocom->getFromDBforDevice($type, $olditem_id)) { $infocom->update(array('id' => $infocom->getID(), 'itemtype' => $type, 'items_id' => $newitem_id), false); } } // Reservations if ($model->fields["replace_reservations"] && in_array($type, $CFG_GLPI["reservation_types"])) { $resaitem = new ReservationItem(); if ($overwrite) { // Delete current reservation of new item $resa_new = new Reservation(); $resa_new->getFromDB($newitem_id); if ($resa_new->is_reserved()) { $resa_new = new ReservationItem(); $resa_new->getFromDBbyItem($type, $newitem_id); if (count($resa_new->fields)) { $resa_new->deleteFromDB(1); } } } // Update old reservation for attribute to new item $resa_old = new Reservation(); $resa_old->getFromDB($olditem_id); if ($resa_old->is_reserved()) { $resa_old = new ReservationItem(); $resa_old->getFromDBbyItem($type, $olditem_id); if (count($resa_old->fields)) { $resa_old->update(array('id' => $resa_old->getID(), 'itemtype' => $type, 'items_id' => $newitem_id), false); } } } // User if ($model->fields["replace_users"] && in_array($type, $CFG_GLPI["linkuser_types"])) { $data = array(); $data['id'] = $newitem->getID(); if ($newitem->isField('users_id') && ($overwrite || empty($data['users_id']))) { $data['users_id'] = $olditem->getField('users_id'); } if ($newitem->isField('contact') && ($overwrite || empty($data['contact']))) { $data['contact'] = $olditem->getField('contact'); } if ($newitem->isField('contact_num') && ($overwrite || empty($data['contact_num']))) { $data['contact_num'] = $olditem->getField('contact_num'); } $newitem->update($data, false); } // Group if ($model->fields["replace_groups"] && in_array($type, $CFG_GLPI["linkgroup_types"])) { if ($newitem->isField('groups_id') && ($overwrite || empty($data['groups_id']))) { $newitem->update(array('id' => $newitem_id, 'groups_id' => $olditem->getField('groups_id')), false); } } // Tickets if ($model->fields["replace_tickets"] && in_array($type, $CFG_GLPI["ticket_types"])) { $ticket_item = new Item_Ticket(); foreach (self::getAssociatedTickets($type, $olditem_id) as $ticket) { $ticket_item->update(array('id' => $ticket['id'], 'items_id' => $newitem_id), false); } } //Array netport_types renamed in networkport_types in GLPI 0.80 if (isset($CFG_GLPI["netport_types"])) { $netport_types = $CFG_GLPI["netport_types"]; } else { $netport_types = $CFG_GLPI["networkport_types"]; } // NetPorts if ($model->fields["replace_netports"] && in_array($type, $netport_types)) { $netport_item = new NetworkPort(); foreach (self::getAssociatedNetports($type, $olditem_id) as $netport) { $netport_item->update(array('id' => $netport['id'], 'itemtype' => $type, 'items_id' => $newitem_id), false); } } // Directs connections if ($model->fields["replace_direct_connections"] && in_array($type, array('Computer'))) { $comp_item = new Computer_Item(); foreach (self::getAssociatedItems($olditem) as $itemtype => $connections) { foreach ($connections as $connection) { $comp_item->update(array('id' => $connection['id'], 'computers_id' => $newitem_id, 'itemtype' => $itemtype), false); } } } // Location if ($location != 0 && $olditem->isField('locations_id')) { $olditem->getFromDB($olditem_id); switch ($location) { case -1: break; default: $olditem->update(array('id' => $olditem_id, 'locations_id' => $location), false); break; } } $plug = new Plugin(); if ($plug->isActivated('ocsinventoryng')) { //Delete computer from OCS if ($model->fields["remove_from_ocs"] == 1) { PluginUninstallUninstall::deleteComputerInOCSByGlpiID($olditem_id); } //Delete link in glpi_ocs_link if ($model->fields["delete_ocs_link"] || $model->fields["remove_from_ocs"]) { PluginUninstallUninstall::deleteOcsLink($olditem_id); } } if ($plug->isActivated('fusioninventory')) { if ($model->fields['raz_fusioninventory']) { PluginUninstallUninstall::deleteFusionInventoryLink(get_class($olditem), $olditem_id); } } // METHOD REPLACEMENT 1 : Purge if ($model->fields['replace_method'] == self::METHOD_PURGE) { // Retrieve, Compute && Update NEW comment field $comment = self::getCommentsForReplacement($olditem, true); $comment .= "\n- " . __('See attached document', 'uninstall'); $newitem->update(array('id' => $newitem_id, 'comment' => addslashes($comment)), false); // If old item is attached in PDF/CSV // Delete AND Purge it in DB if ($document_added) { $olditem->delete(array('id' => $olditem_id), true); } } // METHOD REPLACEMENT 2 : Delete AND Comment if ($model->fields['replace_method'] == self::METHOD_DELETE_AND_COMMENT) { //Add comment on the new item first $comment = self::getCommentsForReplacement($olditem, true); $newitem->update(array('id' => $newitem_id, 'comment' => Toolbox::addslashes_deep($comment)), false); // Retrieve, Compute && Update OLD comment field $comment = self::getCommentsForReplacement($newitem, false); $olditem->update(array('id' => $olditem_id, 'comment' => Toolbox::addslashes_deep($comment)), false); // Delete OLD item from DB (not PURGE) PluginUninstallUninstall::addUninstallLog($type, $olditem_id, 'replaced_by'); $olditem->delete(array('id' => $olditem_id), 0, false); } //Plugin hook after replacement Plugin::doHook("plugin_uninstall_replace_after", $olditem); //Add history PluginUninstallUninstall::addUninstallLog($type, $newitem_id, 'replace'); Html::changeProgressBarPosition($count, $tot + 1); } Html::changeProgressBarPosition($count, $tot, __('Replacement successful', 'uninstall')); echo "</td></tr>"; echo "</table></div>"; }
/** * Delete direct connection beetween an item and a computer when transfering the item * * @param $itemtype itemtype to tranfer * @param $ID ID of the item * * @since version 0.84.4 **/ function manageConnectionComputer($itemtype, $ID) { global $DB; // Get connections $query = "SELECT *\n FROM `glpi_computers_items`\n WHERE `computers_id` NOT IN " . $this->item_search['Computer'] . "\n AND `itemtype` = '" . $itemtype . "'\n AND `items_id` = {$ID}"; if ($result = $DB->query($query)) { if ($DB->numrows($result) != 0) { // Foreach get item $conn = new Computer_Item(); $comp = new Computer(); while ($data = $DB->fetch_assoc($result)) { $item_ID = $data['items_id']; if ($comp->getFromDB($item_ID)) { $conn->delete(array('id' => $data['id'])); } else { // Unexisting item / Force disconnect $conn->delete(array('id' => $data['id'], '_no_history' => true, '_no_auto_action' => true)); } } } } }
function post_addItem() { global $DB; // Manage add from template if (isset($this->input["_oldID"])) { // ADD Devices Item_devices::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']); // ADD Infocoms Infocom::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']); // ADD Contract Contract_Item::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']); // ADD Documents Document_Item::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']); // ADD Ports NetworkPort::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']); // Add connected devices Computer_Item::cloneComputer($this->input["_oldID"], $this->fields['id']); } }
GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief * @since version 0.84 */ include '../inc/includes.php'; Session::checkCentralAccess(); $conn = new Computer_Item(); if (isset($_POST["disconnect"])) { $conn->check($_POST["id"], PURGE); $conn->delete($_POST, 1); Event::log($_POST["computers_id"], "computers", 5, "inventory", sprintf(__('%s disconnects an item'), $_SESSION["glpiname"])); Html::back(); // Connect a computer to a printer/monitor/phone/peripheral } else { if (isset($_POST["add"])) { if (isset($_POST["items_id"]) && $_POST["items_id"] > 0) { $conn->check(-1, CREATE, $_POST); if ($newID = $conn->add($_POST)) { Event::log($_POST["computers_id"], "computers", 5, "inventory", sprintf(__('%s connects an item'), $_SESSION["glpiname"])); } } Html::back();
echo " <input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>"; break; case "unlock_ocsng_monitor": case "unlock_ocsng_peripheral": case "unlock_ocsng_software": case "unlock_ocsng_printer": case "unlock_ocsng_disk": case "unlock_ocsng_ip": echo "<input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>"; break; case "install": Software::dropdownSoftwareToInstall("softwareversions_id", $_SESSION["glpiactive_entity"], 1); echo " <input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][4] . "'>"; break; case "connect": Computer_Item::dropdownConnect('Computer', $_POST["itemtype"], "connect_item"); echo " <input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>"; break; case "connect_to_computer": Dropdown::showAllItems("connect_item", 0, 0, $_SESSION["glpiactive_entity"], array('Monitor', 'Peripheral', 'Phone', 'Printer'), true); echo " <input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>"; break; case "disconnect": echo "<input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>"; break; case "add_group": Dropdown::show('Group'); echo " <input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>"; break; case "add_userprofile": Dropdown::show('Entity', array('entity' => $_SESSION['glpiactiveentities']));
case 4: Infocom::showForItem($phone); Contract::showAssociated($phone); break; case 5: Document::showAssociated($phone); break; case 6: Ticket::showListForItem('Phone', $_POST["id"]); break; case 7: Link::showForItem('Phone', $_POST["id"]); break; case 10: showNotesForm($_POST['target'], 'Phone', $_POST["id"]); break; case 11: Reservation::showForItem('Phone', $_POST["id"]); break; case 12: Log::showForItem($phone); break; default: if (!Plugin::displayAction($phone, $_REQUEST['glpi_tab'])) { Computer_Item::showForItem($phone); NetworkPort::showForItem('Phone', $_POST["id"], 'Phone', $_POST["withtemplate"]); } } } } ajaxFooter();
function cleanDBonPurge() { global $DB; $query = "SELECT `id`\n FROM `glpi_computers_items`\n WHERE `itemtype` = '" . $this->getType() . "'\n AND `items_id` = '" . $this->fields['id'] . "'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $conn = new Computer_Item(); while ($data = $DB->fetch_array($result)) { $data['_no_auto_action'] = true; $conn->delete($data); } } } }
/** * 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(); }
/** * Duplicate connected items to computer from an item template to its clone * * @since version 0.84 * * @param $oldid ID of the item to clone * @param $newid ID of the item cloned **/ static function cloneComputer($oldid, $newid) { global $DB; $query = "SELECT *\n FROM `glpi_computers_items`\n WHERE `computers_id` = '" . $oldid . "';"; $result = $DB->query($query); foreach ($DB->request($query) as $data) { $conn = new Computer_Item(); $conn->add(array('computers_id' => $newid, 'itemtype' => $data["itemtype"], 'items_id' => $data["items_id"])); } }
GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ if (strpos($_SERVER['PHP_SELF'], "dropdownConnect.php")) { include '../inc/includes.php'; header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } else { if (!defined('GLPI_ROOT')) { die("Sorry. You can't access this file directly"); } } if (!isset($_POST['fromtype']) || !($fromitem = getItemForItemtype($_POST['fromtype']))) { exit; } $fromitem->checkGlobal(UPDATE); $used = array(); if (isset($_POST["used"])) { $used = $_POST["used"]; } Computer_Item::dropdownConnect($_POST["itemtype"], $_POST['fromtype'], $_POST['myname'], $_POST["entity_restrict"], $_POST["onlyglobal"], $used);
$peripheral->restore($_POST); Event::log($_POST["id"], "peripherals", 4, "inventory", sprintf(__('%s restores an item'), $_SESSION["glpiname"])); $peripheral->redirectToList(); } else { if (isset($_POST["purge"])) { $peripheral->check($_POST["id"], PURGE); $peripheral->delete($_POST, 1); Event::log($_POST["id"], "peripherals", 4, "inventory", sprintf(__('%s purges an item'), $_SESSION["glpiname"])); $peripheral->redirectToList(); } else { if (isset($_POST["update"])) { $peripheral->check($_POST["id"], UPDATE); $peripheral->update($_POST); Event::log($_POST["id"], "peripherals", 4, "inventory", sprintf(__('%s updates an item'), $_SESSION["glpiname"])); Html::back(); } else { if (isset($_POST["unglobalize"])) { $peripheral->check($_POST["id"], UPDATE); Computer_Item::unglobalizeItem($peripheral); Event::log($_POST["id"], "peripherals", 4, "inventory", sprintf(__('%s sets unitary management'), $_SESSION["glpiname"])); Html::redirect($CFG_GLPI["root_doc"] . "/front/peripheral.form.php?id=" . $_POST["id"]); } else { Html::header(Peripheral::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "assets", "peripheral"); $peripheral->display(array('id' => $_GET["id"], 'withtemplate' => $_GET["withtemplate"])); Html::footer(); } } } } } }
break; case "connect": if (isset($_POST["connect_item"]) && $_POST["connect_item"]) { $conn = new Computer_Item(); foreach ($_POST["item"] as $key => $val) { if ($val == 1) { $input = array('computers_id' => $_POST["connect_item"], 'itemtype' => $_POST["itemtype"], 'items_id' => $key); if ($conn->can(-1, 'w', $input)) { $conn->add($input); } } } } break; case "disconnect": $conn = new Computer_Item(); foreach ($_POST["item"] as $key => $val) { if ($val == 1) { if ($item->getFromDB($key)) { $conn->disconnectForItem($item); } } } break; case "delete": foreach ($_POST["item"] as $key => $val) { if ($val == 1 && $item->can($key, 'd')) { $item->delete(array("id" => $key)); } } break;
/** 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"); }
/** * Link inventory object to another one * * @param $params the input parameters * @param $protocol the commonication protocol used * **/ static function methodLinkObjects($params, $protocol) { global $CFG_GLPI; if (isset($params['help'])) { return array('fields' => 'array, mandatory', 'help' => 'bool, optional'); } if (!Session::getLoginUserID()) { return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED); } //Must be superadmin to use this method if (!Session::haveRight('config', UPDATE)) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED); } if (!isset($params['fields']) || empty($params['fields']) || !is_array($params['fields'])) { return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'fields'); } if (!isset($_SESSION["glpi_currenttime"])) { $_SESSION["glpi_currenttime"] = date("Y-m-d H:i:s"); } $resp = array(); $errors = array(); foreach ($params['fields'] as $links) { if (!in_array($links['from_item']['itemtype'], array('Computer')) && !preg_match("/Device/", $links['from_item']['itemtype'])) { $errors[] = self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', self::getDisplayError()); } switch ($links['from_item']['itemtype']) { case 'Computer': // Direct connections if (in_array($links['to_item']['itemtype'], array('Monitor', 'Peripheral', 'Phone', 'Printer'))) { $comp_item = new Computer_Item(); $data = array(); $data['items_id'] = $links['to_item']['id']; $data['computers_id'] = $links['from_item']['id']; $data['itemtype'] = $links['to_item']['itemtype']; if (!$comp_item->can(-1, UPDATE, $data)) { $errors[] = self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', self::getDisplayError()); } else { if ($comp_item->add($data)) { $resp['Computer'][$data['computers_id']] = self::methodGetObject(array('itemtype' => 'Computer', 'id' => $data['computers_id'], 'with_printer' => 1, 'with_monitor' => 1, 'with_phone' => 1, 'with_peripheral' => 1), $protocol); } else { $errors[] = self::Error($protocol, WEBSERVICES_ERROR_FAILED, '', self::getDisplayError()); } } } // Device connection if (preg_match("/Device/", $links['to_item']['itemtype'])) { $comp_device = new Computer_Device(); $links_field = getPlural(strtolower($links['to_item']['itemtype'])) . "_id"; $data = array(); $data['computers_id'] = $links['from_item']['id']; $data[$links_field] = $links['to_item']['id']; $data['itemtype'] = $links['to_item']['itemtype']; if (!isset($links['to_item']['quantity']) || !is_numeric($links['to_item']['quantity'])) { $quantity = 1; } else { $quantity = $links['to_item']['quantity']; } if (isset($links['to_item']['specificity'])) { if (!is_numeric($links['to_item']['specificity'])) { $errors[] = self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'specificity'); } else { $data['specificity'] = $links['to_item']['specificity']; } } $linked = false; for ($i = 0; $i < $quantity; $i++) { if (!$comp_device->can(-1, UPDATE, $data)) { $errors[] = self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', self::getDisplayError()); } else { if ($comp_device->add($data)) { $linked = true; } } } if ($linked) { $resp['Computer'][$data['computers_id']] = self::methodGetObject(array('itemtype' => 'Computer', 'id' => $data['computers_id']), $protocol); } else { $errors[] = self::Error($protocol, WEBSERVICES_ERROR_FAILED, '', self::getDisplayError()); } } //other link object break; //itemtype } } if (count($errors)) { $resp = array($resp, $errors); } return $resp; }
$print->restore($_POST); Event::log($_POST["id"], "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][23]); $print->redirectToList(); } else { if (isset($_REQUEST["purge"])) { $print->check($_REQUEST["id"], 'd'); $print->delete($_REQUEST, 1); Event::log($_REQUEST["id"], "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][24]); $print->redirectToList(); } else { if (isset($_POST["update"])) { $print->check($_POST["id"], 'w'); $print->update($_POST); Event::log($_POST["id"], "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][21]); glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_GET["unglobalize"])) { $print->check($_GET["id"], 'w'); Computer_Item::unglobalizeItem($print); Event::log($_GET["id"], "printers", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][60]); glpi_header($CFG_GLPI["root_doc"] . "/front/printer.form.php?id=" . $_GET["id"]); } else { commonHeader($LANG['Menu'][2], $_SERVER['PHP_SELF'], "inventory", "printer"); $print->showForm($_GET["id"], array('withtemplate' => $_GET["withtemplate"])); commonFooter(); } } } } } }
/** Display an infocom report * * @param $itemtype item type * @param $begin begin date * @param $end end date **/ function display_infocoms_report($itemtype, $begin, $end) { global $DB, $valeurtot, $valeurnettetot, $valeurnettegraphtot, $valeurgraphtot, $CFG_GLPI; $itemtable = getTableForItemType($itemtype); $query = "SELECT `glpi_infocoms`.*,\n `{$itemtable}`.`name` AS name,\n `{$itemtable}`.`ticket_tco`,\n `glpi_entities`.`completename` AS entname,\n `glpi_entities`.`id` AS entID\n FROM `glpi_infocoms`\n INNER JOIN `{$itemtable}` ON (`{$itemtable}`.`id` = `glpi_infocoms`.`items_id`\n AND `glpi_infocoms`.`itemtype` = '{$itemtype}')\n LEFT JOIN `glpi_entities` ON (`{$itemtable}`.`entities_id` = `glpi_entities`.`id`)\n WHERE `{$itemtable}`.`is_template` = '0' " . getEntitiesRestrictRequest("AND", $itemtable); if (!empty($begin)) { $query .= " AND (`glpi_infocoms`.`buy_date` >= '{$begin}'\n OR `glpi_infocoms`.`use_date` >= '{$begin}') "; } if (!empty($end)) { $query .= " AND (`glpi_infocoms`.`buy_date` <= '{$end}'\n OR `glpi_infocoms`.`use_date` <= '{$end}') "; } $query .= " ORDER BY entname ASC, `buy_date`, `use_date`"; $display_entity = Session::isMultiEntitiesMode(); $result = $DB->query($query); if ($DB->numrows($result) > 0 && ($item = getItemForItemtype($itemtype))) { echo "<h2>" . $item->getTypeName(1) . "</h2>"; echo "<table class='tab_cadre'><tr><th>" . __('Name') . "</th>"; if ($display_entity) { echo "<th>" . __('Entity') . "</th>"; } echo "<th>" . _x('price', 'Value') . "</th><th>" . __('ANV') . "</th>"; echo "<th>" . __('TCO') . "</th><th>" . __('Date of purchase') . "</th>"; echo "<th>" . __('Startup date') . "</th><th>" . __('Warranty expiration date') . "</th></tr>"; $valeursoustot = 0; $valeurnettesoustot = 0; $valeurnettegraph = array(); $valeurgraph = array(); while ($line = $DB->fetch_assoc($result)) { if (isset($line["is_global"]) && $line["is_global"] && $item->getFromDB($line["items_id"])) { $line["value"] *= Computer_Item::countForItem($item); } if ($line["value"] > 0) { $valeursoustot += $line["value"]; } $valeurnette = Infocom::Amort($line["sink_type"], $line["value"], $line["sink_time"], $line["sink_coeff"], $line["buy_date"], $line["use_date"], $CFG_GLPI["date_tax"], "n"); $tmp = Infocom::Amort($line["sink_type"], $line["value"], $line["sink_time"], $line["sink_coeff"], $line["buy_date"], $line["use_date"], $CFG_GLPI["date_tax"], "all"); if (is_array($tmp) && count($tmp) > 0) { foreach ($tmp["annee"] as $key => $val) { if ($tmp["vcnetfin"][$key] > 0) { if (!isset($valeurnettegraph[$val])) { $valeurnettegraph[$val] = 0; } $valeurnettegraph[$val] += $tmp["vcnetdeb"][$key]; } } } if (!empty($line["buy_date"])) { $year = substr($line["buy_date"], 0, 4); if ($line["value"] > 0) { if (!isset($valeurgraph[$year])) { $valeurgraph[$year] = 0; } $valeurgraph[$year] += $line["value"]; } } $valeurnettesoustot += str_replace(" ", "", $valeurnette); echo "<tr class='tab_bg_1'><td>" . $line["name"] . "</td>"; if ($display_entity) { echo "<td>" . $line['entname'] . "</td>"; } echo "<td class='right'>" . Html::formatNumber($line["value"]) . "</td>" . "<td class='right'>" . Html::formatNumber($valeurnette) . "</td>" . "<td class='right'>" . Infocom::showTco($line["ticket_tco"], $line["value"]) . "</td>" . "<td>" . Html::convDate($line["buy_date"]) . "</td>" . "<td>" . Html::convDate($line["use_date"]) . "</td>" . "<td>" . Infocom::getWarrantyExpir($line["buy_date"], $line["warranty_duration"]) . "</td></tr>"; } $valeurtot += $valeursoustot; $valeurnettetot += $valeurnettesoustot; $tmpmsg = sprintf(__('Total: Value=%1$s - Account net value=%2$s'), Html::formatNumber($valeursoustot), Html::formatNumber($valeurnettesoustot)); echo "<tr><td colspan='6' class='center'><h3>{$tmpmsg}</h3></td></tr>"; if (count($valeurnettegraph) > 0) { echo "<tr><td colspan='5' class='center'>"; ksort($valeurnettegraph); $valeurnettegraphdisplay = array_map('round', $valeurnettegraph); foreach ($valeurnettegraph as $key => $val) { if (!isset($valeurnettegraphtot[$key])) { $valeurnettegraphtot[$key] = 0; } $valeurnettegraphtot[$key] += $valeurnettegraph[$key]; } Stat::showGraph(array(__('Account net value') => $valeurnettegraphdisplay), array('title' => __('Account net value'), 'width' => 400)); echo "</td></tr>"; } if (count($valeurgraph) > 0) { echo "<tr><td colspan='5' class='center'>"; ksort($valeurgraph); $valeurgraphdisplay = array_map('round', $valeurgraph); foreach ($valeurgraph as $key => $val) { if (!isset($valeurgraphtot[$key])) { $valeurgraphtot[$key] = 0; } $valeurgraphtot[$key] += $valeurgraph[$key]; } Stat::showGraph(array(_x('price', 'Value') => $valeurgraphdisplay), array('title' => _x('price', 'Value'), 'width' => 400)); echo "</td></tr>"; } echo "</table>"; return true; } return false; }
/** * @see CommonDBTM::doSpecificMassiveActions() **/ function doSpecificMassiveActions($input = array()) { $res = array('ok' => 0, 'ko' => 0, 'noright' => 0); switch ($input['action']) { case "connect": case "disconnect": $ci = new Computer_Item(); return $ci->doSpecificMassiveActions($input); default: return parent::doSpecificMassiveActions($input); } return $res; }
/** Display an infocom report * * @param $itemtype item type * @param $begin begin date * @param $end end date **/ function display_infocoms_report($itemtype, $begin, $end) { global $DB, $valeurtot, $valeurnettetot, $valeurnettegraphtot, $valeurgraphtot, $LANG, $CFG_GLPI; $itemtable = getTableForItemType($itemtype); $query = "SELECT `glpi_infocoms`.*,\n `{$itemtable}`.`name` AS name,\n `{$itemtable}`.`ticket_tco`,\n `glpi_entities`.`completename` AS entname,\n `glpi_entities`.`id` AS entID\n FROM `glpi_infocoms`\n INNER JOIN `{$itemtable}` ON (`{$itemtable}`.`id` = `glpi_infocoms`.`items_id`\n AND `glpi_infocoms`.`itemtype` = '{$itemtype}')\n LEFT JOIN `glpi_entities` ON (`{$itemtable}`.`entities_id` = `glpi_entities`.`id`)\n WHERE `{$itemtable}`.`is_template` = '0' " . getEntitiesRestrictRequest("AND", $itemtable); if (!empty($begin)) { $query .= " AND (`glpi_infocoms`.`buy_date` >= '{$begin}'\n OR `glpi_infocoms`.`use_date` >= '{$begin}') "; } if (!empty($end)) { $query .= " AND (`glpi_infocoms`.`buy_date` <= '{$end}'\n OR `glpi_infocoms`.`use_date` <= '{$end}') "; } $query .= " ORDER BY entname ASC, `buy_date`, `use_date`"; $display_entity = isMultiEntitiesMode(); $result = $DB->query($query); if ($DB->numrows($result) > 0) { $item = new $itemtype(); echo "<h2>" . $item->getTypeName() . "</h2>"; echo "<table class='tab_cadre'><tr><th>" . $LANG['common'][16] . "</th>"; if ($display_entity) { echo "<th>" . $LANG['entity'][0] . "</th>"; } echo "<th>" . $LANG['financial'][21] . "</th><th>" . $LANG['financial'][92] . "</th>"; echo "<th>" . $LANG['financial'][91] . "</th><th>" . $LANG['financial'][14] . "</th>"; echo "<th>" . $LANG['financial'][76] . "</th><th>" . $LANG['financial'][80] . "</th></tr>"; $valeursoustot = 0; $valeurnettesoustot = 0; $valeurnettegraph = array(); $valeurgraph = array(); while ($line = $DB->fetch_array($result)) { if (isset($line["is_global"]) && $line["is_global"]) { $line["value"] *= Computer_Item::countForItem($itemtype, $line["items_id"]); } if ($line["value"] > 0) { $valeursoustot += $line["value"]; } $valeurnette = Infocom::Amort($line["sink_type"], $line["value"], $line["sink_time"], $line["sink_coeff"], $line["buy_date"], $line["use_date"], $CFG_GLPI["date_tax"], "n"); $tmp = Infocom::Amort($line["sink_type"], $line["value"], $line["sink_time"], $line["sink_coeff"], $line["buy_date"], $line["use_date"], $CFG_GLPI["date_tax"], "all"); if (is_array($tmp) && count($tmp) > 0) { foreach ($tmp["annee"] as $key => $val) { if ($tmp["vcnetfin"][$key] > 0) { if (!isset($valeurnettegraph[$val])) { $valeurnettegraph[$val] = 0; } $valeurnettegraph[$val] += $tmp["vcnetdeb"][$key]; } } } if (!empty($line["buy_date"])) { $year = substr($line["buy_date"], 0, 4); if ($line["value"] > 0) { if (!isset($valeurgraph[$year])) { $valeurgraph[$year] = 0; } $valeurgraph[$year] += $line["value"]; } } $valeurnettesoustot += str_replace(" ", "", $valeurnette); echo "<tr class='tab_bg_1'><td>" . $line["name"] . "</td>"; if ($display_entity) { if ($line['entID'] == 0) { echo "<td>" . $LANG['entity'][2] . "</td>"; } else { echo "<td>" . $line['entname'] . "</td>"; } } echo "<td class='right'>" . formatNumber($line["value"]) . "</td><td class='right'>" . formatNumber($valeurnette) . "</td><td class='right'>" . Infocom::showTco($line["ticket_tco"], $line["value"]) . "</td><td>" . convDate($line["buy_date"]) . "</td><td>" . convDate($line["use_date"]) . "</td><td>" . getWarrantyExpir($line["buy_date"], $line["warranty_duration"]) . "</td></tr>"; } $valeurtot += $valeursoustot; $valeurnettetot += $valeurnettesoustot; echo "<tr><td colspan='6' class='center'><h3>" . $LANG['common'][33] . " : " . $LANG['financial'][21] . "=" . formatNumber($valeursoustot) . " - " . $LANG['financial'][81] . "=" . formatNumber($valeurnettesoustot) . "</h3></td></tr>"; if (count($valeurnettegraph) > 0) { echo "<tr><td colspan='5' class='center'>"; ksort($valeurnettegraph); $valeurnettegraphdisplay = array_map('round', $valeurnettegraph); foreach ($valeurnettegraph as $key => $val) { if (!isset($valeurnettegraphtot[$key])) { $valeurnettegraphtot[$key] = 0; } $valeurnettegraphtot[$key] += $valeurnettegraph[$key]; } Stat::showGraph(array($LANG['financial'][81] => $valeurnettegraphdisplay), array('title' => $LANG['financial'][81], 'width' => 400)); echo "</td></tr>"; } if (count($valeurgraph) > 0) { echo "<tr><td colspan='5' class='center'>"; ksort($valeurgraph); $valeurgraphdisplay = array_map('round', $valeurgraph); foreach ($valeurgraph as $key => $val) { if (!isset($valeurgraphtot[$key])) { $valeurgraphtot[$key] = 0; } $valeurgraphtot[$key] += $valeurgraph[$key]; } Stat::showGraph(array($LANG['financial'][21] => $valeurgraphdisplay), array('title' => $LANG['financial'][21], 'width' => 400)); echo "</td></tr>"; } echo "</table>"; return true; } return false; }
/** * Move direct connections from old printer to the new one * * @param $ID the old printer's id * @param $new_printers_id the new printer's id * * @return nothing **/ function moveDirectConnections($ID, $new_printers_id) { global $DB; $computeritem = new Computer_Item(); //For each direct connection of this printer foreach (getAllDatasFromTable("glpi_computers_items", "`itemtype` = 'Printer'\n AND `items_id` = '{$ID}'") as $connection) { //Direct connection exists in the target printer ? if (!countElementsInTable("glpi_computers_items", "`itemtype` = 'Printer'\n AND `items_id` = '{$new_printers_id}'\n AND `computers_id`='" . $connection["computers_id"] . "'")) { //Direct connection doesn't exists in the target printer : move it $computeritem->update(array('id' => $connection['id'], 'items_id' => $new_printers_id)); } else { //Direct connection already exists in the target printer : delete it $computeritem->delete($connection); } } }
$phone->restore($_POST); Event::log($_POST["id"], "phones", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][23]); $phone->redirectToList(); } else { if (isset($_REQUEST["purge"])) { $phone->check($_REQUEST["id"], 'd'); $phone->delete($_REQUEST, 1); Event::log($_REQUEST["id"], "phones", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][24]); $phone->redirectToList(); } else { if (isset($_POST["update"])) { $phone->check($_POST["id"], 'w'); $phone->update($_POST); Event::log($_POST["id"], "phones", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][21]); glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_GET["unglobalize"])) { $phone->check($_GET["id"], 'w'); Computer_Item::unglobalizeItem($phone); Event::log($_GET["id"], "phones", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][60]); glpi_header($CFG_GLPI["root_doc"] . "/front/phone.form.php?id=" . $_GET["id"]); } else { commonHeader($LANG['help'][35], $_SERVER['PHP_SELF'], "inventory", "phone"); $phone->showForm($_GET["id"], array('withtemplate' => $_GET["withtemplate"])); commonFooter(); } } } } } }
function cleanDBonPurge() { $csv = new Computer_SoftwareVersion(); $csv->cleanDBonItemDelete('Computer', $this->fields['id']); $csl = new Computer_SoftwareLicense(); $csl->cleanDBonItemDelete('Computer', $this->fields['id']); $ip = new Item_Problem(); $ip->cleanDBonItemDelete('Computer', $this->fields['id']); $ci = new Change_Item(); $ci->cleanDBonItemDelete('Computer', $this->fields['id']); $ip = new Item_Project(); $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ci = new Computer_Item(); $ci->cleanDBonItemDelete('Computer', $this->fields['id']); Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'], !empty($this->input['keep_devices'])); $disk = new ComputerDisk(); $disk->cleanDBonItemDelete('Computer', $this->fields['id']); $vm = new ComputerVirtualMachine(); $vm->cleanDBonItemDelete('Computer', $this->fields['id']); }
/** * * Import peripherals from OCS * @since 1.0 * @param $cfg_ocs OCSNG mode configuration * @param $computers_id computer's id in GLPI * @param $ocsid computer's id in OCS * @param $ocsservers_id OCS server id * @param $entity the entity in which the peripheral will be created * @param $dohistory record in history link between peripheral and computer */ static function importPeripheral($cfg_ocs, $computers_id, $ocsservers_id, $ocsid, $entity, $dohistory) { global $PluginOcsinventoryngDBocs, $DB; self::checkOCSconnection($ocsservers_id); if ($cfg_ocs["import_periph"]) { $already_processed = array(); $p = new Peripheral(); $conn = new Computer_Item(); $query = "SELECT DISTINCT `CAPTION`, `MANUFACTURER`, `INTERFACE`, `TYPE`\n FROM `inputs`\n WHERE `HARDWARE_ID` = '{$ocsid}'\n AND `CAPTION` <> ''"; $result = $PluginOcsinventoryngDBocs->query($query); if ($PluginOcsinventoryngDBocs->numrows($result) > 0) { while ($line = $PluginOcsinventoryngDBocs->fetch_array($result)) { $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line)); $periph = array(); $periph["name"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["CAPTION"]); //Look for a monitor with the same name (and serial if possible) already connected //to this computer $query = "SELECT `p`.`id`, `gci`.`is_deleted`\n FROM `glpi_printers` as `p`, `glpi_computers_items` as `gci`\n WHERE `p`.`id` = `gci`.`items_id`\n AND `gci`.`is_dynamic`='1'\n AND `computers_id`='{$computers_id}'\n AND `itemtype`='Peripheral'\n AND `p`.`name`='" . $periph["name"] . "'"; $results = $DB->query($query); $id = false; $lock = false; if ($DB->numrows($results) > 0) { $id = $DB->result($results, 0, 'id'); $lock = $DB->result($results, 0, 'is_deleted'); } if (!$id) { // Clean peripheral object $p->reset(); if ($line["MANUFACTURER"] != "NULL") { $periph["brand"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["MANUFACTURER"]); } if ($line["INTERFACE"] != "NULL") { $periph["comment"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["INTERFACE"]); } $periph["peripheraltypes_id"] = Dropdown::importExternal('PeripheralType', $line["TYPE"]); $id_periph = 0; if ($cfg_ocs["import_periph"] == 1) { //Config says : manage peripherals as global //check if peripherals already exists in GLPI $periph["is_global"] = 1; $query = "SELECT `id`\n FROM `glpi_peripherals`\n WHERE `name` = '" . $periph["name"] . "'\n AND `is_global` = '1'\n AND `entities_id` = '{$entity}'"; $result_search = $DB->query($query); if ($DB->numrows($result_search) > 0) { //Periph is already in GLPI //Do not import anything just get periph ID for link $id_periph = $DB->result($result_search, 0, "id"); } else { $input = $periph; if ($cfg_ocs["states_id_default"] > 0) { $input["states_id"] = $cfg_ocs["states_id_default"]; } $input["entities_id"] = $entity; $id_periph = $p->add($input); } } else { if ($cfg_ocs["import_periph"] == 2) { //Config says : manage peripherals as single units //Import all peripherals as non global. $input = $periph; $input["is_global"] = 0; if ($cfg_ocs["states_id_default"] > 0) { $input["states_id"] = $cfg_ocs["states_id_default"]; } $input["entities_id"] = $entity; $id_periph = $p->add($input); } } if ($id_periph) { $already_processed[] = $id_periph; $conn = new Computer_Item(); if ($connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Peripheral', 'items_id' => $id_periph, '_no_history' => !$dohistory, 'is_dynamic' => 1))) { //Update column "is_deleted" set value to 0 and set status to default $input = array(); $input["id"] = $id_periph; $input["is_deleted"] = 0; $input["entities_id"] = $entity; if ($cfg_ocs["states_id_default"] > 0) { $input["states_id"] = $cfg_ocs["states_id_default"]; } $p->update($input); } } } else { $already_processed[] = $id; } } } //Look for all monitors, not locked, not linked to the computer anymore $query = "SELECT `id`\n FROM `glpi_computers_items`\n WHERE `itemtype`='Peripheral'\n AND `computers_id`='{$computers_id}'\n AND `is_dynamic`='1'\n AND `is_deleted`='0'"; if (!empty($already_processed)) { $query .= "AND `items_id` NOT IN (" . implode(',', $already_processed) . ")"; } foreach ($DB->request($query) as $data) { //Delete all connexions $conn->delete(array('id' => $data['id'], '_ocsservers_id' => $ocsservers_id), true); } } }
/** * Delete direct connection for a linked item * * @param $itemtype original type of transfered item * @param $ID ID of the item * @param $link_type type of the linked items to transfer * @param $ocs_computer if computer type OCS ID of the item if available **/ function transferDirectConnection($itemtype, $ID, $link_type, $ocs_computer = false) { global $DB; // Only same Item case : no duplication of computers // Default : delete $keep = 0; $clean = 0; $ocs_field = ""; switch ($link_type) { case 'Printer': $keep = $this->options['keep_dc_printer']; $clean = $this->options['clean_dc_printer']; $ocs_field = "import_printer"; break; case 'Monitor': $keep = $this->options['keep_dc_monitor']; $clean = $this->options['clean_dc_monitor']; $ocs_field = "import_monitor"; break; case 'Peripheral': $keep = $this->options['keep_dc_peripheral']; $clean = $this->options['clean_dc_peripheral']; $ocs_field = "import_peripheral"; break; case 'Phone': $keep = $this->options['keep_dc_phone']; $clean = $this->options['clean_dc_phone']; break; } if (!class_exists($link_type)) { continue; } $link_item = new $link_type(); // Get connections $query = "SELECT *\n FROM `glpi_computers_items`\n WHERE `computers_id` = '{$ID}'\n AND `itemtype` = '" . $link_type . "'"; if ($link_item->maybeRecursive()) { $query .= " AND `items_id` NOT IN " . $this->item_recurs[$link_type]; } if ($result = $DB->query($query)) { if ($DB->numrows($result) != 0) { // Foreach get item while ($data = $DB->fetch_array($result)) { $item_ID = $data['items_id']; if ($link_item->getFromDB($item_ID)) { // If global : if ($link_item->fields['is_global'] == 1) { $need_clean_process = false; // if keep if ($keep) { $newID = -1; // Is already transfer ? if (isset($this->already_transfer[$link_type][$item_ID])) { $newID = $this->already_transfer[$link_type][$item_ID]; // Already transfer as a copy : need clean process if ($newID != $item_ID) { $need_clean_process = true; } } else { // Not yet tranfer // Can be managed like a non global one ? // = all linked computers need to be transfer (so not copy) $query = "SELECT count(*) AS CPT\n FROM `glpi_computers_items`\n WHERE `itemtype` = '" . $link_type . "'\n AND `items_id` = '{$item_ID}'\n AND `computers_id`\n NOT IN " . $this->item_search['Computer']; $result_search = $DB->query($query); // All linked computers need to be transfer -> use unique transfer system if ($DB->result($result_search, 0, 'CPT') == 0) { $need_clean_process = false; $this->transferItem($link_type, $item_ID, $item_ID); $newID = $item_ID; } else { // else Transfer by Copy $need_clean_process = true; // Is existing global item in the destination entity ? $query = "SELECT *\n FROM `" . getTableForItemType($link_type) . "`\n WHERE `is_global` = '1'\n AND `entities_id` = '" . $this->to . "'\n AND `name`\n = '" . addslashes($link_item->getField('name')) . "'"; if ($result_search = $DB->query($query)) { if ($DB->numrows($result_search) > 0) { $newID = $DB->result($result_search, 0, 'id'); $this->addToAlreadyTransfer($link_type, $item_ID, $newID); } } // Not found -> transfer copy if ($newID < 0) { // 1 - create new item unset($link_item->fields['id']); $input = $link_item->fields; $input['entities_id'] = $this->to; unset($link_item->fields); $newID = $link_item->add($input); // 2 - transfer as copy $this->transferItem($link_type, $item_ID, $newID); } // Founded -> use to link : nothing to do } } // Finish updated link if needed if ($newID > 0 && $newID != $item_ID) { $query = "UPDATE `glpi_computers_items`\n SET `items_id` = '{$newID}'\n WHERE `id` = '" . $data['id'] . "' "; $DB->query($query); } } else { // Else delete link // Call Disconnect for global device (no disconnect behavior, but history ) $conn = new Computer_Item(); $conn->delete(array('id' => $data['id'], '_no_auto_action' => true)); $need_clean_process = true; // OCS clean link if ($ocs_computer && !empty($ocs_field)) { $query = "UPDATE `glpi_ocslinks`\n SET `{$ocs_field}` = NULL\n WHERE `computers_id` = '{$ID}'"; $DB->query($query); } } // If clean and not linked dc -> delete if ($need_clean_process && $clean) { $query = "SELECT COUNT(*) AS CPT\n FROM `glpi_computers_items`\n WHERE `items_id` = '{$item_ID}'\n AND `itemtype` = '" . $link_type . "'"; if ($result_dc = $DB->query($query)) { if ($DB->result($result_dc, 0, 'CPT') == 0) { if ($clean == 1) { $link_item->delete(array('id' => $item_ID)); } if ($clean == 2) { // purge $link_item->delete(array('id' => $item_ID), 1); } } } } } else { // If unique : //if keep -> transfer list else unlink if ($keep) { $this->transferItem($link_type, $item_ID, $item_ID); } else { // Else delete link (apply disconnect behavior) $conn = new Computer_Item(); $conn->delete(array('id' => $data['id'])); //if clean -> delete if ($clean == 1) { $link_item->delete(array('id' => $item_ID)); } else { if ($clean == 2) { // purge $link_item->delete(array('id' => $item_ID), 1); } } if ($ocs_computer && !empty($ocs_field)) { $query = "UPDATE `glpi_ocslinks`\n SET `{$ocs_field}` = NULL\n WHERE `computers_id` = '{$ID}'"; $DB->query($query); } } } } else { // Unexisting item / Force disconnect $conn = new Computer_Item(); $conn->delete(array('id' => $data['id'], '_no_history' => true, '_no_auto_action' => true)); } } } } }
/** * if Computer_Item deleted * * @param $comp Computer_Item object **/ static function purgeComputer_Item(Computer_Item $comp) { global $DB; if ($device = getItemForItemtype($comp->fields['itemtype'])) { if ($device->getFromDB($comp->fields['items_id'])) { if (isset($comp->input['_ocsservers_id'])) { $ocsservers_id = $comp->input['_ocsservers_id']; } else { $ocsservers_id = PluginOcsinventoryngOcsServer::getByMachineID($comp->fields['computers_id']); } if ($ocsservers_id > 0) { //Get OCS configuration $ocs_config = PluginOcsinventoryngOcsServer::getConfig($ocsservers_id); //Get the management mode for this device $mode = PluginOcsinventoryngOcsServer::getDevicesManagementMode($ocs_config, $comp->fields['itemtype']); $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") { // $tmp["id"] = $comp->fields['items_id']; // $device->delete(array('id' => $tmp['id']), 1); // Put periph in dustbin // } else if ($decoConf == "trash") { // $tmp["id"] = $comp->fields['items_id']; // $device->delete(array('id' => $tmp['id']), 0); // } if ($decoConf == "delete") { $tmp["id"] = $comp->getID(); $query = "DELETE\n FROM `glpi_computers_items`\n WHERE `id`='" . $tmp['id'] . "'"; $result = $DB->query($query); //Put periph in dustbin } else { if ($decoConf == "trash") { $tmp["id"] = $comp->getID(); $query = "UPDATE\n `glpi_computers_items`\n\t\t\t\t\t\t SET `is_deleted` = 1\n WHERE `id`='" . $tmp['id'] . "'"; $result = $DB->query($query); } } } } // $ocsservers_id>0 } } }