Change the Progress Bar Position
static public changeProgressBarPosition ( $crt, $tot, $msg = "" ) : nothing | ||
$crt | Current Value (less then $max) | |
$tot | Maximum Value | |
$msg | message inside the bar (default is %) (default '') | |
return | nothing |
/** * @see RuleCollection::replayRulesOnExistingDB() **/ function replayRulesOnExistingDB($offset = 0, $maxtime = 0, $items = array(), $params = array()) { global $DB; if (isCommandLine()) { echo "replayRulesOnExistingDB started : " . date("r") . "\n"; } $nb = 0; $i = $offset; if (count($items) == 0) { //Select all the differents software $sql = "SELECT DISTINCT `glpi_softwares`.`name`,\n `glpi_manufacturers`.`name` AS manufacturer,\n `glpi_softwares`.`manufacturers_id` AS manufacturers_id,\n `glpi_softwares`.`entities_id` AS entities_id,\n `glpi_softwares`.`is_helpdesk_visible` AS helpdesk\n FROM `glpi_softwares`\n LEFT JOIN `glpi_manufacturers`\n ON (`glpi_manufacturers`.`id` = `glpi_softwares`.`manufacturers_id`)"; // Do not replay on dustbin and templates $sql .= "WHERE `glpi_softwares`.`is_deleted` = '0'\n AND `glpi_softwares`.`is_template` = '0' "; if (isset($params['manufacturer']) && $params['manufacturer']) { $sql .= " AND `glpi_softwares`.`manufacturers_id` = '" . $params['manufacturer'] . "'"; } if ($offset) { $sql .= " LIMIT " . intval($offset) . ",999999999"; } $res = $DB->query($sql); $nb = $DB->numrows($res) + $offset; $step = $nb > 1000 ? 50 : ($nb > 20 ? floor($DB->numrows($res) / 20) : 1); while ($input = $DB->fetch_assoc($res)) { if (!($i % $step)) { if (isCommandLine()) { printf(__('%1$s - replay rules on existing database: %2$s/%3$s (%4$s Mio)') . "\n", date("H:i:s"), $i, $nb, round(memory_get_usage() / (1024 * 1024), 2)); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } } //If manufacturer is set, then first run the manufacturer's dictionnary if (isset($input["manufacturer"])) { $input["manufacturer"] = Manufacturer::processName(addslashes($input["manufacturer"])); } //Replay software dictionnary rules $res_rule = $this->processAllRules($input, array(), array()); if (isset($res_rule["name"]) && $res_rule["name"] != $input["name"] || isset($res_rule["version"]) && $res_rule["version"] != '' || isset($res_rule['new_entities_id']) && $res_rule['new_entities_id'] != $input['entities_id'] || isset($res_rule['is_helpdesk_visible']) && $res_rule['is_helpdesk_visible'] != $input['helpdesk'] || isset($res_rule['manufacturer']) && $res_rule['manufacturer'] != $input['manufacturer']) { $IDs = array(); //Find all the softwares in the database with the same name and manufacturer $sql = "SELECT `id`\n FROM `glpi_softwares`\n WHERE `name` = '" . $input["name"] . "'\n AND `manufacturers_id` = '" . $input["manufacturers_id"] . "'"; $res_soft = $DB->query($sql); if ($DB->numrows($res_soft) > 0) { //Store all the software's IDs in an array while ($result = $DB->fetch_assoc($res_soft)) { $IDs[] = $result["id"]; } //Replay dictionnary on all the softwares $this->replayDictionnaryOnSoftwaresByID($IDs, $res_rule); } } $i++; if ($maxtime) { $crt = explode(" ", microtime()); if ($crt[0] + $crt[1] > $maxtime) { break; } } } // each distinct software if (isCommandLine()) { printf(__('Replay rules on existing database: %1$s/%2$s') . " \n", $i, $nb); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } } else { $this->replayDictionnaryOnSoftwaresByID($items); return true; } if (isCommandLine()) { printf(__('Replay rules on existing database ended on %s') . "\n", date("r")); } return $i == $nb ? -1 : $i; }
/** * Merge softwares with current * * @param $item array of software ID to be merged * * @return boolean about success **/ function merge($item) { global $DB; $ID = $this->getField('id'); echo "<div class='center'>"; echo "<table class='tab_cadrehov'><tr><th>" . __('Merging') . "</th></tr>"; echo "<tr class='tab_bg_2'><td>"; Html::createProgressBar(__('Work in progress...')); echo "</td></tr></table></div>\n"; $item = array_keys($item); // Search for software version $req = $DB->request("glpi_softwareversions", array("softwares_id" => $item)); $i = 0; if ($nb = $req->numrows()) { foreach ($req as $from) { $found = false; foreach ($DB->request("glpi_softwareversions", array("softwares_id" => $ID, "name" => $from["name"])) as $dest) { // Update version ID on License $sql = "UPDATE `glpi_softwarelicenses`\n SET `softwareversions_id_buy` = '" . $dest["id"] . "'\n WHERE `softwareversions_id_buy` = '" . $from["id"] . "'"; $DB->query($sql); $sql = "UPDATE `glpi_softwarelicenses`\n SET `softwareversions_id_use` = '" . $dest["id"] . "'\n WHERE `softwareversions_id_use` = '" . $from["id"] . "'"; $DB->query($sql); // Move installation to existing version in destination software $sql = "UPDATE `glpi_computers_softwareversions`\n SET `softwareversions_id` = '" . $dest["id"] . "'\n WHERE `softwareversions_id` = '" . $from["id"] . "'"; $found = $DB->query($sql); } if ($found) { // Installation has be moved, delete the source version $sql = "DELETE\n FROM `glpi_softwareversions`\n WHERE `id` = '" . $from["id"] . "'"; } else { // Move version to destination software $sql = "UPDATE `glpi_softwareversions`\n SET `softwares_id` = '{$ID}',\n `entities_id` = '" . $this->getField('entities_id') . "'\n WHERE `id` = '" . $from["id"] . "'"; } if ($DB->query($sql)) { $i++; } Html::changeProgressBarPosition($i, $nb + 1); } } // Move software license $sql = "UPDATE `glpi_softwarelicenses`\n SET `softwares_id` = '{$ID}'\n WHERE `softwares_id` IN ('" . implode("','", $item) . "')"; if ($DB->query($sql)) { $i++; } if ($i == $nb + 1) { //error_log ("All merge operations ok."); $soft = new self(); foreach ($item as $old) { $soft->putInTrash($old, __('Software deleted after merging')); } } Html::changeProgressBarPosition($i, $nb + 1, __('Task completed.')); return $i == $nb + 1; }
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>"; }
/** * @see RuleCollection::replayRulesOnExistingDB() **/ function replayRulesOnExistingDB($offset = 0, $maxtime = 0, $items = array(), $params = array()) { global $DB; if (isCommandLine()) { printf(__('Replay rules on existing database started on %s') . "\n", date("r")); } $nb = 0; $i = $offset; //Select all the differents software $sql = "SELECT DISTINCT `glpi_printers`.`name`,\n `glpi_manufacturers`.`name` AS manufacturer,\n `glpi_printers`.`manufacturers_id` AS manufacturers_id,\n `glpi_printers`.`comment` AS comment\n FROM `glpi_printers`\n LEFT JOIN `glpi_manufacturers`\n ON (`glpi_manufacturers`.`id` = `glpi_printers`.`manufacturers_id`) "; // Do not replay on dustbin and templates $sql .= "WHERE `glpi_printers`.`is_deleted` = '0'\n AND `glpi_printers`.`is_template` = '0' "; if ($offset) { $sql .= " LIMIT " . intval($offset) . ",999999999"; } $res = $DB->query($sql); $nb = $DB->numrows($res) + $offset; $step = $nb > 1000 ? 50 : ($nb > 20 ? floor($DB->numrows($res) / 20) : 1); while ($input = $DB->fetch_assoc($res)) { if (!($i % $step)) { if (isCommandLine()) { //TRANS: %1$s is a date, %2$s is a row, %3$s is total row, %4$s is memory printf(__('%1$s - replay rules on existing database: %2$s/%3$s (%4$s Mio)') . "\n", date("H:i:s"), $i, $nb, round(memory_get_usage() / (1024 * 1024), 2)); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } } //Replay printer dictionnary rules $res_rule = $this->processAllRules($input, array(), array()); foreach (array('manufacturer', 'is_global', 'name') as $attr) { if (isset($res_rule[$attr]) && $res_rule[$attr] == '') { unset($res_rule[$attr]); } } //If the software's name or version has changed if (self::somethingHasChanged($res_rule, $input)) { $IDs = array(); //Find all the printers in the database with the same name and manufacturer $sql = "SELECT `id`\n FROM `glpi_printers`\n WHERE `name` = '" . $input["name"] . "'\n AND `manufacturers_id` = '" . $input["manufacturers_id"] . "'"; $res_printer = $DB->query($sql); if ($DB->numrows($res_printer) > 0) { //Store all the printer's IDs in an array while ($result = $DB->fetch_assoc($res_printer)) { $IDs[] = $result["id"]; } //Replay dictionnary on all the printers $this->replayDictionnaryOnPrintersByID($IDs, $res_rule); } } $i++; if ($maxtime) { $crt = explode(" ", microtime()); if ($crt[0] + $crt[1] > $maxtime) { break; } } } if (isCommandLine()) { printf(__('Replay rules on existing database: %1$s/%2$s') . "\n", $i, $nb); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } if (isCommandLine()) { printf(__('Replay rules on existing database ended on %s') . "\n", date("r")); } return $i == $nb ? -1 : $i; }
/** * @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>"; }
/** * Replay collection rules on an existing DB for model dropdowns * * @param $offset offset used to begin (default 0) * @param $maxtime maximum time of process (reload at the end) (default 0) * * @return -1 on completion else current offset **/ function replayRulesOnExistingDBForModel($offset = 0, $maxtime = 0) { global $DB; if (isCommandLine()) { printf(__('Replay rules on existing database started on %s') . "\n", date("r")); } // Model check : need to check using manufacturer extra data if (strpos($this->item_table, 'models') === false) { _e('Error replaying rules'); return false; } $model_table = getPlural(str_replace('models', '', $this->item_table)); $model_field = getForeignKeyFieldForTable($this->item_table); // Need to give manufacturer from item table $Sql = "SELECT DISTINCT `glpi_manufacturers`.`id` AS idmanu,\n `glpi_manufacturers`.`name` AS manufacturer,\n `" . $this->item_table . "`.`id`,\n `" . $this->item_table . "`.`name` AS name,\n `" . $this->item_table . "`.`comment`\n FROM `" . $this->item_table . "`,\n `{$model_table}`\n LEFT JOIN `glpi_manufacturers`\n ON (`{$model_table}`.`manufacturers_id` = `glpi_manufacturers`.`id`)\n WHERE `{$model_table}`.`{$model_field}` = `" . $this->item_table . "`.`id`"; if ($offset) { $Sql .= " LIMIT " . intval($offset) . ",999999999"; } $result = $DB->query($Sql); $nb = $DB->numrows($result) + $offset; $i = $offset; if ($result && $nb > $offset) { // Step to refresh progressbar $step = $nb > 20 ? floor($nb / 20) : 1; $tocheck = array(); while ($data = $DB->fetch_assoc($result)) { if (!($i % $step)) { if (isCommandLine()) { printf(__('Replay rules on existing database: %1$s/%2$s') . "\r", $i, $nb); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } } // Model case if (isset($data["manufacturer"])) { $data["manufacturer"] = Manufacturer::processName(addslashes($data["manufacturer"])); } //Replay Type dictionnary $ID = Dropdown::importExternal(getItemTypeForTable($this->item_table), addslashes($data["name"]), -1, $data, addslashes($data["comment"])); if ($data['id'] != $ID) { $tocheck[$data["id"]][] = $ID; $sql = "UPDATE `{$model_table}`\n SET `{$model_field}` = '{$ID}'\n WHERE `{$model_field}` = '" . $data['id'] . "'"; if (empty($data['idmanu'])) { $sql .= " AND (`manufacturers_id` IS NULL\n OR `manufacturers_id` = '0')"; } else { $sql .= " AND `manufacturers_id` = '" . $data['idmanu'] . "'"; } $DB->query($sql); } $i++; if ($maxtime) { $crt = explode(" ", microtime()); if ($crt[0] + $crt[1] > $maxtime) { break; } } } foreach ($tocheck as $ID => $tab) { $sql = "SELECT COUNT(*)\n FROM `{$model_table}`\n WHERE `{$model_field}` = '{$ID}'"; $result = $DB->query($sql); $deletecartmodel = false; // No item left : delete old item if ($result && $DB->result($result, 0, 0) == 0) { $Sql = "DELETE\n FROM `" . $this->item_table . "`\n WHERE `id` = '{$ID}'"; $resdel = $DB->query($Sql); $deletecartmodel = true; } // Manage cartridge assoc Update items if ($this->getRuleClassName() == 'RuleDictionnaryPrinterModel') { $sql = "SELECT *\n FROM `glpi_cartridgeitems_printermodels`\n WHERE `printermodels_id` = '{$ID}'"; if ($result = $DB->query($sql)) { if ($DB->numrows($result)) { // Get compatible cartridge type $carttype = array(); while ($data = $DB->fetch_assoc($result)) { $carttype[] = $data['cartridgeitems_id']; } // Delete cartrodges_assoc if ($deletecartmodel) { $sql = "DELETE\n FROM `glpi_cartridgeitems_printermodels`\n WHERE `printermodels_id` = 'id'"; $DB->query($sql); } // Add new assoc $ct = new CartridgeItem(); foreach ($carttype as $cartID) { foreach ($tab as $model) { $ct->addCompatibleType($cartID, $model); } } } } } } // each tocheck } if (isCommandLine()) { printf(__('Replay rules on existing database ended on %s') . "\n", date("r")); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } return $i == $nb ? -1 : $i; }
/** * @since version 0.84 * * @see CommonDBTM::doSpecificMassiveActions() **/ function doSpecificMassiveActions($input = array()) { global $CFG_GLPI; $res = array('ok' => 0, 'ko' => 0, 'noright' => 0); switch ($input['action']) { case "import": case "sync": if (!Session::haveRight("import_externalauth_users", 'w')) { $res['nbnoright']++; } else { if (isset($_GET['multiple_actions']) && isset($_SESSION["glpi_massiveaction"])) { if ($count = count($input["item"])) { $i = $input["ldap_process_count"] - $count + 1; Html::createProgressBar(); Html::changeProgressBarPosition($i, $input["ldap_process_count"], sprintf(__('%1$s/%2$s'), $i, $input["ldap_process_count"])); $key = key($input["item"]); unset($input["item"][$key]); if (AuthLdap::ldapImportUserByServerId(array('method' => AuthLDAP::IDENTIFIER_LOGIN, 'value' => $key), $input["mode"], $input["authldaps_id"], true)) { $input['res']['ok']++; } else { $input['res']['ko']++; } if (count($input["item"])) { // more to do -> redirect $_SESSION['glpi_massiveaction']['POST'] = $input; Html::redirect($CFG_GLPI['root_doc'] . '/front/massiveaction.php?multiple_actions=1'); } else { // Nothing to do redirect Html::changeProgressBarPosition(100, 100, __('Successful importation')); $res = $input['res']; $_SESSION['ldap_import']['action'] = 'show'; } } } else { if (count($input['item']) > 0) { $input["ldap_process_count"] = 0; $input["authldaps_id"] = $_SESSION['ldap_import']['authldaps_id']; $input["mode"] = $_SESSION['ldap_import']['mode']; $input['res'] = array('ok' => 0, 'ko' => 0, 'noright' => 0); foreach ($input['item'] as $key => $val) { if ($val) { $input["ldap_process_count"]++; } } $_SESSION['glpi_massiveaction']['POST'] = $input; Html::redirect($CFG_GLPI['root_doc'] . '/front/massiveaction.php?multiple_actions=1'); } else { $res['ko']++; } } } $res['REDIRECT'] = $CFG_GLPI['root_doc'] . "/front/ldap.import.php"; break; case "import_group": $group = new Group(); if (!Session::haveRight("user_authtype", 'w') || !$group->canGlobal('w')) { $res['nbnoright']++; } else { if (isset($_GET['multiple_actions']) && isset($_SESSION["glpi_massiveaction"])) { if ($count = count($input["item"])) { $i = $input["ldap_process_count"] - $count + 1; Html::createProgressBar(); Html::changeProgressBarPosition($i, $input["ldap_process_count"], sprintf(__('%1$s/%2$s'), $i, $input["ldap_process_count"])); $key = key($input["item"]); unset($input["item"][$key]); if (isset($input["ldap_import_entities"][$key])) { $entity = $input["ldap_import_entities"][$key]; } else { $entity = $_SESSION["glpiactive_entity"]; } if (AuthLdap::ldapImportGroup($key, array("authldaps_id" => $input["authldaps_id"], "entities_id" => $entity, "is_recursive" => $input["ldap_import_recursive"][$key], "type" => $input["ldap_import_type"][$key]))) { $input['res']['ok']++; } else { $input['res']['ko']++; } if (count($input["item"])) { // more to do -> redirect $_SESSION['glpi_massiveaction']['POST'] = $input; Html::redirect($CFG_GLPI['root_doc'] . '/front/massiveaction.php?multiple_actions=1'); } else { // Nothing to do redirect Html::changeProgressBarPosition(100, 100, __('Successful importation')); $res = $input['res']; $_SESSION['ldap_import']['action'] = 'show'; } } } else { if (count($input['item']) > 0) { $input["ldap_process_count"] = 0; $input["authldaps_id"] = $_SESSION['ldap_server']; $input['res'] = array('ok' => 0, 'ko' => 0, 'noright' => 0); foreach ($input['item'] as $key => $val) { if ($val) { $input["ldap_process_count"]++; $input["ldap_import_entities"][$key] = $input["ldap_import_entities"][$key]; $input["ldap_import_type"][$key] = $input["ldap_import_type"][$key]; $input["ldap_import_recursive"][$key] = $input["ldap_import_recursive"][$key]; } } $_SESSION['glpi_massiveaction']['POST'] = $input; Html::redirect($CFG_GLPI['root_doc'] . '/front/massiveaction.php?multiple_actions=1'); } else { $res['ko']++; } } } $res['REDIRECT'] = $CFG_GLPI['root_doc'] . "/front/ldap.group.import.php"; break; default: return parent::doSpecificMassiveActions($input); } return $res; }
function process($action, $objectId, $actionId, $entities, $date, $test = false) { global $DB; $nb = 0; $res = array('ok' => 0, 'ko' => 0); // Pas de traitement si sous requète if ($action == PluginUtilitairesUtilitaire::TEST || $action == PluginUtilitairesUtilitaire::LINK) { if (!$this->isSubQuery) { if (!$this->parent) { echo "<div align='center'>"; echo "<table class='tab_cadre_fixe' cellpadding='5'>"; echo "<colgroup>"; echo "<col width='200px' align='left' style='font:bold'>"; echo "<col width='60px' align='right'>"; echo "<tr><th colspan=2 align=center>" . __('Records to process', 'utilitaires') . "</th></tr>"; echo "<tr><th colspan=2 align=center>" . $this->title . "</th></tr>"; } foreach ($this->children as $child) { $child->process($action, $objectId, $actionId, $entities, $date, $test); } $query = $this->select($action) . $this->from() . $this->where(); //echo "<pre>".print_r($query)."</pre>"; switch ($action) { case PluginUtilitairesUtilitaire::TEST: $result = $DB->query($query) or die($DB->error()); if ($DB->numrows($result) != 0) { $line = $DB->fetch_array($result); $nb += $line["NB"]; if ($nb > 0) { echo "<tr class='tab_bg_1'>"; echo "<td title='" . $query . "'>" . $this->table . "</td><td class='center'>" . $line['NB'] . "</td>"; } } break; case PluginUtilitairesUtilitaire::LINK: if ($result = $DB->query($query)) { return 1; } else { return 0; } break; } if (!$this->parent) { echo "<tr class='tab_bg_2'>"; if ($nb > 0) { echo "<td>" . __('Total') . "</td><td class='b center'>" . $nb . "</td>"; } else { echo "<td colspan='2' class='center'>"; echo "<div class='red'>" . __('Nothing to treat', 'utilitaires') . "</div>"; echo "</td>"; } echo "</tr>"; echo "</table></div><br>"; } } } else { if ($action == PluginUtilitairesUtilitaire::TRUNCATE) { if (!$this->isSubQuery) { if (!$this->parent) { echo "<div align='center'>"; echo "<table class='tab_cadre_fixe' cellpadding='5'>"; echo "<colgroup>"; echo "<col width='200px' align='left' style='font:bold'>"; echo "<col width='60px' align='right'>"; echo "<tr><th colspan=2 align=center>" . __('Records to process', 'utilitaires') . "</th></tr>"; echo "<tr><th colspan=2 align=center>" . $this->title . "</th></tr>"; } foreach ($this->children as $child) { $child->process($action, $objectId, $actionId, $entities, $date, $test); } if ($test) { $action = PluginUtilitairesUtilitaire::TEST; } $query = $this->select($action) . $this->from(); //.$this->where() //echo "<pre>".print_r($query)."</pre>"; if ($result = $DB->query($query)) { if ($test) { if ($DB->numrows($result) != 0) { $line = $DB->fetch_array($result); $nb += $line["NB"]; if ($nb > 0) { echo "<tr class='tab_bg_1'>"; echo "<td title='" . $query . "'>" . $this->table . "</td><td class='center'>" . $line['NB'] . "</td>"; } } if (!$this->parent) { echo "<tr class='tab_bg_2'>"; if ($nb > 0) { echo "<td>" . __('Total') . "</td><td class='b center'>" . $nb . "</td>"; } else { echo "<td colspan='2' class='center'>"; echo "<div class='red'>" . __('Nothing to treat', 'utilitaires') . "</div>"; echo "</td>"; } echo "</tr>"; echo "</table></div><br>"; } } else { return 1; } } } } else { if ($action == PluginUtilitairesUtilitaire::TODO) { $object = new $objectId(); $objecttable = getTableForItemType($objectId); $restrict = "1 = 1"; if ($object->maybeTemplate()) { $restrict .= " AND `is_template` = '0'"; } if ($actionId == PluginUtilitairesUtilitaire::PURGE_ACTION) { $restrict .= " AND `is_deleted` = '1'"; } if ($actionId == PluginUtilitairesUtilitaire::DELETE_DELAY) { $restrict .= " AND `status` = '" . CommonITILObject::CLOSED . "'\n AND (`closedate` < '" . $date . "'\n OR `closedate` IS NULL)"; } if ($object->isEntityAssign() && $entities != -1) { $restrict .= getEntitiesRestrictRequest(" AND ", $objecttable, '', $entities, $object->maybeRecursive()); } $count = countElementsInTable($objecttable, $restrict); $items = getAllDatasFromTable($objecttable, $restrict); if (!empty($items)) { echo "<div class='center'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><td>"; Html::createProgressBar(__('Work in progress...')); echo "</td></tr></table></div></br>\n"; $i = 0; foreach ($items as $item) { if ($object->delete(array('id' => $item['id']), 1, 0)) { $res['ok']++; } else { $res['ko']++; } $i++; Html::changeProgressBarPosition($i, $count); } Html::changeProgressBarPosition($i, $count, __('Task completed.')); } } } } if ($action == PluginUtilitairesUtilitaire::TEST || $action == PluginUtilitairesUtilitaire::TRUNCATE || $action == PluginUtilitairesUtilitaire::LINK) { return $nb; } else { return $res; } }
/** * This function is used to import in one time all SNMP model in folder * fusioninventory/snmpmodels/ */ function importMass() { ini_set("max_execution_time", "0"); $nb = 0; foreach (glob(GLPI_ROOT . '/plugins/fusioninventory/snmpmodels/*.xml') as $file) { $nb++; } echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'>"; echo "<th align='center'>"; echo __('Importing SNMP models, please wait...', 'fusioninventory'); echo "</th>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td align='center'>"; Html::createProgressBar(__('Importing SNMP models, please wait...', 'fusioninventory')); $i = 0; foreach (glob(GLPI_ROOT . '/plugins/fusioninventory/snmpmodels/*.xml') as $file) { $this->import($file, 0, 1); $i++; if (substr($i, -1) == '0') { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } } Html::changeProgressBarPosition($nb, $nb, "{$nb} / {$nb}"); echo "</td>"; echo "</table>"; PluginFusioninventorySnmpmodelImportExport::exportDictionnaryFile(); }
/** * @param $model PluginDatainjectionModel object * @param $entities_id **/ static function processInjection(PluginDatainjectionModel $model, $entities_id) { global $CFG_GLPI; // To prevent problem of execution time during injection ini_set("max_execution_time", "0"); // Disable recording each SQL request in $_SESSION $CFG_GLPI["debug_sql"] = 0; $nblines = PluginDatainjectionSession::getParam('nblines'); $clientinjection = new PluginDatainjectionClientInjection(); //New injection engine $engine = new PluginDatainjectionEngine($model, PluginDatainjectionSession::getParam('infos'), $entities_id); $backend = $model->getBackend(); $model->loadSpecificModel(); //Open CSV file $backend->openFile(); $index = 0; //Read CSV file $line = $backend->getNextLine(); //If header is present, then get the second line if ($model->getSpecificModel()->isHeaderPresent()) { $line = $backend->getNextLine(); } //While CSV file is not EOF $prev = ''; $deb = time(); while ($line != null) { //Inject line $injectionline = $index + ($model->getSpecificModel()->isHeaderPresent() ? 2 : 1); $clientinjection->results[] = $engine->injectLine($line[0], $injectionline); $pos = number_format($index * 100 / $nblines, 1); if ($pos != $prev) { $prev = $pos; $fin = time() - $deb; //TODO yllen Html::changeProgressBarPosition($index, $nblines, sprintf(__('%1$s (%2$s)'), sprintf(__('Injection of the file... %d%%', 'datainjection'), $pos), Html::timestampToString(time() - $deb, true))); } $line = $backend->getNextLine(); $index++; } //EOF : change progressbar to 100% ! Html::changeProgressBarPosition(100, 100, sprintf(__('%1$s (%2$s)'), __('Injection finished', 'datainjection'), Html::timestampToString(time() - $deb, true))); // Restore $CFG_GLPI["debug_sql"] = 1; //Close CSV file $backend->closeFile(); //Delete CSV file $backend->deleteFile(); //Change step $_SESSION['datainjection']['step'] = self::STEP_RESULT; //Display results form PluginDatainjectionSession::setParam('results', json_encode($clientinjection->results)); PluginDatainjectionSession::setParam('error_lines', json_encode($engine->getLinesInError())); $p['models_id'] = $model->fields['id']; $p['nblines'] = $nblines; unset($_SESSION['datainjection']['go']); $_SESSION["MESSAGE_AFTER_REDIRECT"] = ""; $url = $CFG_GLPI["root_doc"] . "/plugins/datainjection/ajax/results.php"; Ajax::updateItem("span_injection", $url, $p); }
static function syncOCS($objectId, $entities) { global $DB; $res = array('ok' => 0, 'ko' => 0); $object = new $objectId(); $objecttable = getTableForItemType($objectId); $restrict = ""; if ($object->maybeTemplate()) { $restrict = "`is_template` = '0'"; } if ($object->isEntityAssign() && $entities != -1) { $restrict .= getEntitiesRestrictRequest(" AND ", $objecttable, '', $entities, $object->maybeRecursive()); } $count = countElementsInTable($objecttable, $restrict); $items = getAllDatasFromTable($objecttable, $restrict); if (!empty($items)) { echo "<div class='center'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><td>"; Html::createProgressBar(__('Work in progress...')); echo "</td></tr></table></div></br>\n"; $i = 0; foreach ($items as $item) { //Try to get the OCS server whose machine belongs $query = "SELECT `plugin_ocsinventoryng_ocsservers_id`, `id`\n FROM `glpi_plugin_ocsinventoryng_ocslinks`\n WHERE `computers_id` = '" . $item['id'] . "'\n AND `entities_id` = '" . $entities . "'"; $result = $DB->query($query); if ($DB->numrows($result) == 1) { $data = $DB->fetch_assoc($result); if ($data['plugin_ocsinventoryng_ocsservers_id'] != -1) { //Force update of the machine if (PluginOcsinventoryngOcsServer::updateComputer($data['id'], $data['plugin_ocsinventoryng_ocsservers_id'], 0, 1)) { $res['ok']++; } else { $res['ko']++; } } } $i++; Html::changeProgressBarPosition($i, $count); } Html::changeProgressBarPosition($i, $count, __('Task completed.')); } return $res; }