/** * This method starts the parsing process. * * If the input was not supplied during construction, it's possible to pass * it here instead. * * If either input or options are not supplied, the defaults will be used. * * @param resource|string|array|null $input * @param int|null $options * @return array */ public function parse($input = null, $options = null) { if (!is_null($input)) { $this->setInput($input); } if (is_null($this->input)) { throw new EofException('End of input stream, or no input supplied'); } if (!is_null($options)) { $this->options = $options; } switch ($this->input[0]) { case 'vcalendar': $this->root = new VCalendar(array(), false); break; case 'vcard': $this->root = new VCard(array(), false); break; default: throw new ParseException('The root component must either be a vcalendar, or a vcard'); } foreach ($this->input[1] as $prop) { $this->root->add($this->parseProperty($prop)); } if (isset($this->input[2])) { foreach ($this->input[2] as $comp) { $this->root->add($this->parseComponent($comp)); } } // Resetting the input so we can throw an feof exception the next time. $this->input = null; return $this->root; }
function testDocumentForFree() { $d = new Document(false); $set = array('mediatype' => 'flac', 'url' => 'freesong.flac', 'description' => 'free song'); $new_id = $d->add($set); $d = new Document($new_id); $this->assertEquals($set['description'], $d->description()); $m = $d->price_in('AUD'); $this->assertEquals('$0.00 AUD', $m->show_with_code()); }
/** * add files (from $_FILES) to a ticket * create document if needed * create link from document to ticket * * @param $id of the ticket * * @return array of doc added name **/ function addFiles($id) { global $LANG, $CFG_GLPI; if (!isset($_FILES)) { return array(); } $docadded = array(); $doc = new Document(); $docitem = new Document_Item(); // add Document if exists if (isset($_FILES['multiple'])) { unset($_FILES['multiple']); $TMPFILE = $_FILES; } else { $TMPFILE = array($_FILES); } foreach ($TMPFILE as $_FILES) { if (isset($_FILES['filename']) && count($_FILES['filename']) > 0 && $_FILES['filename']["size"] > 0) { // Check for duplicate if ($doc->getFromDBbyContent($this->fields["entities_id"], $_FILES['filename']['tmp_name'])) { $docID = $doc->fields["id"]; } else { $input2 = array(); $input2["name"] = addslashes($LANG['tracking'][24] . " {$id}"); $input2["tickets_id"] = $id; $input2["entities_id"] = $this->fields["entities_id"]; $input2["documentcategories_id"] = $CFG_GLPI["documentcategories_id_forticket"]; $input2["_only_if_upload_succeed"] = 1; $input2["entities_id"] = $this->fields["entities_id"]; $docID = $doc->add($input2); } if ($docID > 0) { if ($docitem->add(array('documents_id' => $docID, 'itemtype' => $this->getType(), 'items_id' => $id))) { $docadded[] = stripslashes($doc->fields["name"] . " - " . $doc->fields["filename"]); } } } else { if (!empty($_FILES['filename']['name']) && isset($_FILES['filename']['error']) && $_FILES['filename']['error']) { addMessageAfterRedirect($LANG['document'][46], false, ERROR); } } } unset($_FILES); return $docadded; }
/** * @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>"; }
/** 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"); }
/** * add files (from $_FILES) to an ITIL object * create document if needed * create link from document to ITIL object * * @param $id Integer ID of the ITIL object * @param $donotif Boolean if we want to raise notification (default 1) * * @return array of doc added name **/ function addFiles($id, $donotif = 1) { global $CFG_GLPI; if (!isset($_FILES) || !isset($_FILES['filename'])) { return array(); } $docadded = array(); $doc = new Document(); $docitem = new Document_Item(); // if multiple files are uploaded $TMPFILE = array(); if (is_array($_FILES['filename']['name'])) { foreach ($_FILES['filename']['name'] as $key => $filename) { if (!empty($filename)) { $TMPFILE[$key]['filename']['name'] = $filename; $TMPFILE[$key]['filename']['type'] = $_FILES['filename']['type'][$key]; $TMPFILE[$key]['filename']['tmp_name'] = $_FILES['filename']['tmp_name'][$key]; $TMPFILE[$key]['filename']['error'] = $_FILES['filename']['error'][$key]; $TMPFILE[$key]['filename']['size'] = $_FILES['filename']['size'][$key]; } } } else { $TMPFILE = array($_FILES); } foreach ($TMPFILE as $_FILES) { if (isset($_FILES['filename']) && count($_FILES['filename']) > 0 && $_FILES['filename']["size"] > 0) { // Check for duplicate if ($doc->getFromDBbyContent($this->fields["entities_id"], $_FILES['filename']['tmp_name'])) { $docID = $doc->fields["id"]; } else { $input2 = array(); //TRANS: Default document to files attached to tickets : %d is the ticket id $input2["name"] = addslashes(sprintf(__('Document Ticket %d'), $id)); if ($this->getType() == 'Ticket') { $input2["tickets_id"] = $id; } $input2["entities_id"] = $this->fields["entities_id"]; $input2["documentcategories_id"] = $CFG_GLPI["documentcategories_id_forticket"]; $input2["_only_if_upload_succeed"] = 1; $input2["entities_id"] = $this->fields["entities_id"]; $docID = $doc->add($input2); } if ($docID > 0) { if ($docitem->add(array('documents_id' => $docID, '_do_notif' => $donotif, 'itemtype' => $this->getType(), 'items_id' => $id))) { $docadded[] = sprintf(__('%1$s - %2$s'), stripslashes($doc->fields["name"]), stripslashes($doc->fields["filename"])); } } } else { if (!empty($_FILES['filename']['name']) && isset($_FILES['filename']['error']) && $_FILES['filename']['error']) { Session::addMessageAfterRedirect(__('Failed to send the file (probably too large)'), false, ERROR); } } // Only notification for the first New doc $donotif = 0; } unset($_FILES); return $docadded; }
/** * Copy order documents into the newly generated item * @since 1.5.3 * @param unknown_type $itemtype * @param unknown_type $items_id * @param unknown_type $orders_id * @param unknown_type $entity */ static function copyDocuments($itemtype, $items_id, $orders_id, $entity) { global $CFG_GLPI; $config = PluginOrderConfig::getConfig(); if ($config->canCopyDocuments() && in_array($itemtype, $CFG_GLPI["document_types"])) { $document_item = new Document_Item(); $document = new Document(); foreach (getAllDatasFromTable('glpi_documents_items', "`itemtype`='PluginOrderOrder'\n AND `items_id`='{$orders_id}'") as $doc) { $document->getFromDB($doc['documents_id']); $mime = $document->fields['mime']; $newdocument = clone $document; $newdocument->fields['entities_id'] = $entity; unset($newdocument->fields['id']); $newID = $document->add($newdocument->fields); $tmp['itemtype'] = $itemtype; $tmp['items_id'] = $items_id; $tmp['documents_id'] = $newID; $document_item->add($tmp); //force mimetype $document->update(array('id' => $newID, 'mime' => $mime)); } } }
public function saveAnswers($datas) { $form = new PluginFormcreatorForm(); $form->getFromDB($datas['formcreator_form']); $query = "SELECT q.`id`, q.`fieldtype`, q.`name`\n FROM glpi_plugin_formcreator_questions q\n LEFT JOIN glpi_plugin_formcreator_sections s ON s.`id` = q.`plugin_formcreator_sections_id`\n WHERE s.`plugin_formcreator_forms_id` = {$datas['formcreator_form']}"; $result = $GLOBALS['DB']->query($query); // Update form answers if (isset($_POST['save_formanswer'])) { $status = $_POST['status']; $this->update(array('id' => (int) $datas['id'], 'status' => $status, 'comment' => isset($_POST['comment']) ? $_POST['comment'] : 'NULL')); // Update questions answers if ($status == 'waiting') { while ($question = $GLOBALS['DB']->fetch_array($result)) { if ($question['fieldtype'] != 'file') { $answer = new PluginFormcreatorAnswer(); $found = $answer->find('`plugin_formcreator_formanwers_id` = ' . (int) $datas['id'] . ' AND `plugin_formcreator_question_id` = ' . $question['id']); $found = array_shift($found); $data_value = $datas['formcreator_field_' . $question['id']]; if (isset($data_value)) { if (is_array($data_value)) { foreach ($data_value as $key => $value) { $data_value[$key] = $value; } $answer_value = json_encode($data_value); } else { $answer_value = $data_value; } } else { $answer_value = ''; } $answer->update(array('id' => $found['id'], 'answer' => $answer_value)); } elseif (isset($_FILES['formcreator_field_' . $question['id']]['tmp_name']) && is_file($_FILES['formcreator_field_' . $question['id']]['tmp_name'])) { $doc = new Document(); $answer = new PluginFormcreatorAnswer(); $found = $answer->find('`plugin_formcreator_formanwers_id` = ' . (int) $datas['id'] . ' AND `plugin_formcreator_question_id` = ' . $question['id']); $found = array_shift($found); $file_datas = array(); $file_datas["name"] = $form->fields['name'] . ' - ' . $question['name']; $file_datas["entities_id"] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id']; $file_datas["is_recursive"] = $form->fields['is_recursive']; Document::uploadDocument($file_datas, $_FILES['formcreator_field_' . $question['id']]); if ($docID = $doc->add($file_datas)) { $table = getTableForItemType('Document'); $filename = $_FILES['formcreator_field_' . $question['id']]['name']; $query = "UPDATE {$table} SET filename = '" . $filename . "' WHERE id = " . $docID; $GLOBALS['DB']->query($query); $docItem = new Document_Item(); $docItemId = $docItem->add(array('documents_id' => $docID, 'itemtype' => __CLASS__, 'items_id' => (int) $datas['id'])); $answer->update(array('id' => $found['id'], 'answer' => $docID)); } } } } // Create new form answer object } else { // Does the form need to be validate ? if ($form->fields['validation_required']) { $status = 'waiting'; } else { $status = 'accepted'; } $id = $this->add(array('entities_id' => isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id'], 'is_recursive' => $form->fields['is_recursive'], 'plugin_formcreator_forms_id' => $datas['formcreator_form'], 'requester_id' => isset($_SESSION['glpiID']) ? $_SESSION['glpiID'] : 0, 'validator_id' => isset($datas['formcreator_validator']) ? $datas['formcreator_validator'] : 0, 'status' => $status, 'request_date' => date('Y-m-d H:i:s'))); // Save questions answers while ($question = $GLOBALS['DB']->fetch_assoc($result)) { // If the answer is set, check if it is an array (then implode id). if (isset($datas[$question['id']])) { $question_answer = $datas[$question['id']]; if (is_array(json_decode($question_answer))) { $question_answer = json_decode($question_answer); foreach ($question_answer as $key => $value) { $question_answer[$key] = $value; } $question_answer = json_encode($question_answer); } else { $question_answer = $question_answer; } } else { $question_answer = ''; } $answer = new PluginFormcreatorAnswer(); $answerID = $answer->add(array('plugin_formcreator_formanwers_id' => $id, 'plugin_formcreator_question_id' => $question['id'], 'answer' => $question_answer)); // If the question is a file field, save the file as a document if ($question['fieldtype'] == 'file' && isset($_FILES['formcreator_field_' . $question['id']]['tmp_name']) && is_file($_FILES['formcreator_field_' . $question['id']]['tmp_name'])) { $doc = new Document(); $file_datas = array(); $file_datas["name"] = $form->fields['name'] . ' - ' . $question['name']; $file_datas["entities_id"] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id']; $file_datas["is_recursive"] = $form->fields['is_recursive']; Document::uploadDocument($file_datas, $_FILES['formcreator_field_' . $question['id']]); if ($docID = $doc->add($file_datas)) { $table = getTableForItemType('Document'); $filename = $_FILES['formcreator_field_' . $question['id']]['name']; $query = "UPDATE {$table} SET filename = '" . $filename . "' WHERE id = " . $docID; $GLOBALS['DB']->query($query); $docItem = new Document_Item(); $docItemId = $docItem->add(array('documents_id' => $docID, 'itemtype' => __CLASS__, 'items_id' => $id)); $answer->update(array('id' => $answerID, 'answer' => $docID)); } } } } NotificationEvent::raiseEvent('plugin_formcreator_form_created', $this); if ($form->fields['validation_required'] || $status == 'accepted') { switch ($status) { case 'waiting': // Notify the validator NotificationEvent::raiseEvent('plugin_formcreator_need_validation', $this); break; case 'refused': // Notify the requester NotificationEvent::raiseEvent('plugin_formcreator_refused', $this); break; case 'accepted': // Notify the requester if (!$this->generateTarget()) { Session::addMessageAfterRedirect(__('Cannot generate targets!', 'formcreator'), true, ERROR); $this->update(array('id' => $this->getID(), 'status' => 'waiting')); } NotificationEvent::raiseEvent('plugin_formcreator_accepted', $this); return false; break; } } Session::addMessageAfterRedirect(__('The form have been successfully saved!', 'formcreator'), true, INFO); }
/** * Résultat de la création du sous-lieu + ajout dans la base de données */ static function showFormResCreateLocation($opt) { global $CFG_GLPI, $DB; $filename = $opt["document_id"] . $opt["name"] . "." . $opt["extension"]; $filepath = "/_uploads/" . $filename; $id = 0; if ($opt["test"] == "existLocation") { $query = "SELECT `id`,`name`\n FROM `glpi_locations`\n WHERE `id` = '" . $opt["locations_id"] . "'"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { $name = $data['name']; $id = $data['id']; } } else { if ($opt["test"] == "newLocation") { $locations_id = $opt["locations_idParent"]; } } $params = array("name" => $opt["name"], "document_id" => $opt["document_id"], "filepath" => $filepath, "filename" => $filename, "entities_id" => $opt["entities_id"], "locations_id" => $opt["locations_id"], "id" => $id, "itemtype" => "Location"); //FONCTION QUI PERMET D'AJOUTER LE LIEU DANS LA BASE DE DONNEES $dropdown = new Location(); //AJOUT DU LIEU if ($opt["test"] == 'newLocation') { if ($newID = $dropdown->add($params)) { } else { $locations_found = $dropdown->find("`name` = '" . $params['name'] . "' AND `entities_id` = '" . $params['entities_id'] . "' AND `locations_id` = '" . $params['locations_id'] . "'", '', '1'); $newID = key($locations_found); } $opt["locations_id"] = $newID; } if ($opt["locations_id"] != $opt["locations_idParent"]) { //AJOUT DU DOC ASSOCIE AU LIEU $doc = new Document(); $documentitem = new Document_Item(); $self = new self(); $input = array(); $input["entities_id"] = $opt["entities_id"]; $input["name"] = $opt["name"]; $input["upload_file"] = $filename; //$input["documentcategories_id"]=$options["rubrique"]; //$input["mime"]="text/html"; $input["date_mod"] = date("Y-m-d H:i:s"); $input["users_id"] = Session::getLoginUserID(); $newdoc = $doc->add($input); // Add new location if ($opt["test"] == 'newLocation') { // We check if the element already exists $restrict = "`items_id` = '" . $newID . "' AND `itemtype` = 'Location'"; if (countElementsInTable("glpi_plugin_positions_positions", $restrict) != 0) { Session::addMessageAfterRedirect(__('This item is already bound to a location', 'positions'), false, ERROR); Html::redirect($CFG_GLPI["root_doc"] . "/plugins/positions/front/map.php?locations_id=" . $opt["locations_idParent"]); // If not we can add its position and picture } else { $documentitem->add(array('documents_id' => $newdoc, 'itemtype' => 'Location', 'items_id' => $newID, 'entities_id' => $opt["entities_id"])); $param = array("items_id" => $newID, "entities_id" => $opt["entities_id"], "locations_id" => $opt["locations_idParent"], "itemtype" => "Location", "x_coordinates" => -800, "y_coordinates" => -150); $self->add($param); if ($opt["checked"] == 'on') { self::showMapCreateLocation($opt); } else { if ($opt["checked"] == 'off') { Html::redirect($CFG_GLPI["root_doc"] . "/plugins/positions/front/map.php?locations_id=" . $opt["locations_id"]); } } } // Add existing location } else { if ($opt["test"] == 'existLocation') { $documentitem->add(array('documents_id' => $newdoc, 'itemtype' => 'Location', 'items_id' => $id)); $param = array("items_id" => $id, "entities_id" => $opt["entities_id"], "locations_id" => $opt["locations_idParent"], "itemtype" => "Location", "x_coordinates" => -800, "y_coordinates" => -150); $self->add($param); if ($opt["checked"] == 'on') { self::showMapCreateLocation($opt); } else { if ($opt["checked"] == 'off') { Html::redirect($CFG_GLPI["root_doc"] . "/plugins/positions/front/map.php?locations_id=" . $opt["locations_id"]); } } } } } else { Session::addMessageAfterRedirect(__('This item is already bound to a location', 'positions'), false, ERROR); Html::redirect($CFG_GLPI["root_doc"] . "/plugins/positions/front/map.php?locations_id=" . $opt["locations_id"]); } }
/** * Copy order documents into the newly generated item * @since 1.5.3 * @param unknown_type $itemtype * @param unknown_type $items_id * @param unknown_type $orders_id * @param unknown_type $entity */ public static function copyDocuments($itemtype, $items_id, $orders_id, $entity) { global $CFG_GLPI; $config = PluginOrderConfig::getConfig(); if ($config->canCopyDocuments() && in_array($itemtype, $CFG_GLPI["document_types"])) { $document = new Document(); foreach (getAllDatasFromTable('glpi_documents_items', "`itemtype`='PluginOrderOrder' AND `items_id`='{$orders_id}'") as $doc) { $document->getFromDB($doc['documents_id']); $newdocument = clone $document; $newdocument->fields['entities_id'] = $entity; $newdocument->fields['items_id'] = $items_id; $newdocument->fields['itemtype'] = $itemtype; unset($newdocument->fields['id']); $document->add($newdocument->fields); } } }
// Original Author of file: Julien Dombre // Purpose of file: // ---------------------------------------------------------------------- define('GLPI_ROOT', '..'); include GLPI_ROOT . "/inc/includes.php"; if (!isset($_GET["id"])) { $_GET["id"] = -1; } $doc = new Document(); $documentitem = new Document_Item(); if (isset($_POST["add"])) { $doc->check(-1, 'w', $_POST); if (isset($_POST['itemtype']) && isset($_POST['items_id']) && isset($_FILES['filename']['tmp_name']) && $doc->getFromDBbyContent($_POST["entities_id"], $_FILES['filename']['tmp_name'])) { $documentitem->add(array('documents_id' => $doc->fields['id'], 'itemtype' => $_POST['itemtype'], 'items_id' => $_POST['items_id'])); } else { $newID = $doc->add($_POST); $name = ""; if (isset($_POST["name"])) { $name = $_POST["name"]; } else { if (isset($_FILES['filename']) && isset($_FILES['filename']['name'])) { $name = $_FILES['filename']['name']; } } Event::log($newID, "documents", 4, "document", $_SESSION["glpiname"] . " " . $LANG['log'][20] . " " . $name . "."); } glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_POST["delete"])) { $doc->check($_POST["id"], 'w'); if ($doc->delete($_POST)) {
public function saveToTargets($datas) { $valid = true; // Validate form fields foreach ($_POST as $key => $value) { if (substr($key, 0, 18) == 'formcreator_field_') { $question_id = (int) substr($key, 18); $question = new PluginFormcreatorQuestion(); $question->getFromDB($question_id); $className = $question->fields['fieldtype'] . 'Field'; $filePath = dirname(__FILE__) . '/fields/' . $question->fields['fieldtype'] . '-field.class.php'; if ($question->fields['fieldtype'] == 'float') { $value = str_replace(',', '.', $datas['formcreator_field_' . $question_id]); $datas['formcreator_field_' . $question_id] = $value; } if (is_file($filePath)) { include_once $filePath; if (class_exists($className)) { if (!$className::isValid($question->fields, $value, $datas)) { $valid = false; } } } else { $valid = false; } } } // If not valid back to form if (!$valid) { $_SESSION['formcreator']['datas'] = $datas; Html::back(); // Otherwize generate targets } else { $_SESSION['formcreator_documents'] = array(); // Save files as Documents foreach ($_FILES as $question_name => $file) { if (isset($file['tmp_name']) && is_file($file['tmp_name'])) { $doc = new Document(); $question_id = trim(strrchr($question_name, '_'), '_'); $question = new PluginFormcreatorQuestion(); $question->getFromDB($question_id); $file_datas = array(); $file_datas["name"] = $this->fields['name'] . ' - ' . $question->fields['name']; $file_datas["entities_id"] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $this->fields['entities_id']; $file_datas["is_recursive"] = $this->fields['is_recursive']; Document::uploadDocument($file_datas, $file); if ($docID = $doc->add($file_datas)) { $_SESSION['formcreator_documents'][] = $docID; $table = getTableForItemType('Document'); $query = "UPDATE {$table} SET filename = '" . addslashes($file['name']) . "' WHERE id = " . $docID; $GLOBALS['DB']->query($query); } } } // Get all targets $target_class = new PluginFormcreatorTarget(); $founded_targets = $target_class->find('plugin_formcreator_forms_id = ' . $this->getID()); foreach ($founded_targets as $target) { $obj = new $target['itemtype'](); $obj->getFromDB($target['items_id']); $obj->save($this, $datas); } Session::addMessageAfterRedirect(__('The form have been successfully saved!', 'formcreator'), true, INFO); unset($_SESSION['formcreator_documents']); } }
Copyright (C) 2013 by the Moreticket Development Team. ------------------------------------------------------------------------- LICENSE This file is part of Moreticket. Moreticket is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Moreticket 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 Moreticket. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ include '../../../inc/includes.php'; $closeTicket = new PluginMoreticketCloseTicket(); if (isset($_POST["add"])) { $closeTicket->check(-1, UPDATE, $_POST); $doc = new Document(); $doc->check(-1, CREATE, $_POST); $DocId = $doc->add($_POST); $test = $closeTicket->add(array('requesters_id' => $_POST['requesters_id'], 'tickets_id' => $_POST['tickets_id'], 'date' => $_POST['date'], 'comment' => $_POST['comment'], 'documents_id' => $DocId)); Html::back(); }
along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkLoginUser(); if (!isset($_GET["id"])) { $_GET["id"] = -1; } $doc = new Document(); $documentitem = new Document_Item(); if (isset($_POST["add"])) { $doc->check(-1, 'w', $_POST); if ($newID = $doc->add($_POST)) { Event::log($newID, "documents", 4, "login", sprintf(__('%1$s adds the item %2$s'), $_SESSION["glpiname"], $doc->fields["name"])); } Html::back(); } else { if (isset($_POST["delete"])) { $doc->check($_POST["id"], 'd'); if ($doc->delete($_POST)) { Event::log($_POST["id"], "documents", 4, "document", sprintf(__('%s deletes an item'), $_SESSION["glpiname"])); } $doc->redirectToList(); } else { if (isset($_POST["restore"])) { $doc->check($_POST["id"], 'd'); if ($doc->restore($_POST)) { Event::log($_POST["id"], "documents", 4, "document", sprintf(__('%s restores an item'), $_SESSION["glpiname"]));
/** * Add a document to a existing ticket * for an authenticated user * * @param $params array of options (ticket, uri, name, base64, comment) * only one of uri and base64 must be set * name is mandatory when base64 set, for extension check (filename) * @param $protocol the communication protocol used * * @return array of hashtable **/ static function methodAddTicketDocument($params, $protocol) { global $DB, $CFG_GLPI; if (isset($params['help'])) { return array('ticket' => 'integer,mandatory', 'uri' => 'string,optional', 'base64' => 'string,optional', 'content' => 'string,optional', 'close' => 'bool,optional', 'reopen' => 'bool,optional', 'source' => 'string,optional', 'private' => 'bool,optional', 'help' => 'bool,optional'); } if (!Session::getLoginUserID()) { return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED); } $ticket = new Ticket(); if (!isset($params['ticket'])) { return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'ticket'); } if (!is_numeric($params['ticket'])) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'ticket'); } if (!$ticket->can($params['ticket'], 'r')) { return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND); } if (in_array($ticket->fields["status"], $ticket->getClosedStatusArray())) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', 'closed ticket'); } if (!$ticket->canAddFollowups()) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', 'access denied'); } if (isset($params['name']) && !empty($params['name'])) { $document_name = addslashes($params['name']); } else { $document_name = addslashes(sprintf(__('%1$s %2$s'), _x('phone', 'Number'), $ticket->fields['id'])); } $filename = tempnam(GLPI_DOC_DIR . '/_tmp', 'PWS'); $response = parent::uploadDocument($params, $protocol, $filename, $document_name); //An error occured during document upload if (parent::isError($protocol, $response)) { return $response; } $doc = new Document(); $documentitem = new Document_Item(); $docid = $doc->getFromDBbyContent($ticket->fields["entities_id"], $filename); if ($docid) { $input = array('itemtype' => $ticket->getType(), 'items_id' => $ticket->getID(), 'documents_id' => $doc->getID()); if ($DB->request('glpi_documents_items', $input)->numrows()) { return self::Error($protocol, WEBSERVICES_ERROR_FAILED, '', 'document already associated to this ticket'); } $new = $documentitem->add($input); } else { $input = array('itemtype' => $ticket->getType(), 'items_id' => $ticket->getID(), 'tickets_id' => $ticket->getID(), 'entities_id' => $ticket->getEntityID(), 'is_recursive' => $ticket->isRecursive(), 'documentcategories_id' => $CFG_GLPI["documentcategories_id_forticket"]); $new = $doc->add($input); } // to not add it twice during followup unset($_FILES['filename']); if (!$new) { return self::Error($protocol, WEBSERVICES_ERROR_FAILED, '', self::getDisplayError()); } if (isset($params['comment']) && !empty($params['comment'])) { $params['content'] = $params['comment']; unset($params['comment']); } if (isset($params['content']) && !empty($params['content'])) { return self::methodAddTicketFollowup($params, $protocol); } return self::methodGetTicket(array('ticket' => $params['ticket']), $protocol); }
/** * add files (from $this->input['_filename']) to an ITIL object * create document if needed * create link from document to ITIL object * * @param $donotif Boolean if we want to raise notification (default 1) * @param $disablenotif (default 0) * * @return array of doc added name **/ function addFiles($donotif = 1, $disablenotif = 0) { global $CFG_GLPI; if (!isset($this->input['_filename']) || count($this->input['_filename']) == 0) { return array(); } $docadded = array(); foreach ($this->input['_filename'] as $key => $file) { $doc = new Document(); $docitem = new Document_Item(); $docID = 0; $filename = GLPI_TMP_DIR . "/" . $file; $input2 = array(); // Crop/Resize image file if needed if (isset($this->input['_coordinates']) && !empty($this->input['_coordinates'][$key])) { $image_coordinates = json_decode(urldecode($this->input['_coordinates'][$key]), true); Toolbox::resizePicture($filename, $filename, $image_coordinates['img_w'], $image_coordinates['img_h'], $image_coordinates['img_y'], $image_coordinates['img_x'], $image_coordinates['img_w'], $image_coordinates['img_h'], 0); } else { Toolbox::resizePicture($filename, $filename, 0, 0, 0, 0, 0, 0, 0); } //If file tag is present if (isset($this->input['_tag_filename']) && !empty($this->input['_tag_filename'][$key])) { $this->input['_tag'][$key] = $this->input['_tag_filename'][$key]; } // Check for duplicate if ($doc->getFromDBbyContent($this->fields["entities_id"], $filename)) { if (!$doc->fields['is_blacklisted']) { $docID = $doc->fields["id"]; } // File already exist, we replace the tag by the existing one if (isset($this->input['_tag'][$key]) && $docID > 0 && isset($this->input['content'])) { $this->input['content'] = preg_replace('/' . Document::getImageTag($this->input['_tag'][$key]) . '/', Document::getImageTag($doc->fields["tag"]), $this->input['content']); $docadded[$docID]['tag'] = $doc->fields["tag"]; } } else { //TRANS: Default document to files attached to tickets : %d is the ticket id $input2["name"] = addslashes(sprintf(__('Document Ticket %d'), $this->getID())); if ($this->getType() == 'Ticket') { $input2["tickets_id"] = $this->getID(); // Insert image tag if (isset($this->input['_tag'][$key])) { $input2["tag"] = $this->input['_tag'][$key]; } } $input2["entities_id"] = $this->fields["entities_id"]; $input2["documentcategories_id"] = $CFG_GLPI["documentcategories_id_forticket"]; $input2["_only_if_upload_succeed"] = 1; $input2["entities_id"] = $this->fields["entities_id"]; $input2["_filename"] = array($file); $docID = $doc->add($input2); } if ($docID > 0) { if ($docitem->add(array('documents_id' => $docID, '_do_notif' => $donotif, '_disablenotif' => $disablenotif, 'itemtype' => $this->getType(), 'items_id' => $this->getID()))) { $docadded[$docID]['data'] = sprintf(__('%1$s - %2$s'), stripslashes($doc->fields["name"]), stripslashes($doc->fields["filename"])); if (isset($input2["tag"])) { $docadded[$docID]['tag'] = $input2["tag"]; unset($this->input['_filename'][$key]); unset($this->input['_tag'][$key]); } if (isset($this->input['_coordinates'][$key])) { unset($this->input['_coordinates'][$key]); } } } // Only notification for the first New doc $donotif = 0; } // Ticket update if (isset($this->input['content'])) { if ($CFG_GLPI["use_rich_text"]) { $this->input['content'] = $this->convertTagToImage($this->input['content'], true, $docadded); $this->input['_forcenotif'] = true; } else { $this->fields['content'] = $this->setSimpleTextContent($this->input['content']); $this->updateInDB(array('content')); } } return $docadded; }
/** * Copy order documents into the newly generated item * @since 1.5.3 * @param unknown_type $itemtype * @param unknown_type $items_id * @param unknown_type $orders_id * @param unknown_type $entity */ public static function copyDocuments($itemtype, $items_id, $orders_id, $entity) { global $CFG_GLPI; $config = PluginOrderConfig::getConfig(); if ($config->canCopyDocuments() && in_array($itemtype, $CFG_GLPI["document_types"])) { $document = new Document(); $docitem = new Document_Item(); $item = new $itemtype(); $item->getFromDB($items_id); $is_recursive = 0; foreach (getAllDatasFromTable('glpi_documents_items', "`itemtype`='PluginOrderOrder'\n AND `items_id`='{$orders_id}'") as $doc) { //Create a new document $document->getFromDB($doc['documents_id']); if ($document->getEntityID() != $entity && !$document->fields['is_recursive'] || !in_array($entity, getSonsOf('glpi_entities', $document->getEntityID()))) { $found_docs = getAllDatasFromTable('glpi_documents', "`entities_id`='{$entity}'\n AND `sha1sum`='" . $document->fields['sha1sum'] . "'"); if (empty($found_docs)) { $tmpdoc = $document->fields; $tmpdoc['entities_id'] = $entity; unset($tmpdoc['id']); $documents_id = $document->add($tmpdoc); $is_recursive = $document->fields['is_recursive']; } else { $found_doc = array_pop($found_docs); $documents_id = $found_doc['id']; $is_recursive = $found_doc['is_recursive']; } } else { $documents_id = $document->getID(); $is_recursive = $document->fields['is_recursive']; } //Link the document to the newly generated item $fields['documents_id'] = $documents_id; $fields['entities_id'] = $entity; $fields['items_id'] = $items_id; $fields['itemtype'] = $itemtype; $fields['is_recursive'] = $is_recursive; $newID = $docitem->add($fields); } } }
/** * Transfer documents * * @param $itemtype original type of transfered item * @param $ID original ID of the document * @param $newID new ID of the document **/ function transferDocuments($itemtype, $ID, $newID) { global $DB; $need_clean_process = false; // if keep if ($this->options['keep_document']) { $document = new Document(); // Get contracts for the item $query = "SELECT *\n FROM `glpi_documents_items`\n WHERE `items_id` = '{$ID}'\n AND `itemtype` = '{$itemtype}'\n AND `documents_id` NOT IN " . $this->item_recurs['Document']; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Foreach get item while ($data = $DB->fetch_array($result)) { $need_clean_process = false; $item_ID = $data['documents_id']; $newdocID = -1; // is already transfer ? if (isset($this->already_transfer['Document'][$item_ID])) { $newdocID = $this->already_transfer['Document'][$item_ID]; if ($newdocID != $item_ID) { $need_clean_process = true; } } else { // No // Can be transfer without copy ? = all linked items need to be transfer (so not copy) $canbetransfer = true; $query = "SELECT DISTINCT `itemtype`\n FROM `glpi_documents_items`\n WHERE `documents_id` = '{$item_ID}'"; if ($result_type = $DB->query($query)) { if ($DB->numrows($result_type) > 0) { while (($data_type = $DB->fetch_array($result_type)) && $canbetransfer) { $dtype = $data_type['itemtype']; if (isset($this->item_search[$dtype])) { // No items to transfer -> exists links $query_search = "SELECT count(*) AS CPT\n FROM `glpi_documents_items`\n WHERE `documents_id` = '{$item_ID}'\n AND `itemtype` = '{$dtype}'\n AND `items_id`\n NOT IN " . $this->item_search[$dtype]; // contacts, contracts, and enterprises are linked as device. if (isset($this->item_recurs[$dtype])) { $query_search .= " AND `items_id`\n NOT IN " . $this->item_recurs[$dtype]; } $result_search = $DB->query($query_search); if ($DB->result($result_search, 0, 'CPT') > 0) { $canbetransfer = false; } } } } } // Yes : transfer if ($canbetransfer) { $this->transferItem('Document', $item_ID, $item_ID); $newdocID = $item_ID; } else { $need_clean_process = true; $document->getFromDB($item_ID); // No : search contract $query = "SELECT *\n FROM `glpi_documents`\n WHERE `entities_id` = '" . $this->to . "'\n AND `name` = '" . addslashes($document->fields['name']) . "'"; if ($result_search = $DB->query($query)) { if ($DB->numrows($result_search) > 0) { $newdocID = $DB->result($result_search, 0, 'id'); $this->addToAlreadyTransfer('Document', $item_ID, $newdocID); } } // found : use it // not found : copy doc if ($newdocID < 0) { // 1 - create new item unset($document->fields['id']); $input = $document->fields; // Not set new entity Do by transferItem unset($document->fields); $newdocID = $document->add($input); // 2 - transfer as copy $this->transferItem('Document', $item_ID, $newdocID); } } } // Update links if ($ID == $newID) { if ($item_ID != $newdocID) { $query = "UPDATE `glpi_documents_items`\n SET `documents_id` = '{$newdocID}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } // Same Item -> update links } else { // Copy Item -> copy links if ($item_ID != $newdocID) { $query = "INSERT\n INTO `glpi_documents_items`\n (`documents_id`, `items_id`, `itemtype`)\n VALUES ('{$newdocID}','{$newID}','{$itemtype}')"; $DB->query($query); } else { // same doc for new item update link $query = "UPDATE\n `glpi_documents_items`\n SET `items_id` = '{$newID}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } } // If clean and unused -> if ($need_clean_process && $this->options['clean_document']) { $query = "SELECT COUNT(*) AS CPT\n FROM `glpi_documents_items`\n WHERE `documents_id` = '{$item_ID}'"; if ($result_remaining = $DB->query($query)) { if ($DB->result($result_remaining, 0, 'CPT') == 0) { if ($this->options['clean_document'] == 1) { $document->delete(array('id' => $item_ID)); } if ($this->options['clean_document'] == 2) { // purge $document->delete(array('id' => $item_ID), 1); } } } } } } } } else { // else unlink $query = "DELETE\n FROM `glpi_documents_items`\n WHERE `items_id` = '{$ID}'\n AND `itemtype` = '{$itemtype}'"; $DB->query($query); } }
function addFilesTickets($id, $question_name, $entities_id) { global $LANG, $CFG_GLPI; $docadded = array(); $doc = new Document(); $docitem = new Document_Item(); // if multiple files are uploaded $TMPFILE = array(); if (is_array($_FILES[$question_name]['name'])) { $_FILES['filename'] = $_FILES[$question_name]; foreach ($_FILES[$question_name]['name'] as $key => $filename) { if (!empty($filename)) { $TMPFILE[$key]['filename']['name'] = $filename; $TMPFILE[$key]['filename']['type'] = $_FILES['filename']['type'][$key]; $TMPFILE[$key]['filename']['tmp_name'] = $_FILES['filename']['tmp_name'][$key]; $TMPFILE[$key]['filename']['error'] = $_FILES['filename']['error'][$key]; $TMPFILE[$key]['filename']['size'] = $_FILES['filename']['size'][$key]; } } } else { $TMPFILE = array($_FILES); } foreach ($TMPFILE as $_FILES) { if (isset($_FILES[$question_name]) && count($_FILES[$question_name]) > 0 && $_FILES[$question_name]["size"] > 0) { $_FILES['filename'] = $_FILES[$question_name]; // Check for duplicate if ($doc->getFromDBbyContent($entities_id, $_FILES['filename']['tmp_name'])) { $docID = $doc->fields["id"]; } else { $input2 = array(); $input2["name"] = addslashes(__('Document Ticket') . " {$id}"); $input2["tickets_id"] = $id; $input2["entities_id"] = $entities_id; $input2["documentcategories_id"] = $CFG_GLPI["documentcategories_id_forticket"]; $input2["_only_if_upload_succeed"] = 1; $input2["entities_id"] = $entities_id; $docID = $doc->add($input2); if ($docID > 0) { if ($docitem->add(array('documents_id' => $docID, 'itemtype' => 'Ticket', 'items_id' => $id))) { $docadded[] = stripslashes($doc->fields["name"] . " - " . $doc->fields["filename"]); } } } } } unset($_FILES['filename']); return true; }