static function pdfDevice(PluginPdfSimplePDF $pdf, Computer $computer) { global $DB; $devtypes = Item_Devices::getDeviceTypes(); $ID = $computer->getField('id'); if (!$computer->can($ID, 'r')) { return false; } $pdf->setColumnsSize(100); $pdf->displayTitle('<b>' . Toolbox::ucfirst(_n('Component', 'Components', 2)) . '</b>'); $pdf->setColumnsSize(3, 14, 42, 41); foreach ($devtypes as $itemtype) { $devicetypes = new $itemtype(); $specificities = $devicetypes->getSpecificities(); $specif_fields = array_keys($specificities); $specif_text = implode(',', $specif_fields); if (!empty($specif_text)) { $specif_text = " ," . $specif_text . " "; } $associated_type = str_replace('Item_', '', $itemtype); $linktable = getTableForItemType($itemtype); $fk = getForeignKeyFieldForTable(getTableForItemType($associated_type)); $query = "SELECT count(*) AS NB, `id`, `" . $fk . "`" . $specif_text . "\n FROM `" . $linktable . "`\n WHERE `items_id` = '" . $ID . "'\n AND `itemtype` = 'Computer'\n GROUP BY `" . $fk . "`" . $specif_text; $device = new $associated_type(); foreach ($DB->request($query) as $data) { if ($device->getFromDB($data[$fk])) { $spec = $device->getAdditionalFields(); $col4 = ''; if (count($spec)) { $colspan = 60 / count($spec); foreach ($spec as $i => $label) { if (isset($device->fields[$label["name"]]) && !empty($device->fields[$label["name"]])) { if ($label["type"] == "dropdownValue" && $device->fields[$label["name"]] != 0) { $table = getTableNameForForeignKeyField($label["name"]); $value = Dropdown::getDropdownName($table, $device->fields[$label["name"]]); $col4 .= '<b><i>' . sprintf(__('%1$s: %2$s'), $label["label"] . '</i></b>', Html::clean($value) . " "); } else { $value = $device->fields[$label["name"]]; $col4 .= '<b><i>' . sprintf(__('%1$s: %2$s'), $label["label"] . '</i></b>', $value . " "); } } else { if (isset($device->fields[$label["name"] . "_default"]) && !empty($device->fields[$label["name"] . "_default"])) { $col4 .= '<b><i>' . sprintf(__('%1$s: %2$s'), $label["label"] . '</i></b>', $device->fields[$label["name"] . "_default"] . " "); } } } } $pdf->displayLine($data['NB'], $device->getTypeName(), $device->getName(), $col4); } } } $pdf->displaySpace(); }
/** * @since version 0.85 **/ static function getSpecificities($specif = '') { return array('mac' => array('long name' => __('MAC address'), 'short name' => __('MAC address'), 'size' => 18, 'id' => 20, 'datatype' => 'mac'), 'serial' => parent::getSpecificities('serial'), 'busID' => parent::getSpecificities('busID')); }
function cleanDBonPurge() { $csv = new Computer_SoftwareVersion(); $csv->cleanDBonItemDelete('Computer', $this->fields['id']); $csl = new Computer_SoftwareLicense(); $csl->cleanDBonItemDelete('Computer', $this->fields['id']); $ip = new Item_Problem(); $ip->cleanDBonItemDelete('Computer', $this->fields['id']); $ci = new Change_Item(); $ci->cleanDBonItemDelete('Computer', $this->fields['id']); $ip = new Item_Project(); $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ci = new Computer_Item(); $ci->cleanDBonItemDelete('Computer', $this->fields['id']); Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'], !empty($this->input['keep_devices'])); $disk = new ComputerDisk(); $disk->cleanDBonItemDelete('Computer', $this->fields['id']); $vm = new ComputerVirtualMachine(); $vm->cleanDBonItemDelete('Computer', $this->fields['id']); }
/** * @since version 0.85 **/ static function getSpecificities($specif = '') { return array('serial' => parent::getSpecificities('serial')); }
function cleanDBonPurge() { global $DB; $ci = new Computer_Item(); $ci->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $query = "UPDATE `glpi_cartridges`\n SET `printers_id` = NULL\n WHERE `printers_id` = '" . $this->fields['id'] . "'"; $result = $DB->query($query); $ip = new Item_Problem(); $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ci = new Change_Item(); $ci->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ip = new Item_Project(); $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']); Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'], !empty($this->input['keep_devices'])); }
GLPI 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. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief * @since version 0.84 */ include '../inc/includes.php'; Session::checkCentralAccess(); if (isset($_POST["add"])) { Item_Devices::addDevicesFromPOST($_POST); Html::back(); } else { if (isset($_POST["updateall"])) { Item_Devices::updateAll($_POST); Html::back(); } } Html::displayErrorAndDie('Lost');
/** * @since version 0.85 **/ static function getSpecificities($specif = '') { return array('frequency' => array('long name' => sprintf(__('%1$s (%2$s)'), __('Frequency'), __('MHz')), 'short name' => __('Frequency'), 'size' => 10, 'id' => 20), 'serial' => parent::getSpecificities('serial'), 'nbcores' => array('long name' => __('Number of cores'), 'short name' => __('Cores'), 'size' => 2, 'id' => 21), 'nbthreads' => array('long name' => __('Number of threads'), 'short name' => __('Threads'), 'size' => 2, 'id' => 22), 'busID' => parent::getSpecificities('busID')); }
/** * @since version 0.85 * * @see CommonDBTM::processMassiveActionsForOneItemtype() **/ static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $baseitem, array $ids) { global $DB; switch ($ma->getAction()) { case 'unlock': $input = $ma->getInput(); if (isset($input['attached_item'])) { $attached_items = $input['attached_item']; if (($device_key = array_search('Device', $attached_items)) !== false) { unset($attached_items[$device_key]); $attached_items = array_merge($attached_items, Item_Devices::getDeviceTypes()); } $links = array(); foreach ($attached_items as $attached_item) { $infos = self::getLocksQueryInfosByItemType($attached_item, $baseitem->getType()); if ($item = getItemForItemtype($infos['type'])) { $infos['item'] = $item; $links[$attached_item] = $infos; } } foreach ($ids as $id) { $action_valid = false; foreach ($links as $infos) { $infos['condition'][$infos['field']] = $id; foreach ($DB->request($infos['table'], $infos['condition']) as $data) { // Restore without history $action_valid = $infos['item']->restore(array('id' => $data['id'])); } } if ($action_valid) { $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK); } else { $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO); $ma->addMessage($infos['item']->getErrorMessage(ERROR_ON_ACTION)); } } } return; } parent::processMassiveActionsForOneItemtype($ma, $baseitem, $ids); }
GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief * @since version 0.84 */ include '../inc/includes.php'; Session::checkCentralAccess(); if (isset($_POST["add"])) { if (isset($_POST['devicetype'])) { if ($link = getItemForItemtype('Item_' . $_POST['devicetype'])) { $link->addDevices(1, $_POST['itemtype'], $_POST['items_id'], $_POST['devices_id']); } } Html::back(); } else { if (isset($_POST["updateall"])) { Item_Devices::updateAll($_POST, false); Html::back(); } else { if (isset($_POST["delete"])) { Item_Devices::updateAll($_POST, true); Html::back(); } } } Html::displayErrorAndDie('Lost');
/** * Display a 2 columns Footer for Form buttons * Close the form is user can edit * * @param $options array of possible options: * - withtemplate : 1 for newtemplate, 2 for newobject from template * - colspan for each column (default 2) * - candel : set to false to hide "delete" button * - canedit : set to false to hide all buttons * - addbuttons : array of buttons to add **/ function showFormButtons($options = array()) { global $CFG_GLPI; // for single object like config if (isset($this->fields['id'])) { $ID = $this->fields['id']; } else { $ID = 1; } $params['colspan'] = 2; $params['withtemplate'] = ''; $params['candel'] = true; $params['canedit'] = true; $params['addbuttons'] = array(); if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $params[$key] = $val; } } if (!$params['canedit'] || !$this->canEdit($ID)) { echo "</table></div>"; // Form Header always open form if (!$params['canedit']) { Html::closeForm(); } return false; } echo "<tr class='tab_bg_2'>"; if ($params['withtemplate'] || $this->isNewID($ID)) { echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>"; if ($ID <= 0 || $params['withtemplate'] == 2) { echo Html::submit(_x('button', 'Add'), array('name' => 'add')); } else { //TRANS : means update / actualize echo Html::submit(_x('button', 'Save'), array('name' => 'update')); } } else { if ($params['candel'] && !$this->can($ID, DELETE) && !$this->can($ID, PURGE)) { $params['candel'] = false; } if ($params['canedit'] && $this->can($ID, UPDATE)) { echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>\n"; echo Html::submit(_x('button', 'Save'), array('name' => 'update')); } if ($params['candel']) { if ($params['canedit'] && $this->can($ID, UPDATE)) { echo "</td></tr><tr class='tab_bg_2'>\n"; } if ($this->isDeleted()) { if ($this->can($ID, DELETE)) { echo "<td class='right' colspan='" . $params['colspan'] * 2 . "' >\n"; echo Html::submit(_x('button', 'Restore'), array('name' => 'restore')); } if ($this->can($ID, PURGE)) { echo "<span class='very_small_space'>"; if (in_array($this->getType(), Item_Devices::getConcernedItems())) { Html::showToolTip(__('Check to keep the devices while deleting this item')); echo " "; echo "<input type='checkbox' name='keep_devices' value='1'"; if (!empty($_SESSION['glpikeep_devices_when_purging_item'])) { echo " checked"; } echo "> "; } echo Html::submit(_x('button', 'Delete permanently'), array('name' => 'purge')); echo "</span>"; } } else { echo "<td class='right' colspan='" . $params['colspan'] * 2 . "' >\n"; // If maybe dynamic : do not take into account is_deleted field if (!$this->maybeDeleted() || $this->useDeletedToLockIfDynamic()) { if ($this->can($ID, PURGE)) { echo Html::submit(_x('button', 'Delete permanently'), array('name' => 'purge', 'confirm' => __('Confirm the final deletion?'))); } } else { if (!$this->isDeleted() && $this->can($ID, DELETE)) { echo Html::submit(_x('button', 'Put in dustbin'), array('name' => 'delete')); } } } } if ($this->isField('date_mod')) { echo "<input type='hidden' name='_read_date_mod' value='" . $this->getField('date_mod') . "'>"; } } if (!$this->isNewID($ID)) { echo "<input type='hidden' name='id' value='{$ID}'>"; } echo "</td>"; echo "</tr>\n"; if ($params['canedit'] && count($params['addbuttons'])) { echo "<tr class='tab_bg_2'>"; if ($params['colspan'] * 2 - count($params['addbuttons']) > 0) { echo "<td colspan='" . ($params['colspan'] * 2 - count($params['addbuttons'])) . "'> " . "</td>"; } foreach ($params['addbuttons'] as $key => $val) { echo "<td><input class='submit' type='submit' name='{$key}' value=\"" . Html::entities_deep($val) . "\"></td>"; } echo "</tr>"; } // Close for Form echo "</table></div>"; Html::closeForm(); }
/** * Do the standard massive actions * * @since version 0.84 * * This must not be overloaded in Class * @param $input array of input datas * * @return an array of results (ok, ko, noright counts, may include REDIRECT field to set REDIRECT page) **/ function doMassiveActions($input = array()) { global $CFG_GLPI; if (!isset($input["item"]) || count($input["item"]) == 0) { return false; } $res = array('ok' => 0, 'ko' => 0, 'noright' => 0); switch ($input['action']) { case 'add_document': case 'remove_document': $doc = new Document(); return $doc->doSpecificMassiveActions($input); case "add_transfer_list": if (!isset($_SESSION['glpitransfer_list'])) { $_SESSION['glpitransfer_list'] = array(); } if (!isset($_SESSION['glpitransfer_list'][$input["itemtype"]])) { $_SESSION['glpitransfer_list'][$input["itemtype"]] = array(); } foreach ($input["item"] as $key => $val) { if ($val == 1) { $_SESSION['glpitransfer_list'][$input["itemtype"]][$key] = $key; $res['ok']++; } } $res['REDIRECT'] = $CFG_GLPI['root_doc'] . '/front/transfer.action.php'; break; case "delete": foreach ($input["item"] as $key => $val) { if ($val == 1) { if ($this->can($key, 'd')) { if ($this->delete(array("id" => $key))) { $res['ok']++; } else { $res['ko']++; } } else { $res['noright']++; } } } break; case "purge": foreach ($input["item"] as $key => $val) { if ($val == 1) { if ($this->can($key, 'd')) { $force = 1; // Only mark deletion for if ($this->maybeDeleted() && $this->useDeletedToLockIfDynamic() && $this->isDynamic()) { $force = 0; } if ($this->delete(array("id" => $key), $force)) { $res['ok']++; } else { $res['ko']++; } } else { $res['noright']++; } } } break; case "restore": foreach ($input["item"] as $key => $val) { if ($val == 1) { if ($this->can($key, 'd')) { if ($this->restore(array("id" => $key))) { $res['ok']++; } else { $res['ko']++; } } else { $res['noright']++; } } } break; case "update": $searchopt = Search::getCleanedOptions($input["itemtype"], 'w'); if (isset($searchopt[$input["id_field"]])) { /// Infocoms case if (!isPluginItemType($input["itemtype"]) && Search::isInfocomOption($input["itemtype"], $input["id_field"])) { $ic = new Infocom(); $link_entity_type = -1; /// Specific entity item if ($searchopt[$input["id_field"]]["table"] == "glpi_suppliers") { $ent = new Supplier(); if ($ent->getFromDB($input[$input["field"]])) { $link_entity_type = $ent->fields["entities_id"]; } } foreach ($input["item"] as $key => $val) { if ($val == 1) { if ($this->getFromDB($key)) { if ($link_entity_type < 0 || $link_entity_type == $this->getEntityID() || $ent->fields["is_recursive"] && in_array($link_entity_type, getAncestorsOf("glpi_entities", $this->getEntityID()))) { $input2["items_id"] = $key; $input2["itemtype"] = $input["itemtype"]; if ($ic->can(-1, 'w', $input2)) { // Add infocom if not exists if (!$ic->getFromDBforDevice($input["itemtype"], $key)) { $input2["items_id"] = $key; $input2["itemtype"] = $input["itemtype"]; unset($ic->fields); $ic->add($input2); $ic->getFromDBforDevice($input["itemtype"], $key); } $id = $ic->fields["id"]; unset($ic->fields); if ($ic->update(array('id' => $id, $input["field"] => $input[$input["field"]]))) { $res['ok']++; } else { $res['ko']++; } } else { $res['noright']++; } } else { $res['ko']++; } } else { $res['ko']++; } } } } else { /// Not infocoms $link_entity_type = array(); /// Specific entity item $itemtable = getTableForItemType($input["itemtype"]); $itemtype2 = getItemTypeForTable($searchopt[$input["id_field"]]["table"]); if ($item2 = getItemForItemtype($itemtype2)) { if ($input["id_field"] != 80 && $searchopt[$input["id_field"]]["table"] != $itemtable && $item2->isEntityAssign() && $this->isEntityAssign()) { if ($item2->getFromDB($input[$input["field"]])) { if (isset($item2->fields["entities_id"]) && $item2->fields["entities_id"] >= 0) { if (isset($item2->fields["is_recursive"]) && $item2->fields["is_recursive"]) { $link_entity_type = getSonsOf("glpi_entities", $item2->fields["entities_id"]); } else { $link_entity_type[] = $item2->fields["entities_id"]; } } } } } foreach ($input["item"] as $key => $val) { if ($val == 1) { if ($this->can($key, 'w') && $this->canMassiveAction($input['action'], $input['field'], $input[$input["field"]])) { if (count($link_entity_type) == 0 || in_array($this->fields["entities_id"], $link_entity_type)) { if ($this->update(array('id' => $key, $input["field"] => $input[$input["field"]]))) { $res['ok']++; } else { $res['ko']++; } } else { $res['ko']++; } } else { $res['noright']++; } } } } } break; case "activate_infocoms": $ic = new Infocom(); if ($ic->canCreate()) { foreach ($input["item"] as $key => $val) { $input = array('itemtype' => $input['itemtype'], 'items_id' => $key); if (!$ic->getFromDBforDevice($input['itemtype'], $key)) { if ($ic->can(-1, 'w', $input)) { if ($ic->add($input)) { $res['ok']++; } else { $res['ko']++; } } else { $res['noright']++; } } else { $res['ko']++; } } } break; case "add_contract_item": $contractitem = new Contract_Item(); foreach ($input["item"] as $key => $val) { if (isset($input['items_id'])) { // Add items to contracts $input = array('itemtype' => $input["item_itemtype"], 'items_id' => $input["items_id"], 'contracts_id' => $key); } if (isset($input['contracts_id'])) { // Add contract to item $input = array('itemtype' => $input["itemtype"], 'items_id' => $key, 'contracts_id' => $input['contracts_id']); } else { return false; } if ($contractitem->can(-1, 'w', $input)) { if ($contractitem->add($input)) { $res['ok']++; } else { $res['ko']++; } } else { $res['noright']++; } } break; case "remove_contract_item": foreach ($input["item"] as $key => $val) { if (isset($input['items_id'])) { // Remove item to contracts $input = array('itemtype' => $input["item_itemtype"], 'items_id' => $input["items_id"], 'contracts_id' => $key); } else { // Remove contract to items $input = array('itemtype' => $input["itemtype"], 'items_id' => $key, 'contracts_id' => $input['contracts_id']); } $contractitem = new Contract_Item(); if ($contractitem->can(-1, 'w', $input)) { if ($item = getItemForItemtype($input["itemtype"])) { if ($item->getFromDB($input['items_id'])) { $contract = new Contract(); if ($contract->getFromDB($input['contracts_id'])) { if ($contractitem->getFromDBForItems($contract, $item)) { if ($contractitem->delete(array('id' => $contractitem->getID()))) { $res['ok']++; } else { $res['ko']++; } } else { $res['ko']++; } } else { $res['ko']++; } } else { $res['ko']++; } } else { $res['ko']++; } } else { $res['noright']++; } } break; //Lock management //Lock management case 'unlock_Printer': case 'unlock_Monitor': case 'unlock_NetworkPort': case 'unlock_NetworkName': case 'unlock_IPAddress': case 'unlock_ComputerDisk': case 'unlock_ComputerVirtualMachine': case 'unlock_Peripheral': case 'unlock_SoftwareVersion': $itemtype = Lock::getItemTypeForMassiveAction($input["action"]); if ($itemtype) { $res = Lock::unlockItems($itemtype, $this->getType(), $input["item"]); } break; case 'unlock_Device': foreach (Item_Devices::getDeviceTypes() as $itemtype) { $res = Lock::unlockItems($itemtype, $this->getType(), $input["item"]); } break; default: // Plugin specific actions $split = explode('_', $input["action"]); $res = ''; if ($split[0] == 'plugin' && isset($split[1])) { // Normalized name plugin_name_action // Allow hook from any plugin on any (core or plugin) type $res = Plugin::doOneHook($split[1], 'MassiveActionsProcess', $input); // } else if ($plug=isPluginItemType($input["itemtype"])) { // non-normalized name // hook from the plugin defining the type // $res = Plugin::doOneHook($plug['plugin'], 'MassiveActionsProcess', $input); } else { $res = $this->doSpecificMassiveActions($input); } break; } return $res; }
function cleanDBonPurge() { $csv = new Computer_SoftwareVersion(); $csv->cleanDBonItemDelete('Computer', $this->fields['id']); $csl = new Computer_SoftwareLicense(); $csl->cleanDBonItemDelete('Computer', $this->fields['id']); $ip = new Item_Problem(); $ip->cleanDBonItemDelete('Computer', $this->fields['id']); $ci = new Computer_Item(); $ci->cleanDBonItemDelete('Computer', $this->fields['id']); Item_Devices::cleanItemDeviceDBOnItemDelete('Computer', $this->fields['id']); $disk = new ComputerDisk(); $disk->cleanDBonItemDelete('Computer', $this->fields['id']); $vm = new ComputerVirtualMachine(); $vm->cleanDBonItemDelete('Computer', $this->fields['id']); }
static function resetOCSLocks($objectId, $entities) { global $DB; $res = array('ok' => 0, 'ko' => 0); $object = new $objectId(); $objecttable = getTableForItemType($objectId); $restrict = ""; if ($object->maybeTemplate()) { $restrict = "`is_template` = '0'"; } if ($object->isEntityAssign() && $entities != -1) { $restrict .= getEntitiesRestrictRequest(" AND ", $objecttable, '', $entities, $object->maybeRecursive()); } $count = countElementsInTable($objecttable, $restrict); $items = getAllDatasFromTable($objecttable, $restrict); $computers = array(); if (!empty($items)) { echo "<div class='center'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><td>"; Html::createProgressBar(__('Work in progress...')); echo "</td></tr></table></div></br>\n"; $i = 0; foreach ($items as $item) { //Fields if (PluginOcsinventoryngOcsServer::deleteInOcsArray($item['id'], 'all', "computer_update", true)) { $res['ok']++; } $i++; $computers[$item['id']] = 1; Html::changeProgressBarPosition($i, $count); } foreach (Item_Devices::getDeviceTypes() as $itemtype) { $res[] = Lock::unlockItems($itemtype, 'Computer', $computers); } $res[] = Lock::unlockItems('Monitor', 'Monitor', $computers); $res[] = Lock::unlockItems('Printer', 'Printer', $computers); $res[] = Lock::unlockItems('Peripheral', 'Peripheral', $computers); $res[] = Lock::unlockItems('SoftwareVersion', 'SoftwareVersion', $computers); $res[] = Lock::unlockItems('NetworkPort', 'Computer', $computers); $res[] = Lock::unlockItems('NetworkName', 'NetworkPort', $computers); $res[] = Lock::unlockItems('IPAddress', 'NetworkName', $computers); $res[] = Lock::unlockItems('ComputerDisk', 'ComputerDisk', $computers); $res[] = Lock::unlockItems('ComputerVirtualMachine', 'ComputerVirtualMachine', $computers); Html::changeProgressBarPosition($i, $count, __('Task completed.')); } return $res; }
/** Update a ocs computer * * @param $ID integer : ID of ocslinks row * @param $plugin_ocsinventoryng_ocsservers_id integer : ocs server ID * @param $dohistory bool : do history ? * @param $force bool : force update ? * * @return action done **/ static function updateComputer($ID, $plugin_ocsinventoryng_ocsservers_id, $dohistory, $force = 0) { global $DB, $PluginOcsinventoryngDBocs, $CFG_GLPI; self::checkOCSconnection($plugin_ocsinventoryng_ocsservers_id); $cfg_ocs = self::getConfig($plugin_ocsinventoryng_ocsservers_id); $query = "SELECT *\n FROM `glpi_plugin_ocsinventoryng_ocslinks`\n WHERE `id` = '{$ID}'\n AND `plugin_ocsinventoryng_ocsservers_id`\n = '{$plugin_ocsinventoryng_ocsservers_id}'"; $result = $DB->query($query); if ($DB->numrows($result) == 1) { $line = $DB->fetch_assoc($result); $comp = new Computer(); $comp->getFromDB($line["computers_id"]); // Get OCS ID $query_ocs = "SELECT *\n FROM `hardware`\n WHERE `ID` = '" . $line['ocsid'] . "'"; $result_ocs = $PluginOcsinventoryngDBocs->query($query_ocs); // Need do history to be 2 not to lock fields if ($dohistory) { $dohistory = 2; } if ($PluginOcsinventoryngDBocs->numrows($result_ocs) == 1) { $data_ocs = Toolbox::addslashes_deep($PluginOcsinventoryngDBocs->fetch_array($result_ocs)); // automatic transfer computer if ($CFG_GLPI['transfers_id_auto'] > 0 && Session::isMultiEntitiesMode()) { self::transferComputer($line, $data_ocs); $comp->getFromDB($line["computers_id"]); } // update last_update and and last_ocs_update $query = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`\n SET `last_update` = '" . $_SESSION["glpi_currenttime"] . "',\n `last_ocs_update` = '" . $data_ocs["LASTDATE"] . "',\n `ocs_agent_version` = '" . $data_ocs["USERAGENT"] . " '\n WHERE `id` = '{$ID}'"; $DB->query($query); if ($force) { $ocs_checksum = self::MAX_CHECKSUM; self::setChecksumForComputer($line['ocsid'], $ocs_checksum); } else { $ocs_checksum = $data_ocs["CHECKSUM"]; } $mixed_checksum = intval($ocs_checksum) & intval($cfg_ocs["checksum"]); //By default log history $loghistory["history"] = 1; // Is an update to do ? if ($mixed_checksum) { // Get updates on computers : $computer_updates = importArrayFromDB($line["computer_update"]); if (!in_array(self::IMPORT_TAG_078, $computer_updates)) { $computer_updates = self::migrateComputerUpdates($line["computers_id"], $computer_updates); } // Update Administrative informations self::updateAdministrativeInfo($line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $computer_updates, $comp->fields['entities_id'], $dohistory); if ($mixed_checksum & pow(2, self::HARDWARE_FL)) { $p = array('computers_id' => $line['computers_id'], 'ocs_id' => $line['ocsid'], 'plugin_ocsinventoryng_ocsservers_id' => $plugin_ocsinventoryng_ocsservers_id, 'cfg_ocs' => $cfg_ocs, 'computers_updates' => $computer_updates, 'dohistory' => $dohistory, 'check_history' => true, 'entities_id' => $comp->fields['entities_id']); $loghistory = self::updateHardware($p); } if ($mixed_checksum & pow(2, self::BIOS_FL)) { self::updateBios($line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $computer_updates, $dohistory, $comp->fields['entities_id']); } // Get import devices $import_device = array(); $types = Item_Devices::getDeviceTypes(); foreach ($types as $old => $type) { $associated_type = str_replace('Item_', '', $type); $associated_table = getTableForItemType($associated_type); $fk = getForeignKeyFieldForTable($associated_table); $query = "SELECT `i`.`id`, `t`.`designation` as `name`\n FROM `" . getTableForItemType($type) . "` as i\n LEFT JOIN `{$associated_table}` as t ON (`t`.`id`=`i`.`{$fk}`)\n WHERE `itemtype`='Computer'\n AND `items_id`='" . $line['computers_id'] . "'\n AND `is_dynamic`"; $prevalue = $type . self::FIELD_SEPARATOR; foreach ($DB->request($query) as $data) { $import_device[$prevalue . $data['id']] = $prevalue . $data["name"]; // TODO voir si il ne serait pas plus simple propre // en adaptant updateDevices // $import_device[$type][$data['id']] = $data["name"]; } } if ($mixed_checksum & pow(2, self::MEMORIES_FL)) { self::updateDevices("Item_DeviceMemory", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); } if ($mixed_checksum & pow(2, self::STORAGES_FL)) { self::updateDevices("Item_DeviceHardDrive", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); self::updateDevices("Item_DeviceDrive", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); } if ($mixed_checksum & pow(2, self::HARDWARE_FL)) { self::updateDevices("Item_DeviceProcessor", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); } if ($mixed_checksum & pow(2, self::VIDEOS_FL)) { self::updateDevices("Item_DeviceGraphicCard", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); } if ($mixed_checksum & pow(2, self::SOUNDS_FL)) { self::updateDevices("Item_DeviceSoundCard", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); } if ($mixed_checksum & pow(2, self::NETWORKS_FL)) { //TODO import_ip ? //$import_ip = importArrayFromDB($line["import_ip"]); self::updateDevices("Item_DeviceNetworkCard", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, array(), $dohistory); } if ($mixed_checksum & pow(2, self::MODEMS_FL) || $mixed_checksum & pow(2, self::PORTS_FL)) { self::updateDevices("Item_DevicePci", $line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $import_device, '', $dohistory); } if ($mixed_checksum & pow(2, self::MONITORS_FL)) { // Get import monitors self::importMonitor($cfg_ocs, $line['computers_id'], $plugin_ocsinventoryng_ocsservers_id, $line['ocsid'], $comp->fields["entities_id"], $dohistory); } if ($mixed_checksum & pow(2, self::PRINTERS_FL)) { // Get import printers self::importPrinter($cfg_ocs, $line['computers_id'], $plugin_ocsinventoryng_ocsservers_id, $line['ocsid'], $comp->fields["entities_id"], $dohistory); } if ($mixed_checksum & pow(2, self::INPUTS_FL)) { // Get import peripheral self::importPeripheral($cfg_ocs, $line['computers_id'], $plugin_ocsinventoryng_ocsservers_id, $line['ocsid'], $comp->fields["entities_id"], $dohistory); } if ($mixed_checksum & pow(2, self::SOFTWARES_FL)) { // Get import software self::updateSoftware($line['computers_id'], $comp->fields["entities_id"], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, !$loghistory["history"] ? 0 : $dohistory); } if ($mixed_checksum & pow(2, self::DRIVES_FL)) { // Get import drives self::updateDisk($line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $dohistory); } if ($mixed_checksum & pow(2, self::REGISTRY_FL)) { //import registry entries not needed self::updateRegistry($line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs); } if ($mixed_checksum & pow(2, self::VIRTUALMACHINES_FL)) { // Get import vm self::updateVirtualMachines($line['computers_id'], $line['ocsid'], $plugin_ocsinventoryng_ocsservers_id, $cfg_ocs, $dohistory); } //Update TAG self::updateTag($line, $data_ocs); // Update OCS Cheksum $newchecksum = "(CHECKSUM - {$mixed_checksum})"; self::setChecksumForComputer($line['ocsid'], $newchecksum, true); //Return code to indicate that computer was synchronized return array('status' => self::COMPUTER_SYNCHRONIZED, 'entitites_id' => $comp->fields["entities_id"], 'rule_matched' => array(), 'computers_id' => $line['computers_id']); } // ELSE Return code to indicate only last inventory date changed return array('status' => self::COMPUTER_NOTUPDATED, 'entities_id' => $comp->fields["entities_id"], 'rule_matched' => array(), 'computers_id' => $line['computers_id']); } } }
/** * Move locks from ocslink.import_* to is_dynamic in related tables * * @param $migration **/ function plugin_ocsinventoryng_migrateComputerLocks(Migration $migration) { global $DB; $import = array('import_printer' => 'Printer', 'import_monitor' => 'Monitor', 'import_peripheral' => 'Peripheral'); foreach ($import as $field => $itemtype) { foreach ($DB->request('ocs_glpi_ocslinks', '', array('computers_id', $field)) as $data) { if (FieldExists('ocs_glpi_ocslinks', $field)) { $import_field = importArrayFromDB($data[$field]); //If array is not empty if (!empty($import_field)) { $query_update = "UPDATE `glpi_computers_items`\n SET `is_dynamic`='1'\n WHERE `id` IN (" . implode(',', array_keys($import_field)) . ")\n AND `itemtype`='{$itemtype}'"; $DB->query($query_update); } } } $migration->dropField('ocs_glpi_ocslinks', $field); } //Migration disks and vms $import = array('import_disk' => 'glpi_computerdisks', 'import_vm' => 'glpi_computervirtualmachines', 'import_software' => 'glpi_computers_softwareversions', 'import_ip' => 'glpi_networkports'); foreach ($import as $field => $table) { if (FieldExists('ocs_glpi_ocslinks', $field)) { foreach ($DB->request('ocs_glpi_ocslinks', '', array('computers_id', $field)) as $data) { $import_field = importArrayFromDB($data[$field]); //If array is not empty if (!empty($import_field)) { $in_where = "(" . implode(',', array_keys($import_field)) . ")"; $query_update = "UPDATE `{$table}`\n SET `is_dynamic`='1'\n WHERE `id` IN {$in_where}"; $DB->query($query_update); if ($table == 'glpi_networkports') { $query_update = "UPDATE `glpi_networkports` AS PORT,\n `glpi_networknames` AS NAME\n SET NAME.`is_dynamic` = 1\n WHERE PORT.`id` IN {$in_where}\n AND NAME.`itemtype` = 'NetworkPort'\n AND NAME.`items_id` = PORT.`id`"; $DB->query($query_update); $query_update = "UPDATE `glpi_networkports` AS PORT,\n `glpi_networknames` AS NAME,\n `glpi_ipaddresses` AS ADDR\n SET ADDR.`is_dynamic` = 1\n WHERE PORT.`id` IN {$in_where}\n AND NAME.`itemtype` = 'NetworkPort'\n AND NAME.`items_id` = PORT.`id`\n AND ADDR.`itemtype` = 'NetworkName'\n AND ADDR.`items_id` = NAME.`id`"; $DB->query($query_update); } } } $migration->dropField('ocs_glpi_ocslinks', $field); } } if (FieldExists('ocs_glpi_ocslinks', 'import_device')) { foreach ($DB->request('ocs_glpi_ocslinks', '', array('computers_id', 'import_device')) as $data) { $import_device = importArrayFromDB($data['import_device']); if (!in_array('_version_078_', $import_device)) { $import_device = plugin_ocsinventoryng_migrateImportDevice($import_device); } $devices = array(); $types = Item_Devices::getDeviceTypes(); foreach ($import_device as $key => $val) { if (!$key) { // OcsServer::IMPORT_TAG_078 continue; } list($type, $nomdev) = explode('$$$$$', $val); list($type, $iddev) = explode('$$$$$', $key); if (!isset($types[$type])) { // should never happen continue; } $devices[$types[$type]][] = $iddev; } foreach ($devices as $type => $data) { //If array is not empty $query_update = "UPDATE `" . getTableForItemType($type) . "`\n SET `is_dynamic`='1'\n WHERE `id` IN (" . implode(',', $data) . ")"; $DB->query($query_update); } } $migration->dropField('ocs_glpi_ocslinks', 'import_device'); } $migration->migrationOneTable('ocs_glpi_ocslinks'); }
/** * Get all the types that can have a document * * @since version 0.85 * * @return array of the itemtypes **/ static function getItemtypesThatCanHave() { global $CFG_GLPI; return array_merge($CFG_GLPI['document_types'], CommonDevice::getDeviceTypes(), Item_Devices::getDeviceTypes()); }
/** * Get the standard massive actions * * @param $item the item for which we want the massive actions * @param $is_deleted massive action for deleted items ? (default 0) * @param $checkitem link item to check right (default NULL) * * @return an array of massive actions or false if $item is not valid **/ static function getAllMassiveActions($item, $is_deleted = 0, CommonDBTM $checkitem = NULL) { global $CFG_GLPI, $PLUGIN_HOOKS; // TODO: when maybe* will be static, when can completely switch to $itemtype ! if (is_string($item)) { $itemtype = $item; if (!($item = getItemForItemtype($itemtype))) { return false; } } else { if ($item instanceof CommonDBTM) { $itemtype = $item->getType(); } else { return false; } } if (!is_null($checkitem)) { $canupdate = $checkitem->canUpdate(); $candelete = $checkitem->canDelete(); $canpurge = $checkitem->canPurge(); } else { $canupdate = $itemtype::canUpdate(); $candelete = $itemtype::canDelete(); $canpurge = $itemtype::canPurge(); } $actions = array(); $self_pref = __CLASS__ . self::CLASS_ACTION_SEPARATOR; if ($is_deleted) { if ($canpurge) { if (in_array($itemtype, Item_Devices::getConcernedItems())) { $actions[$self_pref . 'purge_item_but_devices'] = _x('button', 'Delete permanently but keep devices'); $actions[$self_pref . 'purge'] = _x('button', 'Delete permanently and remove devices'); } else { $actions[$self_pref . 'purge'] = _x('button', 'Delete permanently'); } $actions[$self_pref . 'restore'] = _x('button', 'Restore'); } } else { if ($_SESSION['glpiactiveprofile']['interface'] == 'central' && ($canupdate || InfoCom::canApplyOn($itemtype) && Infocom::canUpdate())) { //TRANS: select action 'update' (before doing it) $actions[$self_pref . 'update'] = _x('button', 'Update'); } Infocom::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem); CommonDBConnexity::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem); // do not take into account is_deleted if items may be dynamic if ($item->maybeDeleted() && !$item->useDeletedToLockIfDynamic()) { if ($candelete) { $actions[$self_pref . 'delete'] = _x('button', 'Put in dustbin'); } } else { if ($canpurge) { $actions[$self_pref . 'purge'] = _x('button', 'Delete permanently'); if ($item instanceof CommonDropdown) { $actions[$self_pref . 'purge_but_item_linked'] = _x('button', 'Delete permanently even if linked items'); } } } Document::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem); Contract::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem); // Specific actions $actions += $item->getSpecificMassiveActions($checkitem); // Plugin Specific actions if (isset($PLUGIN_HOOKS['use_massive_action'])) { foreach ($PLUGIN_HOOKS['use_massive_action'] as $plugin => $val) { $plug_actions = Plugin::doOneHook($plugin, 'MassiveActions', $itemtype); if (count($plug_actions)) { $actions += $plug_actions; } } } } Lock::getMassiveActionsForItemtype($actions, $itemtype, $is_deleted, $checkitem); // Manage forbidden actions : try complete action name or MassiveAction:action_name $forbidden_actions = $item->getForbiddenStandardMassiveAction(); if (is_array($forbidden_actions) && count($forbidden_actions)) { foreach ($forbidden_actions as $actiontodel) { if (isset($actions[$actiontodel])) { unset($actions[$actiontodel]); } else { // Not found search adding MassiveAction prefix $actiontodel = $self_pref . $actiontodel; if (isset($actions[$actiontodel])) { unset($actions[$actiontodel]); } } } } return $actions; }
/** * Display form to unlock fields and links * * @param CommonDBTM $item the source item **/ static function showForItem(CommonDBTM $item) { global $DB; $ID = $item->getID(); $itemtype = $item->getType(); $header = false; //If user doesn't have write right on the item, lock form must not be displayed if (!$item->canCreate()) { return false; } echo "<div width='50%'>"; echo "<form method='post' id='lock_form'\n name='lock_form' action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>"; echo "<input type='hidden' name='id' value='{$ID}'>\n"; echo "<input type='hidden' name='itemtype' value='{$itemtype}'>\n"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='2''>" . __('Locked items') . "</th></tr>"; //Use a hook to allow external inventory tools to manage per field lock $results = Plugin::doHookFunction('display_locked_fields', array('item' => $item, 'header' => $header)); $header |= $results['header']; //Special locks for computers only if ($itemtype == 'Computer') { //Locks for items recorded in glpi_computers_items table $types = array('Monitor', 'Peripheral', 'Printer'); foreach ($types as $type) { $params = array('is_dynamic' => 1, 'is_deleted' => 1, 'computers_id' => $ID, 'itemtype' => $type); $params['FIELDS'] = array('id', 'items_id'); $first = true; foreach ($DB->request('glpi_computers_items', $params) as $line) { $tmp = new $type(); $tmp->getFromDB($line['items_id']); $header = true; if ($first) { echo "<tr><th colspan='2'>" . $type::getTypeName(2) . "</th></tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='Computer_Item[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $tmp->getName() . "</td>"; echo "</tr>\n"; } } $types = array('ComputerDisk', 'ComputerVirtualMachine'); foreach ($types as $type) { $params = array('is_dynamic' => 1, 'is_deleted' => 1, 'computers_id' => $ID); $params['FIELDS'] = array('id', 'name'); $first = true; foreach ($DB->request(getTableForItemType($type), $params) as $line) { $header = true; if ($first) { echo "<tr><th colspan='2'>" . $type::getTypeName(2) . "</th></tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='" . $type . "[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $line['name'] . "</td>"; echo "</tr>\n"; } } //Software versions $params = array('is_dynamic' => 1, 'is_deleted' => 1, 'computers_id' => $ID); $first = true; $query = "SELECT `csv`.`id` AS `id`,\n `sv`.`name` AS `version`,\n `s`.`name` AS `software`\n FROM `glpi_computers_softwareversions` AS csv\n LEFT JOIN `glpi_softwareversions` AS sv\n ON (`csv`.`softwareversions_id` = `sv`.`id`)\n LEFT JOIN `glpi_softwares` AS s\n ON (`sv`.`softwares_id` = `s`.`id`)\n WHERE `csv`.`is_deleted` = '1'\n AND `csv`.`is_dynamic` = '1'\n AND `csv`.`computers_id` = '{$ID}'"; foreach ($DB->request($query) as $line) { $header = true; if ($first) { echo "<tr><th colspan='2'>" . Software::getTypeName(2) . "</th></tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='Computer_SoftwareVersion[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $line['software'] . " " . $line['version'] . "</td>"; echo "</tr>\n"; } //Software licenses $params = array('is_dynamic' => 1, 'is_deleted' => 1, 'computers_id' => $ID); $first = true; $query = "SELECT `csv`.`id` AS `id`,\n `sv`.`name` AS `version`,\n `s`.`name` AS `software`\n FROM `glpi_computers_softwarelicenses` AS csv\n LEFT JOIN `glpi_softwarelicenses` AS sv\n ON (`csv`.`softwarelicenses_id` = `sv`.`id`)\n LEFT JOIN `glpi_softwares` AS s\n ON (`sv`.`softwares_id` = `s`.`id`)\n WHERE `csv`.`is_deleted` = '1'\n AND `csv`.`is_dynamic` = '1'\n AND `csv`.`computers_id` = '{$ID}'"; foreach ($DB->request($query) as $line) { $header = true; if ($first) { echo "<tr><th colspan='2'>" . SoftwareLicense::getTypeName(2) . "</th>" . "</tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='Computer_SoftwareLicense[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $line['software'] . " " . $line['version'] . "</td>"; echo "</tr>\n"; } } $first = true; $item = new NetworkPort(); $params = array('is_dynamic' => 1, 'is_deleted' => 1, 'items_id' => $ID, 'itemtype' => $itemtype); $params['FIELDS'] = array('id'); foreach ($DB->request('glpi_networkports', $params) as $line) { $item->getFromDB($line['id']); $header = true; if ($first) { echo "<tr><th colspan='2'>" . NetworkPort::getTypeName(2) . "</th></tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='NetworkPort[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $item->getName() . "</td>"; echo "</tr>\n"; } $first = true; $item = new NetworkName(); $params = array('`glpi_networknames`.`is_dynamic`' => 1, '`glpi_networknames`.`is_deleted`' => 1, '`glpi_networknames`.`itemtype`' => 'NetworkPort', '`glpi_networknames`.`items_id`' => '`glpi_networkports`.`id`', '`glpi_networkports`.`items_id`' => $ID, '`glpi_networkports`.`itemtype`' => $itemtype); $params['FIELDS'] = array('glpi_networknames' => 'id'); foreach ($DB->request(array('glpi_networknames', 'glpi_networkports'), $params) as $line) { $item->getFromDB($line['id']); $header = true; if ($first) { echo "<tr><th colspan='2'>" . NetworkName::getTypeName(2) . "</th></tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='NetworkName[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $item->getName() . "</td>"; echo "</tr>\n"; } $first = true; $item = new IPAddress(); $params = array('`glpi_ipaddresses`.`is_dynamic`' => 1, '`glpi_ipaddresses`.`is_deleted`' => 1, '`glpi_ipaddresses`.`itemtype`' => 'Networkname', '`glpi_ipaddresses`.`items_id`' => '`glpi_networknames`.`id`', '`glpi_networknames`.`itemtype`' => 'NetworkPort', '`glpi_networknames`.`items_id`' => '`glpi_networkports`.`id`', '`glpi_networkports`.`items_id`' => $ID, '`glpi_networkports`.`itemtype`' => $itemtype); $params['FIELDS'] = array('glpi_ipaddresses' => 'id'); foreach ($DB->request(array('glpi_ipaddresses', 'glpi_networknames', 'glpi_networkports'), $params) as $line) { $item->getFromDB($line['id']); $header = true; if ($first) { echo "<tr><th colspan='2'>" . IPAddress::getTypeName(2) . "</th></tr>\n"; $first = false; } echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='IPAddress[" . $line['id'] . "]'></td>"; echo "<td class='left' width='95%'>" . $item->getName() . "</td>"; echo "</tr>\n"; } $types = Item_Devices::getDeviceTypes(); $nb = 0; foreach ($types as $old => $type) { $nb += countElementsInTable(getTableForItemType($type), "`items_id`='{$ID}'\n AND `itemtype`='{$itemtype}'\n AND `is_dynamic`='1'\n AND `is_deleted`='1'"); } if ($nb) { $header = true; echo "<tr><th colspan='2'>" . _n('Component', 'Components', 2) . "</th></tr>\n"; foreach ($types as $old => $type) { $associated_type = str_replace('Item_', '', $type); $associated_table = getTableForItemType($associated_type); $fk = getForeignKeyFieldForTable($associated_table); $query = "SELECT `i`.`id`,\n `t`.`designation` AS `name`\n FROM `" . getTableForItemType($type) . "` AS i\n LEFT JOIN `{$associated_table}` AS t\n ON (`t`.`id` = `i`.`{$fk}`)\n WHERE `itemtype` = '{$itemtype}'\n AND `items_id` = '{$ID}'\n AND `is_dynamic` = '1'\n AND `is_deleted` = '1'"; foreach ($DB->request($query) as $data) { echo "<tr class='tab_bg_1'><td class='center' width='10'>"; echo "<input type='checkbox' name='" . $type . "[" . $data['id'] . "]'></td>"; echo "<td class='left' width='95%'>"; printf(__('%1$s: %2$s'), $associated_type::getTypeName(), $data['name']); echo "</td></tr>\n"; } } } if ($header) { echo "</table>"; Html::openArrowMassives('lock_form', true); Html::closeArrowMassives(array('unlock' => _sx('button', 'Unlock'))); } else { echo "<tr class='tab_bg_2'>"; echo "<td class='center' colspan='2'>" . __('No locked item') . "</td></tr>"; echo "</table>"; } Html::closeForm(); echo "</div>\n"; }
/** * Transfer devices of an item * * @param $itemtype original type of transfered item * @param $ID ID of the item * @param $newID new ID of the item **/ function transferDevices($itemtype, $ID, $newID) { global $DB, $CFG_GLPI; // Only same case because no duplication of computers switch ($this->options['keep_device']) { // delete devices case 0: foreach (Item_Devices::getItemAffinities($itemtype) as $type) { $table = getTableForItemType($type); $query = "DELETE\n FROM `{$table}`\n WHERE `itemtype` = '{$itemtype}'\n AND `items_id` = '{$ID}'"; $result = $DB->query($query); } // Keep devices // Keep devices default: foreach (Item_Devices::getItemAffinities($itemtype) as $itemdevicetype) { $itemdevicetable = getTableForItemType($itemdevicetype); $devicetype = $itemdevicetype::getDeviceType(); $devicetable = getTableForItemType($devicetype); $fk = getForeignKeyFieldForTable($devicetable); $device = new $devicetype(); // Get contracts for the item $query = "SELECT *\n FROM `{$itemdevicetable}`\n WHERE `items_id` = '{$ID}'\n AND `itemtype` = '{$itemtype}'\n AND `{$fk}` NOT IN " . $this->item_recurs[$devicetype]; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Foreach get item while ($data = $DB->fetch_assoc($result)) { $item_ID = $data[$fk]; $newdeviceID = -1; // is already transfer ? if (isset($this->already_transfer[$devicetype][$item_ID])) { $newdeviceID = $this->already_transfer[$devicetype][$item_ID]; } 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 `{$itemdevicetable}`\n WHERE `{$fk}` = '{$item_ID}'"; if ($result_type = $DB->query($query)) { if ($DB->numrows($result_type) > 0) { while (($data_type = $DB->fetch_assoc($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 `{$itemdevicetable}`\n WHERE `{$fk}` = '{$item_ID}'\n AND `itemtype` = '{$dtype}'\n AND `items_id`\n NOT IN " . $this->item_search[$dtype]; $result_search = $DB->query($query_search); if ($DB->result($result_search, 0, 'cpt') > 0) { $canbetransfer = false; } } else { $canbetransfer = false; } } } } // Yes : transfer if ($canbetransfer) { $this->transferItem($devicetype, $item_ID, $item_ID); $newdeviceID = $item_ID; } else { $device->getFromDB($item_ID); // No : search device $field = "name"; if (!FieldExists($devicetable, "name")) { $field = "designation"; } $query = "SELECT *\n FROM `{$devicetable}`\n WHERE `entities_id` = '" . $this->to . "'\n AND `" . $field . "` = '" . addslashes($device->fields[$field]) . "'"; if ($result_search = $DB->query($query)) { if ($DB->numrows($result_search) > 0) { $newdeviceID = $DB->result($result_search, 0, 'id'); $this->addToAlreadyTransfer($devicetype, $item_ID, $newdeviceID); } } // found : use it // not found : copy contract if ($newdeviceID < 0) { // 1 - create new item unset($device->fields['id']); $input = $device->fields; // Fix for fields with NULL in DB foreach ($input as $key => $value) { if ($value == '') { unset($input[$key]); } } $input['entities_id'] = $this->to; unset($device->fields); $newdeviceID = $device->add(Toolbox::addslashes_deep($input)); // 2 - transfer as copy $this->transferItem($devicetype, $item_ID, $newdeviceID); } } } // Update links $query = "UPDATE `{$itemdevicetable}`\n SET `{$fk}` = '{$newdeviceID}',\n `items_id` = '{$newID}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); $this->transferItem($itemdevicetype, $data['id'], $data['id']); } } } } break; } }
/** * Update from 0.83.1 to 0.84 * * @return bool for success (will die for most error) **/ function update0831to084() { global $DB, $migration; $updateresult = true; $ADDTODISPLAYPREF = array(); //TRANS: %s is the number of new version $migration->displayTitle(sprintf(__('Update to %s'), '0.84')); $migration->setVersion('0.84'); // Add the internet field and copy rights from networking $migration->addField('glpi_profiles', 'internet', 'char', array('after' => 'networking', 'update' => '`networking`')); $backup_tables = false; $newtables = array('glpi_contractcosts', 'glpi_entities_rssfeeds', 'glpi_groups_rssfeeds', 'glpi_problems_suppliers', 'glpi_profiles_rssfeeds', 'glpi_rssfeeds_users', 'glpi_rssfeeds', 'glpi_suppliers_tickets', 'glpi_ticketcosts'); foreach ($newtables as $new_table) { // rename new tables if exists ? if (TableExists($new_table)) { $migration->dropTable("backup_{$new_table}"); $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}."); $backup_tables = true; $query = $migration->renameTable("{$new_table}", "backup_{$new_table}"); } } if ($backup_tables) { $migration->displayWarning("You can delete backup tables if you have no need of them.", true); } updateNetworkFramework($ADDTODISPLAYPREF); $migration->addField('glpi_mailcollectors', 'accepted', 'string'); $migration->addField('glpi_mailcollectors', 'refused', 'string'); $migration->addField('glpi_mailcollectors', 'use_kerberos', 'bool', array('value' => 0)); $migration->addField("glpi_mailcollectors", 'errors', "integer"); $migration->addField("glpi_mailcollectors", 'use_mail_date', "bool", array('value' => 0)); // Password security $migration->addField('glpi_configs', 'use_password_security', 'bool'); $migration->addField('glpi_configs', 'password_min_length', 'integer', array('value' => 8)); $migration->addField('glpi_configs', 'password_need_number', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'password_need_letter', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'password_need_caps', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'password_need_symbol', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'use_check_pref', 'bool'); // Ajax buffer time $migration->addField('glpi_configs', 'ajax_buffertime_load', 'integer', array('value' => 0, 'after' => 'ajax_min_textsearch_load')); // Clean display prefs $query = "UPDATE `glpi_displaypreferences`\n SET `num` = 160\n WHERE `itemtype` = 'Software'\n AND `num` = 7"; $DB->query($query); // Update bookmarks from States to AllAssets foreach ($DB->request("glpi_bookmarks", "`itemtype` = 'States'") as $data) { $query = str_replace('itemtype=States', 'itemtype=AllAssets', $data['query']); $query = "UPDATE `glpi_bookmarks`\n SET query = '" . addslashes($query) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } $query = "UPDATE `glpi_bookmarks`\n SET `itemtype` = 'AllAssets', `path` = 'front/allassets.php'\n WHERE `itemtype` = 'States'"; $DB->query($query); $query = "UPDATE `glpi_displaypreferences`\n SET `itemtype` = 'AllAssets'\n WHERE `itemtype` = 'States'"; $DB->query($query); if (TableExists('glpi_networkportmigrations')) { $migration->displayWarning("You should have a look at the \"migration cleaner\" tool !", true); $migration->displayWarning("With it, you should re-create the networks topologies and the links between the networks and the addresses", true); } $lang_to_update = array('ca_CA' => 'ca_ES', 'dk_DK' => 'da_DK', 'ee_ET' => 'et_EE', 'el_EL' => 'el_GR', 'he_HE' => 'he_IL', 'no_NB' => 'nb_NO', 'no_NN' => 'nn_NO', 'ua_UA' => 'uk_UA'); foreach ($lang_to_update as $old => $new) { $query = "UPDATE `glpi_configs`\n SET `language` = '{$new}'\n WHERE `language` = '{$old}';"; $DB->queryOrDie($query, "0.84 language in config {$old} to {$new}"); $query = "UPDATE `glpi_users`\n SET `language` = '{$new}'\n WHERE `language` = '{$old}';"; $DB->queryOrDie($query, "0.84 language in users {$old} to {$new}"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and problems status')); $status = array('new' => CommonITILObject::INCOMING, 'assign' => CommonITILObject::ASSIGNED, 'plan' => CommonITILObject::PLANNED, 'waiting' => CommonITILObject::WAITING, 'solved' => CommonITILObject::SOLVED, 'closed' => CommonITILObject::CLOSED, 'accepted' => CommonITILObject::ACCEPTED, 'observe' => CommonITILObject::OBSERVED, 'evaluation' => CommonITILObject::EVALUATION, 'approbation' => CommonITILObject::APPROVAL, 'test' => CommonITILObject::TEST, 'qualification' => CommonITILObject::QUALIFICATION); foreach (array('glpi_tickets', 'glpi_problems') as $table) { // Migrate datas foreach ($status as $old => $new) { $query = "UPDATE `{$table}`\n SET `status` = '{$new}'\n WHERE `status` = '{$old}'"; $DB->queryOrDie($query, "0.84 status in {$table} {$old} to {$new}"); } $migration->changeField($table, 'status', 'status', 'integer', array('value' => CommonITILObject::INCOMING)); } // Migrate templates $query = "SELECT `glpi_notificationtemplatetranslations`.*\n FROM `glpi_notificationtemplatetranslations`\n INNER JOIN `glpi_notificationtemplates`\n ON (`glpi_notificationtemplates`.`id`\n = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n WHERE `glpi_notificationtemplatetranslations`.`content_text` LIKE '%storestatus=%'\n OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%storestatus=%'\n OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%storestatus=%'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $subject = $data['subject']; $text = $data['content_text']; $html = $data['content_html']; foreach ($status as $old => $new) { $subject = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $subject); $text = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $text); $html = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $html); $subject = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $subject); $text = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $text); $html = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $html); } $query = "UPDATE `glpi_notificationtemplatetranslations`\n SET `subject` = '" . addslashes($subject) . "',\n `content_text` = '" . addslashes($text) . "',\n `content_html` = '" . addslashes($html) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->queryOrDie($query, "0.84 fix tags usage for storestatus"); } } } // Update Rules $changes = array(); $changes['RuleTicket'] = 'status'; $DB->query("SET SESSION group_concat_max_len = 4194304;"); foreach ($changes as $ruletype => $field) { // Get rules $query = "SELECT GROUP_CONCAT(`id`)\n FROM `glpi_rules`\n WHERE `sub_type` = '" . $ruletype . "'\n GROUP BY `sub_type`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Get rule string $rules = $DB->result($result, 0, 0); // Update actions foreach ($status as $old => $new) { $query = "UPDATE `glpi_ruleactions`\n SET `value` = '{$new}'\n WHERE `field` = '{$field}'\n AND `value` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 update datas for rules actions"); } } } } // Update glpi_profiles : ticket_status foreach ($DB->request('glpi_profiles') as $data) { $fields_to_decode = array('ticket_status', 'problem_status'); foreach ($fields_to_decode as $field) { $tab = importArrayFromDB($data[$field]); if (is_array($tab)) { $newtab = array(); foreach ($tab as $key => $values) { foreach ($values as $key2 => $val2) { $newtab[$status[$key]][$status[$key2]] = $val2; } } $query = "UPDATE `glpi_profiles`\n SET `{$field}` = '" . addslashes(exportArrayToDB($newtab)) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query, "0.84 migrate {$field} of glpi_profiles"); } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Merge entity and entitydatas')); if (TableExists('glpi_entitydatas')) { $migration->changeField('glpi_entities', 'id', 'id', 'integer'); $migration->migrationOneTable('glpi_entities'); // pour que la procedure soit re-entrante if (countElementsInTable("glpi_entities", "id=0") < 1) { // Create root entity $query = "INSERT INTO `glpi_entities`\n (`id`, `name`, `completename`, `entities_id`, `level`)\n VALUES (0,'" . addslashes(__('Root entity')) . "',\n '" . addslashes(__('Root entity')) . "', '-1', '1');"; $DB->queryOrDie($query, '0.84 insert root entity into glpi_entities'); } // $newID = $DB->insert_id(); // $query = "UPDATE `glpi_entities` // SET `id` = '0' // WHERE `id` = '$newID'"; // $DB->queryOrDie($query, '0.84 be sure that id of the root entity if 0 in glpi_entities'); $migration->addField("glpi_entities", 'address', "text"); $migration->addField("glpi_entities", 'postcode', "string"); $migration->addField("glpi_entities", 'town', "string"); $migration->addField("glpi_entities", 'state', "string"); $migration->addField("glpi_entities", 'country', "string"); $migration->addField("glpi_entities", 'website', "string"); $migration->addField("glpi_entities", 'phonenumber', "string"); $migration->addField("glpi_entities", 'fax', "string"); $migration->addField("glpi_entities", 'email', "string"); $migration->addField("glpi_entities", 'admin_email', "string"); $migration->addField("glpi_entities", 'admin_email_name', "string"); $migration->addField("glpi_entities", 'admin_reply', "string"); $migration->addField("glpi_entities", 'admin_reply_name', "string"); $migration->addField("glpi_entities", 'notification_subject_tag', "string"); $migration->addField("glpi_entities", 'notepad', "longtext"); $migration->addField("glpi_entities", 'ldap_dn', "string"); $migration->addField("glpi_entities", 'tag', "string"); $migration->addField("glpi_entities", 'authldaps_id', "integer"); $migration->addField("glpi_entities", 'mail_domain', "string"); $migration->addField("glpi_entities", 'entity_ldapfilter', "text"); $migration->addField("glpi_entities", 'mailing_signature', "text"); $migration->addField("glpi_entities", 'cartridges_alert_repeat', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'consumables_alert_repeat', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_licenses_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_contracts_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_infocoms_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_reservations_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'autoclose_delay', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'notclosed_delay', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'calendars_id', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'auto_assign_mode', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'tickettype', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'max_closedate', "datetime"); $migration->addField("glpi_entities", 'inquest_config', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'inquest_rate', "integer"); $migration->addField("glpi_entities", 'inquest_delay', "integer", array('value' => -10)); $migration->addField("glpi_entities", 'inquest_URL', "string"); $migration->addField("glpi_entities", 'autofill_warranty_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_use_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_buy_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_delivery_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_order_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'tickettemplates_id', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'entities_id_software', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'default_contract_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'default_infocom_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'default_alarm_threshold', "integer", array('value' => -2)); $migration->migrationOneTable('glpi_entities'); $fields = array('address', 'postcode', 'town', 'state', 'country', 'website', 'phonenumber', 'fax', 'email', 'admin_email', 'admin_email_name', 'admin_reply', 'admin_reply_name', 'notification_subject_tag', 'notepad', 'ldap_dn', 'tag', 'authldaps_id', 'mail_domain', 'entity_ldapfilter', 'mailing_signature', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'use_licenses_alert', 'use_contracts_alert', 'use_infocoms_alert', 'use_reservations_alert', 'autoclose_delay', 'notclosed_delay', 'calendars_id', 'auto_assign_mode', 'tickettype', 'max_closedate', 'inquest_config', 'inquest_rate', 'inquest_delay', 'inquest_URL', 'autofill_warranty_date', 'autofill_use_date', 'autofill_buy_date', 'autofill_delivery_date', 'autofill_order_date', 'tickettemplates_id', 'entities_id_software', 'default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold'); $entity = new Entity(); foreach ($DB->request('glpi_entitydatas') as $data) { if ($entity->getFromDB($data['entities_id'])) { $update_fields = array(); foreach ($fields as $field) { if (is_null($data[$field])) { $update_fields[] = "`{$field}` = NULL"; } else { $update_fields[] = "`{$field}` = '" . addslashes($data[$field]) . "'"; } } $query = "UPDATE `glpi_entities`\n SET " . implode(',', $update_fields) . "\n WHERE `id` = '" . $data['entities_id'] . "'"; $DB->queryOrDie($query, "0.84 transfer datas from glpi_entitydatas to glpi_entities"); } else { $migration->displayMessage('Entity ID ' . $data['entities_id'] . ' does not exist'); } } $migration->dropTable('glpi_entitydatas'); } regenerateTreeCompleteName("glpi_entities"); $migration->displayMessage(sprintf(__('Data migration - %s'), 'copy entity information to computers_softwareversions')); if ($migration->addField("glpi_computers_softwareversions", "entities_id", "integer")) { $migration->migrationOneTable('glpi_computers_softwareversions'); $query3 = "UPDATE `glpi_computers_softwareversions`\n LEFT JOIN `glpi_computers`\n ON `computers_id`=`glpi_computers`.`id`\n SET `glpi_computers_softwareversions`.`entities_id` = `glpi_computers`.`entities_id`"; $DB->queryOrDie($query3, "0.84 update entities_id in glpi_computers_softwareversions"); /// create index for search count on tab $migration->addKey("glpi_computers_softwareversions", array('entities_id', 'is_template', 'is_deleted'), 'computers_info'); $migration->addKey("glpi_computers_softwareversions", 'is_template'); $migration->addKey("glpi_computers_softwareversions", 'is_deleted'); } /// create new index for search $migration->addKey("glpi_softwarelicenses", array('softwares_id', 'expire'), 'softwares_id_expire'); $migration->dropKey("glpi_softwarelicenses", 'softwares_id'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'create validation_answer notification')); // Check if notifications already exists if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n AND `event` = 'validation_answer'") == 0) { // No notifications duplicate all $query = "SELECT *\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Ticket'\n AND `event` = 'validation'"; foreach ($DB->request($query) as $notif) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . addslashes($notif['name']) . " Answer',\n '" . $notif['entities_id'] . "', 'Ticket',\n 'validation_answer', '" . $notif['mode'] . "',\n '" . $notif['notificationtemplates_id'] . "',\n '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n '" . $notif['is_active'] . "', NOW());"; $DB->queryOrDie($query, "0.84 insert validation_answer notification"); $newID = $DB->insert_id(); $query2 = "SELECT *\n FROM `glpi_notificationtargets`\n WHERE `notifications_id` = '" . $notif['id'] . "'"; foreach ($DB->request($query2) as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`notifications_id`, `type`, `items_id`)\n VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')"; $DB->queryOrDie($query, "0.84 insert targets for validation_answer notification"); } } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'create contracts notification')); $from_to = array('end' => 'periodicity', 'notice' => 'periodicitynotice'); foreach ($from_to as $from => $to) { // Check if notifications already exists if (countElementsInTable('glpi_notifications', "`itemtype` = 'Contract' AND `event` = '{$to}'") == 0) { // No notifications duplicate all $query = "SELECT *\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Contract'\n AND `event` = '{$from}'"; foreach ($DB->request($query) as $notif) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . addslashes($notif['name']) . " Periodicity',\n '" . $notif['entities_id'] . "', 'Contract', '{$to}', '" . $notif['mode'] . "',\n '" . $notif['notificationtemplates_id'] . "',\n '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n '" . $notif['is_active'] . "', NOW());"; $DB->queryOrDie($query, "0.84 insert contract " . $to . " notification"); $newID = $DB->insert_id(); $query2 = "SELECT *\n FROM `glpi_notificationtargets`\n WHERE `notifications_id` = '" . $notif['id'] . "'"; foreach ($DB->request($query2) as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`notifications_id`, `type`, `items_id`)\n VALUES ('" . $newID . "', '" . $target['type'] . "', '" . $target['items_id'] . "')"; $DB->queryOrDie($query, "0.84 insert targets for ĉontract " . $to . " notification"); } } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'contract and ticket costs')); if (!TableExists('glpi_contractcosts')) { $query = "CREATE TABLE `glpi_contractcosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `contracts_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `contracts_id` (`contracts_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_contractcosts"); $migration->migrationOneTable('glpi_contractcosts'); foreach ($DB->request('glpi_contracts', "`cost` > 0") as $data) { $begin_to_add = "NULL"; $end_to_add = "NULL"; if (!is_null($data['begin_date'])) { $begin_to_add = "'" . $data['begin_date'] . "'"; if ($data['duration']) { $end_to_add = "'" . date("Y-m-d", strtotime($data['begin_date'] . "+" . $data['duration'] . " month")) . "'"; } else { $end_to_add = "'" . $data['begin_date'] . "'"; } } $query = "INSERT INTO `glpi_contractcosts`\n (`contracts_id`, `name`, `begin_date`, `end_date`,\n `cost`, `entities_id`,\n `is_recursive`)\n VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n '" . $data['cost'] . "', '" . $data['entities_id'] . "',\n '" . $data['is_recursive'] . "')"; $DB->queryOrDie($query, '0.84 move contracts costs'); } $migration->dropField('glpi_contracts', 'cost'); } if (!TableExists('glpi_ticketcosts')) { $query = "CREATE TABLE `glpi_ticketcosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `tickets_id` (`tickets_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_ticketcosts"); $migration->migrationOneTable('glpi_ticketcosts'); foreach ($DB->request('glpi_tickets', "`cost_time` > 0\n OR `cost_fixed` > 0\n OR `cost_material` > 0") as $data) { $begin_to_add = "NULL"; $end_to_add = "NULL"; if (!is_null($data['date'])) { $begin_to_add = "'" . $data['date'] . "'"; if (!is_null($data['solvedate'])) { $end_to_add = "'" . $data['solvedate'] . "'"; } else { $end_to_add = "'" . $data['date'] . "'"; } } $query = "INSERT INTO `glpi_ticketcosts`\n (`tickets_id`, `name`, `begin_date`, `end_date`,\n `cost_time`,`cost_fixed`,\n `cost_material`, `entities_id`,\n `actiontime`)\n VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n '" . $data['cost_time'] . "','" . $data['cost_fixed'] . "',\n '" . $data['cost_material'] . "', '" . $data['entities_id'] . "',\n '" . $data['actiontime'] . "')"; $DB->queryOrDie($query, '0.84 move tickets costs'); } $migration->dropField('glpi_tickets', 'cost_time'); $migration->dropField('glpi_tickets', 'cost_fixed'); $migration->dropField('glpi_tickets', 'cost_material'); } $migration->addField("glpi_profiles", "ticketcost", "char", array('update' => "'w'", 'condition' => " WHERE `update_ticket` = 1")); // Set default to r as before $query = "UPDATE `glpi_profiles`\n SET `ticketcost` = 'r'\n WHERE `ticketcost` IS NULL"; $DB->queryOrDie($query, "0.84 set ticketcost in glpi_profiles"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'rss flows')); if (!TableExists('glpi_rssfeeds')) { $query = "CREATE TABLE `glpi_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) DEFAULT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `url` text COLLATE utf8_unicode_ci,\n `refresh_rate` int(11) NOT NULL DEFAULT '86400',\n `max_items` int(11) NOT NULL DEFAULT '20',\n `have_error` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `date_mod` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `users_id` (`users_id`),\n KEY `date_mod` (`date_mod`),\n KEY `have_error` (`have_error`),\n KEY `is_active` (`is_active`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds"); $ADDTODISPLAYPREF['RSSFeed'] = array(2, 4, 5, 19, 6, 7); } if (!TableExists('glpi_rssfeeds_users')) { $query = "CREATE TABLE `glpi_rssfeeds_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `users_id` (`users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds_users"); } if (!TableExists('glpi_groups_rssfeeds')) { $query = "CREATE TABLE `glpi_groups_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `groups_id` (`groups_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_groups_rssfeeds"); } if (!TableExists('glpi_profiles_rssfeeds')) { $query = "CREATE TABLE `glpi_profiles_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `profiles_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `profiles_id` (`profiles_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_profiles_rssfeeds"); } if (!TableExists('glpi_entities_rssfeeds')) { $query = "CREATE TABLE `glpi_entities_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_entities_rssfeeds"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'planning recalls')); if (!TableExists('glpi_planningrecalls')) { $query = "CREATE TABLE `glpi_planningrecalls` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `items_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `before_time` int(11) NOT NULL DEFAULT '-10',\n `when` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `users_id` (`users_id`),\n KEY `before_time` (`before_time`),\n KEY `when` (`when`),\n UNIQUE KEY `unicity` (`itemtype`,`items_id`, `users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_planningrecalls"); } $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'PlanningRecall'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Planning recall', 'PlanningRecall', NOW())"; $DB->queryOrDie($query, "0.84 add planning recall notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##recall.action##: ##recall.item.name##',\n '##recall.action##: ##recall.item.name##\n\n##recall.item.content##\n\n##lang.recall.planning.begin##: ##recall.planning.begin##\n##lang.recall.planning.end##: ##recall.planning.end##\n##lang.recall.planning.state##: ##recall.planning.state##\n##lang.recall.item.private##: ##recall.item.private##',\n'<p>##recall.action##: <a href=\"##recall.item.url##\">##recall.item.name##</a></p>\n<p>##recall.item.content##</p>\n<p>##lang.recall.planning.begin##: ##recall.planning.begin##<br />##lang.recall.planning.end##: ##recall.planning.end##<br />##lang.recall.planning.state##: ##recall.planning.state##<br />##lang.recall.item.private##: ##recall.item.private##<br /><br /></p>\n<p><br /><br /></p>')"; $DB->queryOrDie($query, "0.84 add planning recall notification translation"); $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('Planning recall', 0, 'PlanningRecall', 'planningrecall', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.84 add planning recall notification"); $notifid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::AUTHOR . ");"; $DB->queryOrDie($query, "0.84 add planning recall notification target"); } } if (!countElementsInTable('glpi_crontasks', "`itemtype`='PlanningRecall' AND `name`='planningrecall'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('PlanningRecall', 'planningrecall', 300, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.84 populate glpi_crontasks for planningrecall"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various fields')); $migration->changeField('glpi_entities', 'default_alarm_threshold', 'default_cartridges_alarm_threshold', 'integer', array('value' => -2)); $migration->migrationOneTable('glpi_entities'); $migration->addField("glpi_entities", 'default_consumables_alarm_threshold', "integer", array('value' => -2, 'update' => 'default_cartridges_alarm_threshold')); $migration->migrationOneTable('glpi_entities'); // move -1 to Entity::CONFIG_NEVER $query = 'UPDATE `glpi_entities` SET `default_consumables_alarm_threshold` = -10 WHERE `default_consumables_alarm_threshold` = -1'; $DB->query($query); $query = 'UPDATE `glpi_entities` SET `default_cartridges_alarm_threshold` = -10 WHERE `default_cartridges_alarm_threshold` = -1'; $DB->query($query); $migration->addField("glpi_entities", 'send_contracts_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_contracts_alert', 'update' => '0', 'condition' => 'WHERE `id`=0')); $migration->addField("glpi_entities", 'send_infocoms_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_infocoms_alert', 'update' => '0', 'condition' => 'WHERE `id`=0')); $migration->addField("glpi_entities", 'send_licenses_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_licenses_alert', 'update' => '0', 'condition' => 'WHERE `id`=0')); $migration->addField("glpi_configs", "notification_to_myself", "bool", array('value' => 1)); $migration->addField("glpi_configs", 'duedateok_color', "string", array('value' => '#06ff00')); $migration->addField("glpi_configs", 'duedatewarning_color', "string", array('value' => '#ffb800')); $migration->addField("glpi_configs", 'duedatecritical_color', "string", array('value' => '#ff0000')); $migration->addField("glpi_configs", 'duedatewarning_less', "integer", array('value' => 20)); $migration->addField("glpi_configs", 'duedatecritical_less', "integer", array('value' => 5)); $migration->addField("glpi_configs", 'duedatewarning_unit', "string", array('value' => '%')); $migration->addField("glpi_configs", 'duedatecritical_unit', "string", array('value' => '%')); $migration->addField("glpi_configs", "realname_ssofield", "string"); $migration->addField("glpi_configs", "firstname_ssofield", "string"); $migration->addField("glpi_configs", "email1_ssofield", "string"); $migration->addField("glpi_configs", "email2_ssofield", "string"); $migration->addField("glpi_configs", "email3_ssofield", "string"); $migration->addField("glpi_configs", "email4_ssofield", "string"); $migration->addField("glpi_configs", "phone_ssofield", "string"); $migration->addField("glpi_configs", "phone2_ssofield", "string"); $migration->addField("glpi_configs", "mobile_ssofield", "string"); $migration->addField("glpi_configs", "comment_ssofield", "string"); $migration->addField("glpi_configs", "title_ssofield", "string"); $migration->addField("glpi_configs", "category_ssofield", "string"); $migration->addField("glpi_configs", "language_ssofield", "string"); $migration->addField("glpi_configs", "entity_ssofield", "string"); $migration->addField("glpi_configs", "registration_number_ssofield", "string"); $migration->addField("glpi_users", "notification_to_myself", "tinyint(1) DEFAULT NULL"); $migration->addField("glpi_users", 'duedateok_color', "string"); $migration->addField("glpi_users", 'duedatewarning_color', "string"); $migration->addField("glpi_users", 'duedatecritical_color', "string"); $migration->addField("glpi_users", 'duedatewarning_less', "int(11) DEFAULT NULL"); $migration->addField("glpi_users", 'duedatecritical_less', "int(11) DEFAULT NULL"); $migration->addField("glpi_users", 'duedatewarning_unit', "string"); $migration->addField("glpi_users", 'duedatecritical_unit', "string"); $migration->addField("glpi_users", 'display_options', "text"); $migration->addField("glpi_reservationitems", "is_deleted", "bool"); $migration->addKey("glpi_reservationitems", "is_deleted"); $migration->addField("glpi_documentcategories", 'documentcategories_id', "integer"); $migration->addField("glpi_documentcategories", 'completename', "text"); $migration->addField("glpi_documentcategories", 'level', "integer"); $migration->addField("glpi_documentcategories", 'ancestors_cache', "longtext"); $migration->addField("glpi_documentcategories", 'sons_cache', "longtext"); $migration->migrationOneTable('glpi_documentcategories'); $migration->addKey("glpi_documentcategories", array('documentcategories_id', 'name'), 'unicity'); regenerateTreeCompleteName("glpi_documentcategories"); $migration->addField("glpi_contacts", 'usertitles_id', "integer"); $migration->addKey("glpi_contacts", 'usertitles_id'); $migration->addField("glpi_contacts", 'address', "text"); $migration->addField("glpi_contacts", 'postcode', "string"); $migration->addField("glpi_contacts", 'town', "string"); $migration->addField("glpi_contacts", 'state', "string"); $migration->addField("glpi_contacts", 'country', "string"); $migration->addField("glpi_configs", 'x509_ou_restrict', "string", array('after' => 'x509_email_field')); $migration->addField("glpi_configs", 'x509_o_restrict', "string", array('after' => 'x509_email_field')); $migration->addField("glpi_configs", 'x509_cn_restrict', "string", array('after' => 'x509_email_field')); if (!TableExists('glpi_slalevelcriterias')) { $query = "CREATE TABLE `glpi_slalevelcriterias` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `slalevels_id` int(11) NOT NULL DEFAULT '0',\n `criteria` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `condition` int(11) NOT NULL DEFAULT '0'\n COMMENT 'see define.php PATTERN_* and REGEX_* constant',\n `pattern` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `slalevels_id` (`slalevels_id`),\n KEY `condition` (`condition`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 create glpi_slalevelcriterias"); } $migration->addField("glpi_slalevels", 'match', "CHAR(10) DEFAULT NULL COMMENT 'see define.php *_MATCHING constant'"); $query = "UPDATE `glpi_slalevelactions`\n SET `action_type` = 'append'\n WHERE `action_type` = 'assign'\n AND `field` IN ('_users_id_requester', '_groups_id_requester',\n '_users_id_assign', '_groups_id_assign',\n '_suppliers_id_assign', '_users_id_observer',\n '_groups_id_observer');"; $DB->queryOrDie($query, "0.84 update data for SLA actors add"); // Clean observer as recipient of satisfaction survey $query = "DELETE FROM `glpi_notificationtargets`\n WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n AND `glpi_notificationtargets`.`items_id` = '" . Notification::OBSERVER . "'\n AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n FROM `glpi_notifications`\n WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n AND `glpi_notifications`.`event` = 'satisfaction')"; $DB->queryOrDie($query, "0.84 clean targets for satisfaction notification"); // Clean user as recipient of item not unique $query = "DELETE FROM `glpi_notificationtargets`\n WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n AND `glpi_notificationtargets`.`items_id` = '" . Notification::USER . "'\n AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n FROM `glpi_notifications`\n WHERE `glpi_notifications`.`itemtype` = 'FieldUnicity'\n AND `glpi_notifications`.`event` = 'refuse')"; $DB->queryOrDie($query, "0.84 clean targets for fieldunicity notification"); if (!TableExists('glpi_blacklists')) { $query = "CREATE TABLE `glpi_blacklists` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `type` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `type` (`type`),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 create glpi_blacklists"); $ADDTODISPLAYPREF['Blacklist'] = array(12, 11); $toinsert = array(Blacklist::IP => array('empty IP' => '', 'localhost' => '127.0.0.1', 'zero IP' => '0.0.0.0'), Blacklist::MAC => array('empty MAC' => '')); foreach ($toinsert as $type => $datas) { if (count($datas)) { foreach ($datas as $name => $value) { $query = "INSERT INTO `glpi_blacklists`\n (`type`,`name`,`value`)\n VALUES ('{$type}','" . addslashes($name) . "','" . addslashes($value) . "')"; $DB->queryOrDie($query, "0.84 insert datas to glpi_blacklists"); } } } } $query = "SELECT `id`\n FROM `glpi_rulerightparameters`\n WHERE `name` = '(LDAP) MemberOf'"; $result = $DB->query($query); if (!$DB->numrows($result)) { $query = "INSERT INTO `glpi_rulerightparameters`\n VALUES (NULL, '(LDAP) MemberOf', 'memberof', '')"; $DB->queryOrDie($query, "0.84 insert (LDAP) MemberOf in glpi_rulerightparameters"); } if (!TableExists('glpi_ssovariables')) { $query = "CREATE TABLE `glpi_ssovariables` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 create glpi_ssovariables"); $query = "INSERT INTO `glpi_ssovariables`\n (`id`, `name`, `comment`)\n VALUES (1, 'HTTP_AUTH_USER', ''),\n (2, 'REMOTE_USER', ''),\n (3, 'PHP_AUTH_USER', ''),\n (4, 'USERNAME', ''),\n (5, 'REDIRECT_REMOTE_USER', ''),\n (6, 'HTTP_REMOTE_USER', '')"; $DB->queryOrDie($query, "0.84 add values from glpi_ssovariables"); } if ($migration->addField('glpi_configs', 'ssovariables_id', 'integer')) { $migration->migrationOneTable('glpi_configs'); //Get configuration $query = "SELECT `existing_auth_server_field`\n FROM `glpi_configs`"; $result = $DB->query($query); $existing_auth_server_field = $DB->result($result, 0, "existing_auth_server_field"); if ($existing_auth_server_field) { //Get dropdown value for existing_auth_server_field $query = "SELECT `id`\n FROM `glpi_ssovariables`\n WHERE `name` = '{$existing_auth_server_field}'"; $result = $DB->query($query); //Update config if ($DB->numrows($result) > 0) { $query = "UPDATE `glpi_configs`\n SET `ssovariables_id` = '" . $DB->result($result, 0, "id") . "'"; $DB->queryOrDie($query, "0.84 update glpi_configs"); } //Drop old field } } $migration->dropField('glpi_configs', 'existing_auth_server_field'); //Remove field to specify an ldap server for SSO users : don't need it anymore $migration->dropField('glpi_configs', 'authldaps_id_extra'); // Clean uneeded logs $cleancondition = array(); $cleancondition['reminder_kb'] = "`itemtype` IN ('Entity', 'User', 'Profile', 'Group')\n AND `itemtype_link` IN ('Reminder', 'Knowbase')"; foreach ($cleancondition as $name => $condition) { $query = "DELETE\n FROM `glpi_logs`\n WHERE {$condition}"; $DB->queryOrDie($query, "0.84 clean logs for {$name}"); } //Remove OCS tables from GLPI's core $migration->renameTable('glpi_ocsadmininfoslinks', 'ocs_glpi_ocsadmininfoslinks'); $migration->renameTable('glpi_ocslinks', 'ocs_glpi_ocslinks'); $migration->renameTable('glpi_ocsservers', 'ocs_glpi_ocsservers'); $migration->renameTable('glpi_registrykeys', 'ocs_glpi_registrykeys'); // Migrate RuleOcs to RuleImportEntity $query = "UPDATE `glpi_rules`\n SET `sub_type` = 'RuleImportEntity'\n WHERE `sub_type` = 'RuleOcs'"; $DB->queryOrDie($query, "0.84 update datas for old OCS rules"); $migration->copyTable('glpi_rules', 'ocs_glpi_rules'); $migration->copyTable('glpi_ruleactions', 'ocs_glpi_ruleactions'); $migration->copyTable('glpi_rulecriterias', 'ocs_glpi_rulecriterias'); // Delete OCS rules $DB->query("SET SESSION group_concat_max_len = 4194304;"); $query = "SELECT GROUP_CONCAT(`id`)\n FROM `glpi_rules`\n WHERE `sub_type` = 'RuleImportEntity'\n GROUP BY `sub_type`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Get rule string $rules = $DB->result($result, 0, 0); $query = "DELETE\n FROM `glpi_ruleactions`\n WHERE `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas"); $query = "DELETE\n FROM `glpi_rulecriterias`\n WHERE `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas"); $query = "DELETE\n FROM `glpi_rules`\n WHERE `id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas"); } } // copy table to keep value of fields deleted after $migration->copyTable('glpi_profiles', 'ocs_glpi_profiles'); $migration->dropField('glpi_profiles', 'ocsng'); $migration->dropField('glpi_profiles', 'sync_ocsng'); $migration->dropField('glpi_profiles', 'view_ocsng'); $migration->dropField('glpi_profiles', 'clean_ocsng'); $migration->changeField('glpi_profiles', 'rule_ocs', 'rule_import', 'char'); $migration->changeField('glpi_rulecacheprinters', 'ignore_ocs_import', 'ignore_import', 'char'); $migration->changeField('glpi_rulecachesoftwares', 'ignore_ocs_import', 'ignore_import', 'char'); $migration->dropField('glpi_configs', 'use_ocs_mode'); // clean crontask $migration->copyTable('glpi_crontasks', 'ocs_glpi_crontasks'); $query = "DELETE\n FROM `glpi_crontasks`\n WHERE `itemtype` = 'OcsServer'"; $DB->queryOrDie($query, "0.84 delete OcsServer in crontasks"); // clean displaypreferences $migration->copyTable('glpi_displaypreferences', 'ocs_glpi_displaypreferences'); $query = "DELETE\n FROM `glpi_displaypreferences`\n WHERE `itemtype` = 'OcsServer'"; $DB->queryOrDie($query, "0.84 delete OcsServer in displaypreferences"); // Give history entries to plugin $query = "UPDATE `glpi_logs`\n SET `linked_action` = `linked_action`+1000,\n `itemtype_link` = 'PluginOcsinventoryngOcslink'\n WHERE `linked_action` IN (8,9,10,11)"; $DB->queryOrDie($query, "0.84 update OCS links in history"); $migration->displayWarning("You can delete ocs_* tables if you use OCS mode ONLY AFTER ocsinventoryng plugin installation.", true); $migration->displayWarning("You can delete ocs_* tables if you do not use OCS synchronisation.", true); $migration->addField('glpi_authldaps', 'pagesize', 'integer'); $migration->addField('glpi_authldaps', 'ldap_maxlimit', 'integer'); $migration->addField('glpi_authldaps', 'can_support_pagesize', 'bool'); // Add delete ticket notification if (countElementsInTable("glpi_notifications", "`itemtype` = 'Ticket' AND `event` = 'delete'") == 0) { // Get first template for tickets : $notid = 0; $query = "SELECT MIN(id) AS id\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'Ticket'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 1) { $notid = $DB->result($result, 0, 0); } } if ($notid > 0) { $notifications = array('delete' => array(Notification::GLOBAL_ADMINISTRATOR)); $notif_names = array('delete' => 'Delete Ticket'); foreach ($notifications as $type => $targets) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . $notif_names[$type] . "', 0, 'Ticket', '{$type}', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.83 add problem {$type} notification"); $notifid = $DB->insert_id(); foreach ($targets as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});"; $DB->queryOrDie($query, "0.83 add problem {$type} notification target"); } } } } // Add multiple suppliers for itil objects if (!TableExists('glpi_problems_suppliers')) { $query = "CREATE TABLE `glpi_problems_suppliers` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `suppliers_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`problems_id`,`type`,`suppliers_id`),\n KEY `group` (`suppliers_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_problems_suppliers"); $migration->migrationOneTable('glpi_problems_suppliers'); foreach ($DB->request('glpi_problems', "`suppliers_id_assign` > 0") as $data) { $query = "INSERT INTO `glpi_problems_suppliers`\n (`suppliers_id`, `type`, `problems_id`)\n VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n '" . $data['id'] . "')"; $DB->query($query); } $migration->dropField('glpi_problems', 'suppliers_id_assign'); } if (!TableExists('glpi_suppliers_tickets')) { $query = "CREATE TABLE `glpi_suppliers_tickets` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `suppliers_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`tickets_id`,`type`,`suppliers_id`),\n KEY `group` (`suppliers_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_suppliers_tickets"); $migration->migrationOneTable('glpi_suppliers_tickets'); foreach ($DB->request('glpi_tickets', "`suppliers_id_assign` > 0") as $data) { $query = "INSERT INTO `glpi_suppliers_tickets`\n (`suppliers_id`, `type`, `tickets_id`)\n VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n '" . $data['id'] . "')"; $DB->query($query); } $migration->dropField('glpi_tickets', 'suppliers_id_assign'); } $migration->addField('glpi_tickets', 'locations_id', 'integer'); $migration->addKey('glpi_tickets', 'locations_id'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket')); $changes = array(); $changes['RuleTicket'] = array('suppliers_id_assign' => '_suppliers_id_assign'); $changes['RuleDictionnarySoftware'] = array('_ignore_ocs_import' => '_ignore_import'); $changes['RuleImportEntity'] = array('_ignore_ocs_import' => '_ignore_import'); $changes['RuleDictionnaryPrinter'] = array('_ignore_ocs_import' => '_ignore_import'); $DB->query("SET SESSION group_concat_max_len = 4194304;"); foreach ($changes as $ruletype => $tab) { // Get rules $query = "SELECT GROUP_CONCAT(`id`)\n FROM `glpi_rules`\n WHERE `sub_type` = '" . $ruletype . "'\n GROUP BY `sub_type`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Get rule string $rules = $DB->result($result, 0, 0); // Update actions foreach ($tab as $old => $new) { $query = "UPDATE `glpi_ruleactions`\n SET `field` = '{$new}'\n WHERE `field` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 update datas for rules actions"); } // Update criterias foreach ($tab as $old => $new) { $query = "UPDATE `glpi_rulecriterias`\n SET `criteria` = '{$new}'\n WHERE `criteria` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 update datas for rules criterias"); } } } } // change ruleaction for manufacturer (id to name) $query = "SELECT `glpi_ruleactions` .`id` AS id,\n `sub_type`,\n `glpi_manufacturers`.`name` AS newvalue\n FROM `glpi_rules`\n INNER JOIN `glpi_ruleactions`\n ON (`glpi_rules`.`id` = `glpi_ruleactions`.`rules_id`\n AND `field` = 'Manufacturer')\n LEFT JOIN `glpi_manufacturers`\n ON `glpi_manufacturers`.`id` = `glpi_ruleactions`.`value`\n WHERE `sub_type` = 'RuleDictionnarySoftware'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { // Update manufacturer $query = "UPDATE `glpi_ruleactions`\n SET `value` = '" . $data['newvalue'] . "'\n WHERE `id` = " . $data['id']; $DB->queryOrDie($query, "0.84 update value of manufacturer for rules actions"); } } } // Move ticketrecurrent values to correct ones $migration->changeField('glpi_ticketrecurrents', 'periodicity', 'periodicity', 'string'); $migration->addField('glpi_ticketrecurrents', 'calendars_id', 'integer'); $migration->addField('glpi_ticketrecurrents', 'end_date', 'datetime'); $migration->migrationOneTable('glpi_ticketrecurrents'); foreach ($DB->request('glpi_ticketrecurrents', "`periodicity` >= " . MONTH_TIMESTAMP) as $data) { $periodicity = $data['periodicity']; if (is_numeric($periodicity)) { if ($periodicity >= 365 * DAY_TIMESTAMP) { $periodicity = round($periodicity / (365 * DAY_TIMESTAMP)) . 'YEAR'; } else { $periodicity = round($periodicity / MONTH_TIMESTAMP) . 'MONTH'; } $query = "UPDATE `glpi_ticketrecurrents`\n SET `periodicity` = '{$periodicity}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } } $query = "UPDATE `glpi_notifications`\n SET `itemtype` = 'CartridgeItem'\n WHERE `itemtype` = 'Cartridge'"; $DB->queryOrDie($query, "0.83 update glpi_notifications for Cartridge"); $query = "UPDATE `glpi_notificationtemplates`\n SET `itemtype` = 'CartridgeItem'\n WHERE `itemtype` = 'Cartridge'"; $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Cartridge"); $query = "UPDATE `glpi_notifications`\n SET `itemtype` = 'ConsumableItem'\n WHERE `itemtype` = 'Consumable'"; $DB->queryOrDie($query, "0.83 update glpi_notifications for Consumable"); $query = "UPDATE `glpi_notificationtemplates`\n SET `itemtype` = 'ConsumableItem'\n WHERE `itemtype` = 'Consumable'"; $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Consumable"); $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from item'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'items_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromitem', 'value' => 1))); $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from user'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'users_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromuser', 'value' => 1))); // Change begin_date id for budget $query = "UPDATE `glpi_displaypreferences`\n SET `num` = '5'\n WHERE `itemtype` = 'Budget'\n AND `num` = '2'"; $DB->query($query); migrateComputerDevice('DeviceProcessor', 'frequency', 'integer', array('serial' => 'string')); migrateComputerDevice('DeviceMemory', 'size', 'integer', array('serial' => 'string')); migrateComputerDevice('DeviceHardDrive', 'capacity', 'integer', array('serial' => 'string')); migrateComputerDevice('DeviceGraphicCard', 'memory', 'integer'); migrateComputerDevice('DeviceNetworkCard', 'mac', 'string'); migrateComputerDevice('DeviceSoundCard'); migrateComputerDevice('DeviceMotherBoard'); migrateComputerDevice('DeviceDrive'); migrateComputerDevice('DeviceControl'); migrateComputerDevice('DevicePci'); migrateComputerDevice('DeviceCase'); migrateComputerDevice('DevicePowerSupply'); $migration->migrationOneTable('glpi_computers_softwareversions'); //Rename fields in glpi_computers_softwareversions with inaproprious signification $migration->changeField('glpi_computers_softwareversions', 'is_deleted', 'is_deleted_computer', 'bool'); $migration->changeField('glpi_computers_softwareversions', 'is_template', 'is_template_computer', 'bool'); $migration->migrationOneTable('glpi_computers_softwareversions'); $types = array('glpi_computers_items', 'glpi_computervirtualmachines', 'glpi_computers_softwareversions', 'glpi_computerdisks', 'glpi_networkports', 'glpi_computers_softwarelicenses', 'glpi_networknames', 'glpi_ipaddresses'); foreach (Item_Devices::getDeviceTypes() as $id => $type) { $types[] = getTableForItemType($type); } //Add is_deleted for relations foreach ($types as $table) { if ($migration->addField($table, 'is_deleted', 'bool', array('value' => 0))) { $migration->migrationOneTable($table); $migration->addKey($table, 'is_deleted'); } } ///For computers, rename is is_ocs_import to is_dynamic $migration->changeField('glpi_computers', 'is_ocs_import', 'is_dynamic', 'bool'); $migration->migrationOneTable('glpi_computers'); $migration->dropKey("glpi_computers", 'is_ocs_import'); $migration->addKey("glpi_computers", 'is_dynamic'); //Add field is_dynamic $types = array_merge($types, array('glpi_printers', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_networkports', 'glpi_monitors', 'glpi_networknames', 'glpi_ipaddresses')); foreach ($types as $table) { if ($migration->addField($table, 'is_dynamic', 'bool')) { $migration->migrationOneTable($table); $migration->addKey($table, 'is_dynamic'); } } $ADDTODISPLAYPREF['ReservationItem'] = array(5); // split validation rights in both $migration->changeField('glpi_profiles', 'validate_ticket', 'validate_request', 'char'); $migration->changeField('glpi_profiles', 'create_validation', 'create_request_validation', 'char'); $migration->migrationOneTable('glpi_profiles'); $migration->addField('glpi_profiles', 'validate_incident', 'char', array('update' => 'validate_request')); $migration->addField('glpi_profiles', 'create_incident_validation', 'char', array('update' => 'create_request_validation')); // add rights to delete all validation $migration->addField('glpi_profiles', 'delete_validations', 'char', array('update' => 'delete_ticket')); // add rights to manage public rssfeed $migration->addField('glpi_profiles', 'rssfeed_public', 'char', array('update' => 'reminder_public', 'after' => 'reminder_public')); // add ticket templates $migration->addField('glpi_profiles', 'tickettemplates_id', 'integer'); // Drop not needed fields $migration->dropField('glpi_tickettemplatepredefinedfields', 'entities_id'); $migration->dropField('glpi_tickettemplatepredefinedfields', 'is_recursive'); $migration->dropField('glpi_tickettemplatemandatoryfields', 'entities_id'); $migration->dropField('glpi_tickettemplatemandatoryfields', 'is_recursive'); $migration->dropField('glpi_tickettemplatehiddenfields', 'entities_id'); $migration->dropField('glpi_tickettemplatehiddenfields', 'is_recursive'); // Clean unlinked calendar segments and holidays $query = "DELETE\n FROM `glpi_calendars_holidays`\n WHERE `glpi_calendars_holidays`.`calendars_id`\n NOT IN (SELECT `glpi_calendars`.`id`\n FROM `glpi_calendars`)"; $DB->queryOrDie($query, "0.84 clean glpi_calendars_holidays"); $query = "DELETE\n FROM `glpi_calendarsegments`\n WHERE `glpi_calendarsegments`.`calendars_id`\n NOT IN (SELECT `glpi_calendars`.`id`\n FROM `glpi_calendars`)"; $DB->queryOrDie($query, "0.84 clean glpi_calendarsegments"); // Add keys for serial, otherserial and uuid $newindexes = array('serial' => array('glpi_computers', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_deviceprocessors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'otherserial' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'uuid' => array('glpi_computers', 'glpi_computervirtualmachines')); foreach ($newindexes as $field => $tables) { foreach ($tables as $table) { $migration->addKey($table, $field); } } // Clean unlinked ticket_problem $query = "DELETE\n FROM `glpi_problems_tickets`\n WHERE `glpi_problems_tickets`.`tickets_id`\n NOT IN (SELECT `glpi_tickets`.`id`\n FROM `glpi_tickets`)"; $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets"); $query = "DELETE\n FROM `glpi_problems_tickets`\n WHERE `glpi_problems_tickets`.`problems_id`\n NOT IN (SELECT `glpi_problems`.`id`\n FROM `glpi_problems`)"; $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets"); // Clean unlinked softwarelicense_computer $query = "DELETE\n FROM `glpi_computers_softwarelicenses`\n WHERE `glpi_computers_softwarelicenses`.`softwarelicenses_id`\n NOT IN (SELECT `glpi_softwarelicenses`.`id`\n FROM `glpi_softwarelicenses`)"; $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses"); $query = "DELETE\n FROM `glpi_computers_softwarelicenses`\n WHERE `glpi_computers_softwarelicenses`.`computers_id`\n NOT IN (SELECT `glpi_computers`.`id`\n FROM `glpi_computers`)"; $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses"); // Clean unlinked items_problems $query = "DELETE\n FROM `glpi_items_problems`\n WHERE `glpi_items_problems`.`problems_id`\n NOT IN (SELECT `glpi_problems`.`id`\n FROM `glpi_problems`)"; $DB->queryOrDie($query, "0.84 clean glpi_items_problems"); $toclean = array('Computer', 'Monitor', 'NetworkEquipment', 'Peripheral', 'Phone', 'Printer', 'Software'); foreach ($toclean as $type) { $query = "DELETE\n FROM `glpi_items_problems`\n WHERE `glpi_items_problems`.`itemtype` = '{$type}'\n AND `glpi_items_problems`.`items_id`\n NOT IN (SELECT `" . getTableForItemType($type) . "`.`id`\n FROM `" . getTableForItemType($type) . "`)"; $DB->queryOrDie($query, "0.84 clean glpi_items_problems"); } // ************ Keep it at the end ************** //TRANS: %s is the table or item to migrate $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences')); foreach ($ADDTODISPLAYPREF as $type => $tab) { $query = "SELECT DISTINCT `users_id`\n FROM `glpi_displaypreferences`\n WHERE `itemtype` = '{$type}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $query = "SELECT MAX(`rank`)\n FROM `glpi_displaypreferences`\n WHERE `users_id` = '" . $data['users_id'] . "'\n AND `itemtype` = '{$type}'"; $result = $DB->query($query); $rank = $DB->result($result, 0, 0); $rank++; foreach ($tab as $newval) { $query = "SELECT *\n FROM `glpi_displaypreferences`\n WHERE `users_id` = '" . $data['users_id'] . "'\n AND `num` = '{$newval}'\n AND `itemtype` = '{$type}'"; if ($result2 = $DB->query($query)) { if ($DB->numrows($result2) == 0) { $query = "INSERT INTO `glpi_displaypreferences`\n (`itemtype` ,`num` ,`rank` ,`users_id`)\n VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n '" . $data['users_id'] . "')"; $DB->query($query); } } } } } else { // Add for default user $rank = 1; foreach ($tab as $newval) { $query = "INSERT INTO `glpi_displaypreferences`\n (`itemtype` ,`num` ,`rank` ,`users_id`)\n VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')"; $DB->query($query); } } } } // must always be at the end $migration->executeMigration(); return $updateresult; }
/** * Return the instance fields of itemtype identified by id * * @param $itemtype string itemtype (class) of object * @param $id integer identifier of object * @param $params array with theses options : * - 'expand_dropdowns': Show dropdown's names instead of id. default: false. Optionnal * - 'get_hateoas': Show relation of current item in a links attribute. default: true. Optionnal * - 'get_sha1': Get a sha1 signature instead of the full answer. default: false. Optionnal * - 'with_components': Only for [Computer, NetworkEquipment, Peripheral, Phone, Printer], Optionnal. * - 'with_disks': Only for Computer, retrieve the associated filesystems. Optionnal. * - 'with_softwares': Only for Computer, retrieve the associated softwares installations. Optionnal. * - 'with_connections': Only for Computer, retrieve the associated direct connections (like peripherals and printers) .Optionnal. * - 'with_networkports':Retrieve all network connections and advanced network informations. Optionnal. * - 'with_infocoms': Retrieve financial and administrative informations. Optionnal. * - 'with_contracts': Retrieve associated contracts. Optionnal. * - 'with_documents': Retrieve associated external documents. Optionnal. * - 'with_tickets': Retrieve associated itil tickets. Optionnal. * - 'with_problems': Retrieve associated itil problems. Optionnal. * - 'with_changes': Retrieve associated itil changes. Optionnal. * - 'with_notes': Retrieve Notes (if exists, not all itemtypes have notes). Optionnal. * - 'with_logs': Retrieve historical. Optionnal. * * @return array fields of found object **/ protected function getItem($itemtype, $id, $params = array()) { global $CFG_GLPI, $DB; $this->initEndpoint(); // default params $default = array('expand_dropdowns' => false, 'get_hateoas' => true, 'get_sha1' => false, 'with_components' => false, 'with_disks' => false, 'with_softwares' => false, 'with_connections' => false, 'with_networkports' => false, 'with_infocoms' => false, 'with_contracts' => false, 'with_documents' => false, 'with_tickets' => false, 'with_problems' => false, 'with_changes' => false, 'with_notes' => false, 'with_logs' => false); $params = array_merge($default, $params); $item = new $itemtype(); if (!$item->getFromDB($id)) { return $this->messageNotfoundError(); } if (!$item->can($id, READ)) { return $this->messageRightError(); } $fields = $item->fields; // avoid disclosure of critical fields $item::unsetUndisclosedFields($fields); // retrieve devices if (isset($params['with_devices']) && $params['with_devices'] && in_array($itemtype, Item_Devices::getConcernedItems())) { $all_devices = array(); foreach (Item_Devices::getItemAffinities($item->getType()) as $device_type) { $found_devices = getAllDatasFromTable($device_type::getTable(), "`items_id` = '" . $item->getID() . "'\n AND `itemtype` = '" . $item->getType() . "'\n AND `is_deleted` = '0'", true); foreach ($found_devices as $devices_id => &$device) { unset($device['items_id']); unset($device['itemtype']); unset($device['is_deleted']); } if (!empty($found_devices)) { $all_devices[$device_type] = $found_devices; } } $fields['_devices'] = $all_devices; } // retrieve computer disks if (isset($params['with_disks']) && $params['with_disks'] && $itemtype == "Computer") { // build query to retrive filesystems $query = "SELECT `glpi_filesystems`.`name` AS fsname,\n `glpi_computerdisks`.*\n FROM `glpi_computerdisks`\n LEFT JOIN `glpi_filesystems`\n ON (`glpi_computerdisks`.`filesystems_id` = `glpi_filesystems`.`id`)\n WHERE `computers_id` = '{$id}'\n AND `is_deleted` = '0'"; $fields['_disks'] = array(); if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { unset($data['computers_id']); unset($data['is_deleted']); $fields['_disks'][] = array('name' => $data); } } } // retrieve computer softwares if (isset($params['with_softwares']) && $params['with_softwares'] && $itemtype == "Computer") { $fields['_softwares'] = array(); if (!Software::canView()) { $fields['_softwares'] = self::arrayRightError(); } else { $query = "SELECT `glpi_softwares`.`softwarecategories_id`,\n `glpi_softwares`.`id` AS softwares_id,\n `glpi_softwareversions`.`id` AS softwareversions_id,\n `glpi_computers_softwareversions`.`is_dynamic`,\n `glpi_softwareversions`.`states_id`,\n `glpi_softwares`.`is_valid`\n FROM `glpi_computers_softwareversions`\n LEFT JOIN `glpi_softwareversions`\n ON (`glpi_computers_softwareversions`.`softwareversions_id`\n = `glpi_softwareversions`.`id`)\n LEFT JOIN `glpi_softwares`\n ON (`glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`)\n WHERE `glpi_computers_softwareversions`.`computers_id` = '{$id}'\n AND `glpi_computers_softwareversions`.`is_deleted` = '0'\n ORDER BY `glpi_softwares`.`name`, `glpi_softwareversions`.`name`"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_softwares'][] = $data; } } } } // retrieve item connections if (isset($params['with_connections']) && $params['with_connections'] && $itemtype == "Computer") { $fields['_connections'] = array(); foreach ($CFG_GLPI["directconnect_types"] as $connect_type) { $connect_item = new $connect_type(); if ($connect_item->canView()) { $query = "SELECT `glpi_computers_items`.`id` AS assoc_id,\n `glpi_computers_items`.`computers_id` AS assoc_computers_id,\n `glpi_computers_items`.`itemtype` AS assoc_itemtype,\n `glpi_computers_items`.`items_id` AS assoc_items_id,\n `glpi_computers_items`.`is_dynamic` AS assoc_is_dynamic,\n " . getTableForItemType($connect_type) . ".*\n FROM `glpi_computers_items`\n LEFT JOIN `" . getTableForItemType($connect_type) . "`\n ON (`" . getTableForItemType($connect_type) . "`.`id`\n = `glpi_computers_items`.`items_id`)\n WHERE `computers_id` = '{$id}'\n AND `itemtype` = '" . $connect_type . "'\n AND `glpi_computers_items`.`is_deleted` = '0'"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_connections'][$connect_type][] = $data; } } } } } // retrieve item networkports if (isset($params['with_networkports']) && $params['with_networkports']) { $fields['_networkports'] = array(); if (!NetworkEquipment::canView()) { $fields['_networkports'] = self::arrayRightError(); } else { foreach (NetworkPort::getNetworkPortInstantiations() as $networkport_type) { $netport_table = $networkport_type::getTable(); $query = "SELECT\n netp.`id` as netport_id,\n netp.`entities_id`,\n netp.`is_recursive`,\n netp.`logical_number`,\n netp.`name`,\n netp.`mac`,\n netp.`comment`,\n netp.`is_dynamic`,\n netp_subtable.*\n FROM glpi_networkports AS netp\n LEFT JOIN `{$netport_table}` AS netp_subtable\n ON netp_subtable.`networkports_id` = netp.`id`\n WHERE netp.`instantiation_type` = '{$networkport_type}'\n AND netp.`items_id` = '{$id}'\n AND netp.`itemtype` = '{$itemtype}'\n AND netp.`is_deleted` = '0'"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { if (isset($data['netport_id'])) { // append network name $query_netn = "SELECT\n GROUP_CONCAT(CONCAT(ipadr.`id`, '" . Search::SHORTSEP . "' , ipadr.`name`)\n SEPARATOR '" . Search::LONGSEP . "') as ipadresses,\n netn.`id` as networknames_id,\n netn.`name` as networkname,\n netn.`fqdns_id`,\n fqdn.`name` as fqdn_name,\n fqdn.`fqdn`\n FROM `glpi_networknames` AS netn\n LEFT JOIN `glpi_ipaddresses` AS ipadr\n ON ipadr.`itemtype` = 'NetworkName' AND ipadr.`items_id` = netn.`id`\n LEFT JOIN `glpi_fqdns` AS fqdn\n ON fqdn.`id` = netn.`fqdns_id`\n LEFT JOIN `glpi_ipaddresses_ipnetworks` ipadnet\n ON ipadnet.`ipaddresses_id` = ipadr.`id`\n LEFT JOIN `glpi_ipnetworks` `ipnet`\n ON ipnet.`id` = ipadnet.`ipnetworks_id`\n WHERE netn.`itemtype` = 'NetworkPort'\n AND netn.`items_id` = " . $data['netport_id'] . "\n GROUP BY netn.`id`, netn.`name`, netn.fqdns_id, fqdn.name, fqdn.fqdn"; if ($result_netn = $DB->query($query_netn)) { $data_netn = $DB->fetch_assoc($result_netn); $raw_ipadresses = explode(Search::LONGSEP, $data_netn['ipadresses']); $ipadresses = array(); foreach ($raw_ipadresses as $ipadress) { $ipadress = explode(Search::SHORTSEP, $ipadress); //find ip network attached to these ip $ipnetworks = array(); $query_ipnet = "SELECT\n ipnet.`id`,\n ipnet.`completename`,\n ipnet.`name`,\n ipnet.`address`,\n ipnet.`netmask`,\n ipnet.`gateway`,\n ipnet.`ipnetworks_id`,\n ipnet.`comment`\n FROM `glpi_ipnetworks` ipnet\n INNER JOIN `glpi_ipaddresses_ipnetworks` ipadnet\n ON ipnet.`id` = ipadnet.`ipnetworks_id`\n AND ipadnet.`ipaddresses_id` = " . $ipadress[0]; if ($result_ipnet = $DB->query($query_ipnet)) { while ($data_ipnet = $DB->fetch_assoc($result_ipnet)) { $ipnetworks[] = $data_ipnet; } } $ipadresses[] = array('id' => $ipadress[0], 'name' => $ipadress[1], 'IPNetwork' => $ipnetworks); } $data['NetworkName'] = array('id' => $data_netn['networknames_id'], 'name' => $data_netn['networkname'], 'fqdns_id' => $data_netn['fqdns_id'], 'FQDN' => array('id' => $data_netn['fqdns_id'], 'name' => $data_netn['fqdn_name'], 'fqdn' => $data_netn['fqdn']), 'IPAddress' => $ipadresses); } } $fields['_networkports'][$networkport_type][] = $data; } } } } } // retrieve item infocoms if (isset($params['with_infocoms']) && $params['with_infocoms']) { $fields['_infocoms'] = array(); if (!Infocom::canView()) { $fields['_infocoms'] = self::arrayRightError(); } else { $ic = new Infocom(); if ($ic->getFromDBforDevice($itemtype, $id)) { $fields['_infocoms'] = $ic->fields; } } } // retrieve item contracts if (isset($params['with_contracts']) && $params['with_contracts']) { $fields['_contracts'] = array(); if (!Contract::canView()) { $fields['_contracts'] = self::arrayRightError(); } else { $query = "SELECT `glpi_contracts_items`.*\n FROM `glpi_contracts_items`,\n `glpi_contracts`\n LEFT JOIN `glpi_entities` ON (`glpi_contracts`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_contracts`.`id`=`glpi_contracts_items`.`contracts_id`\n AND `glpi_contracts_items`.`items_id` = '{$id}'\n AND `glpi_contracts_items`.`itemtype` = '{$itemtype}'" . getEntitiesRestrictRequest(" AND", "glpi_contracts", '', '', true) . "\n ORDER BY `glpi_contracts`.`name`"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_contracts'][] = $data; } } } } // retrieve item contracts if (isset($params['with_documents']) && $params['with_documents']) { $fields['_documents'] = array(); if (!$itemtype != 'Ticket' && $itemtype != 'KnowbaseItem' && $itemtype != 'Reminder' && !Document::canView()) { $fields['_documents'] = self::arrayRightError(); } else { $query = "SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_documents_items`.`date_mod` AS assocdate,\n `glpi_entities`.`id` AS entityID,\n `glpi_entities`.`completename` AS entity,\n `glpi_documentcategories`.`completename` AS headings,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n LEFT JOIN `glpi_documentcategories`\n ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)\n WHERE `glpi_documents_items`.`items_id` = '{$id}'\n AND `glpi_documents_items`.`itemtype` = '{$itemtype}' "; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_documents'][] = $data; } } } } // retrieve item tickets if (isset($params['with_tickets']) && $params['with_tickets']) { $fields['_tickets'] = array(); if (!Ticket::canView()) { $fields['_tickets'] = self::arrayRightError(); } else { $query = "SELECT " . Ticket::getCommonSelect() . "\n FROM `glpi_tickets` " . Ticket::getCommonLeftJoin() . "\n WHERE `glpi_items_tickets`.`items_id` = '{$id}'\n AND `glpi_items_tickets`.`itemtype` = '{$itemtype}' " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n ORDER BY `glpi_tickets`.`date_mod` DESC"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_tickets'][] = $data; } } } } // retrieve item problems if (isset($params['with_problems']) && $params['with_problems']) { $fields['_problems'] = array(); if (!Problem::canView()) { $fields['_problems'] = self::arrayRightError(); } else { $query = "SELECT " . Problem::getCommonSelect() . "\n FROM `glpi_problems`\n LEFT JOIN `glpi_items_problems`\n ON (`glpi_problems`.`id` = `glpi_items_problems`.`problems_id`) " . Problem::getCommonLeftJoin() . "\n WHERE `items_id` = '{$id}'\n AND `itemtype` = '{$itemtype}' " . getEntitiesRestrictRequest("AND", "glpi_problems") . "\n ORDER BY `glpi_problems`.`date_mod` DESC"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_problems'][] = $data; } } } } // retrieve item changes if (isset($params['with_changes']) && $params['with_changes']) { $fields['_changes'] = array(); if (!Change::canView()) { $fields['_changes'] = self::arrayRightError(); } else { $query = "SELECT " . Change::getCommonSelect() . "\n FROM `glpi_changes`\n LEFT JOIN `glpi_changes_items`\n ON (`glpi_changes`.`id` = `glpi_changes_items`.`problems_id`) " . Change::getCommonLeftJoin() . "\n WHERE `items_id` = '{$id}'\n AND `itemtype` = '{$itemtype}' " . getEntitiesRestrictRequest("AND", "glpi_changes") . "\n ORDER BY `glpi_changes`.`date_mod` DESC"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_changes'][] = $data; } } } } // retrieve item notes if (isset($params['with_notes']) && $params['with_notes']) { $fields['_notes'] = array(); if (!Session::haveRight($itemtype::$rightname, READNOTE)) { $fields['_notes'] = self::arrayRightError(); } else { $fields['_notes'] = Notepad::getAllForItem($item); } } // retrieve item logs if (isset($params['with_logs']) && $params['with_logs']) { $fields['_logs'] = array(); if (!Session::haveRight($itemtype::$rightname, READNOTE)) { $fields['_logs'] = self::arrayRightError(); } else { $fields['_logs'] = getAllDatasFromTable("glpi_logs", "`items_id` = '" . $item->getID() . "'\n AND `itemtype` = '" . $item->getType() . "'"); } } // expand dropdown (retrieve name of dropdowns) and get hateoas from foreign keys $fields = self::parseDropdowns($fields, $params); // get hateoas from children if ($params['get_hateoas']) { $hclasses = self::getHatoasClasses($itemtype); foreach ($hclasses as $hclass) { $fields['links'][] = array('rel' => $hclass, 'href' => self::$api_url . "/{$itemtype}/" . $item->getID() . "/{$hclass}/"); } } // get sha1 footprint if needed if ($params['get_sha1']) { $fields = sha1(json_encode($fields, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK)); } return $fields; }
/** * Update from 0.84 to 0.85 * * @return bool for success (will die for most error) **/ function update084to085() { global $DB, $migration; $updateresult = true; $ADDTODISPLAYPREF = array(); $DELFROMDISPLAYPREF = array(); //TRANS: %s is the number of new version $migration->displayTitle(sprintf(__('Update to %s'), '0.85')); $migration->setVersion('0.85'); $backup_tables = false; $newtables = array('glpi_blacklistedmailcontents', 'glpi_changecosts', 'glpi_changes', 'glpi_changes_groups', 'glpi_changes_items', 'glpi_changes_problems', 'glpi_changes_projects', 'glpi_changes_suppliers', 'glpi_changes_tickets', 'glpi_changes_users', 'glpi_changetasks', 'glpi_changevalidations', 'glpi_dropdowntranslations', 'glpi_knowbaseitemtranslations', 'glpi_notepads', 'glpi_problemcosts', 'glpi_projectcosts', 'glpi_projects', 'glpi_projects_changes', 'glpi_projects_items', 'glpi_projectstates', 'glpi_projecttasks', 'glpi_projecttasks_tickets', 'glpi_projecttaskteams', 'glpi_projecttasktypes', 'glpi_projectteams', 'glpi_projecttypes', 'glpi_queuedmails'); foreach ($newtables as $new_table) { // rename new tables if exists ? if (TableExists($new_table)) { $migration->dropTable("backup_{$new_table}"); $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}."); $backup_tables = true; $query = $migration->renameTable("{$new_table}", "backup_{$new_table}"); } } if ($backup_tables) { $migration->displayWarning("You can delete backup tables if you have no need of them.", true); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'config table')); if (FieldExists('glpi_configs', 'version')) { if (!TableExists('origin_glpi_configs')) { $migration->copyTable('glpi_configs', 'origin_glpi_configs'); } $query = "SELECT *\n FROM `glpi_configs`\n WHERE `id` = '1'"; $result_of_configs = $DB->query($query); // Update glpi_configs $migration->addField('glpi_configs', 'context', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'core'")); $migration->addField('glpi_configs', 'name', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'version'")); $migration->addField('glpi_configs', 'value', 'text', array('update' => "'0.85'")); $migration->addKey('glpi_configs', array('context', 'name'), 'unicity', 'UNIQUE'); $migration->migrationOneTable('glpi_configs'); $fields = array(); if ($DB->numrows($result_of_configs) == 1) { $configs = $DB->fetch_assoc($result_of_configs); unset($configs['id']); unset($configs['version']); // First drop fields not to have constraint on insert foreach ($configs as $name => $value) { $migration->dropField('glpi_configs', $name); } $migration->migrationOneTable('glpi_configs'); // Then insert new values foreach ($configs as $name => $value) { $query = "INSERT INTO `glpi_configs`\n (`context`, `name`, `value`)\n VALUES ('core', '{$name}', '" . addslashes($value) . "');"; $DB->query($query); } } $migration->dropField('glpi_configs', 'version'); $migration->migrationOneTable('glpi_configs'); $migration->dropTable('origin_glpi_configs'); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'profile table')); if (!TableExists('glpi_profilerights')) { if (!TableExists('origin_glpi_profiles')) { $migration->copyTable('glpi_profiles', 'origin_glpi_profiles'); } $query = "CREATE TABLE `glpi_profilerights` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `profiles_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) DEFAULT NULL,\n `rights` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`profiles_id`, `name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_profilerights"); $query = "DESCRIBE `origin_glpi_profiles`"; $rights = array(); foreach ($DB->request($query) as $field) { if ($field['Type'] == 'char(1)') { $rights[$field['Field']] = $field['Field']; $migration->dropField('glpi_profiles', $field['Field']); } } $query = "SELECT *\n FROM `origin_glpi_profiles`"; foreach ($DB->request($query) as $profile) { $profiles_id = $profile['id']; foreach ($rights as $right) { $new_right = 0; if ($profile[$right] == 'r' || $profile[$right] == '1') { $new_right = READ; } else { if ($profile[$right] == 'w') { $new_right = ALLSTANDARDRIGHT; } } $query = "INSERT INTO `glpi_profilerights`\n (`profiles_id`, `name`, `rights`)\n VALUES ('{$profiles_id}', '{$right}', '" . $new_right . "')"; $DB->query($query); } } $migration->migrationOneTable('glpi_profiles'); $migration->dropTable('origin_glpi_profiles'); } // New system of profiles // delete import_externalauth_users foreach ($DB->request("glpi_profilerights", "`name` = 'import_externalauth_users' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . User::IMPORTEXTAUTHUSERS . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'user'"; $DB->queryOrDie($query, "0.85 update user with import_externalauth_users right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'import_externalauth_users'"; $DB->queryOrDie($query, "0.85 delete import_externalauth_users right"); // save value of rule_ticket to root_rule_ticket $query = "UPDATE `glpi_profilerights`\n SET `name` = 'root_rule_ticket'\n WHERE `name` = 'rule_ticket'"; $DB->queryOrDie($query, "0.85 rename rule_ticket to root_rule_ticket"); // rename entity_rule_ticket to rule_ticket $query = "UPDATE `glpi_profilerights`\n SET `name` = 'rule_ticket'\n WHERE `name` = 'entity_rule_ticket'"; $DB->queryOrDie($query, "0.85 rename entity_rule_ticket to rule_ticket"); // delete root_rule_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'root_rule_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . RuleTicket::PARENT . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'rule_ticket'"; $DB->queryOrDie($query, "0.85 update new rule_ticket with old rule_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'root_rule_ticket'"; $DB->queryOrDie($query, "0.85 delete old rule_ticket right"); // delete knowbase_admin foreach ($DB->request("glpi_profilerights", "`name` = 'knowbase_admin' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . KnowbaseItem::KNOWBASEADMIN . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'knowbase'"; $DB->queryOrDie($query, "0.85 update knowbase with knowbase_admin right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'knowbase_admin'"; $DB->queryOrDie($query, "0.85 delete knowbase_admin right"); // delete faq foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . KnowbaseItem::READFAQ . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'knowbase'"; $DB->queryOrDie($query, "0.85 update knowbase with read faq right"); } foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . KnowbaseItem::READFAQ . " | " . KnowbaseItem::PUBLISHFAQ . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'knowbase'"; $DB->queryOrDie($query, "0.85 update knowbase with write faq right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'faq'"; $DB->queryOrDie($query, "0.85 delete faq right"); // delete user_authtype foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . User::READAUTHENT . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'user'"; $DB->queryOrDie($query, "0.85 update user with read user_authtype right"); } foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . User::READAUTHENT . " | " . User::UPDATEAUTHENT . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'user'"; $DB->queryOrDie($query, "0.85 update user with write user_authtype right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'user_authtype'"; $DB->queryOrDie($query, "0.85 delete user_authtype right"); // delete entity_helpdesk foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Entity::READHELPDESK . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'entity'"; $DB->queryOrDie($query, "0.85 update entity with read entity_helpdesk right"); } foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Entity::READHELPDESK . " | " . Entity::UPDATEHELPDESK . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'entity'"; $DB->queryOrDie($query, "0.85 update user with write entity_helpdesk right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'entity_helpdesk'"; $DB->queryOrDie($query, "0.85 delete entity_helpdesk right"); // delete reservation_helpdesk foreach ($DB->request("glpi_profilerights", "`name` = 'reservation_helpdesk' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . ReservationItem::RESERVEANITEM . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'reservation_central'"; $DB->queryOrDie($query, "0.85 update reservation_central with reservation_helpdesk right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'reservation_helpdesk'"; $DB->queryOrDie($query, "0.85 delete reservation_helpdesk right"); // rename reservation_central $query = "UPDATE `glpi_profilerights`\n SET `name` = 'reservation'\n WHERE `name` = 'reservation_central'"; $DB->queryOrDie($query, "0.85 delete reservation_central"); // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'ticket'") == 0) { // rename create_ticket $query = "UPDATE `glpi_profilerights`\n SET `name` = 'ticket'\n WHERE `name` = 'create_ticket'"; $DB->queryOrDie($query, "0.85 rename create_ticket to ticket"); $query = "UPDATE `glpi_profilerights`\n SET `rights` = " . (CREATE | Ticket::READMY) . "\n WHERE `name` = 'ticket'\n AND `rights` = '1'"; $DB->queryOrDie($query, "0.85 update ticket with create_ticket right"); } // delete update_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'update_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . UPDATE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with update_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'update_ticket'"; $DB->queryOrDie($query, "0.85 delete update_ticket right"); // delete delete_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'delete_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . DELETE . " | " . PURGE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with delete_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'delete_ticket'"; $DB->queryOrDie($query, "0.85 delete delete_ticket right"); // delete show_all_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::READALL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with show_all_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_all_ticket'"; $DB->queryOrDie($query, "0.85 delete show_all_ticket right"); // delete show_group_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::READGROUP . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with show_group_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_group_ticket'"; $DB->queryOrDie($query, "0.85 delete show_group_ticket right"); // delete show_assign_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'show_assign_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::READASSIGN . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with show_assign_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_assign_ticket'"; $DB->queryOrDie($query, "0.85 delete show_assign_ticket right"); // delete assign_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'assign_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::ASSIGN . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with assign_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'assign_ticket'"; $DB->queryOrDie($query, "0.85 delete assign_ticket right"); // delete steal_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'steal_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::STEAL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with steal_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'steal_ticket'"; $DB->queryOrDie($query, "0.85 delete steal_ticket right"); // delete own_ticket foreach ($DB->request("glpi_profilerights", "`name` = 'own_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::OWN . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with own_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'own_ticket'"; $DB->queryOrDie($query, "0.85 delete own_ticket right"); // delete update_priority foreach ($DB->request("glpi_profilerights", "`name` = 'update_priority' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Ticket::CHANGEPRIORITY . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticket'"; $DB->queryOrDie($query, "0.85 update ticket with update_priority right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'update_priority'"; $DB->queryOrDie($query, "0.85 delete update_priority right"); // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'followup'") == 0) { // rename create_ticket $query = "UPDATE `glpi_profilerights`\n SET `name` = 'followup'\n WHERE `name` = 'global_add_followups'"; $DB->queryOrDie($query, "0.85 rename global_add_followups to followup"); $query = "UPDATE `glpi_profilerights`\n SET `rights` = " . TicketFollowup::ADDALLTICKET . "\n WHERE `name` = 'followup'\n AND `rights` = '1'"; $DB->queryOrDie($query, "0.85 update followup with global_add_followups right"); } // delete add_followups foreach ($DB->request("glpi_profilerights", "`name` = 'add_followups' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketFollowup::ADDMYTICKET . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with add_followups right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'add_followups'"; $DB->queryOrDie($query, "0.85 delete add_followups right"); // delete group_add_followups foreach ($DB->request("glpi_profilerights", "`name` = 'group_add_followups' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketFollowup::ADDGROUPTICKET . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with group_add_followups right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'group_add_followups'"; $DB->queryOrDie($query, "0.85 delete group_add_followups right"); // delete observe_ticket for followup foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with observe_ticket right"); } // don't delete observe_ticket because already use for task // delete show_full_ticket for followup foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . " | " . TicketFollowup::SEEPRIVATE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with show_full_ticket right"); } // don't delete show_full_ticket because already use for task // delete update_followups foreach ($DB->request("glpi_profilerights", "`name` = 'update_followups' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEALL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with update_followups right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'update_followups'"; $DB->queryOrDie($query, "0.85 delete update_followups right"); // delete update_own_followups foreach ($DB->request("glpi_profilerights", "`name` = 'update_own_followups' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEMY . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with update_own_followups right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'update_own_followups'"; $DB->queryOrDie($query, "0.85 delete update_own_followups right"); // delete delete_followups foreach ($DB->request("glpi_profilerights", "`name` = 'delete_followups' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . PURGE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'followup'"; $DB->queryOrDie($query, "0.85 update followup with delete_followups right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'delete_followups'"; $DB->queryOrDie($query, "0.85 delete delete_followups right"); // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'task'") == 0) { // rename create_ticket $query = "UPDATE `glpi_profilerights`\n SET `name` = 'task'\n WHERE `name` = 'global_add_tasks'"; $DB->queryOrDie($query, "0.85 rename global_add_tasks to task"); $query = "UPDATE `glpi_profilerights`\n SET `rights` = " . TicketTask::ADDALLTICKET . "\n WHERE `name` = 'task'\n AND `rights` = '1'"; $DB->queryOrDie($query, "0.85 update followup with global_add_tasks right"); } // delete update_tasks foreach ($DB->request("glpi_profilerights", "`name` = 'update_tasks' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . READ . " | " . TicketTask::UPDATEALL . " | " . PURGE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'task'"; $DB->queryOrDie($query, "0.85 update task with update_tasks right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'update_tasks'"; $DB->queryOrDie($query, "0.85 delete update_tasks right"); // delete observe_ticket for task foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'task'"; $DB->queryOrDie($query, "0.85 update task with observe_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'observe_ticket'"; $DB->queryOrDie($query, "0.85 delete observe_ticket right"); // delete show_full_ticket for task foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . " | " . TicketTask::SEEPRIVATE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'task'"; $DB->queryOrDie($query, "0.85 update task with show_full_ticket right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_full_ticket'"; $DB->queryOrDie($query, "0.85 delete show_full_ticket right"); // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'ticketvalidation'") == 0) { // rename delete_validations $query = "UPDATE `glpi_profilerights`\n SET `name` = 'ticketvalidation'\n WHERE `name` = 'delete_validations'"; $DB->queryOrDie($query, "0.85 rename delete_validations to ticketvalidation"); $query = "UPDATE `glpi_profilerights`\n SET `rights` = " . DELETE . "\n WHERE `name` = 'ticketvalidation'\n AND `rights` = '1'"; $DB->queryOrDie($query, "0.85 update ticketvalidation with delete_validations right"); } // delete create_request_validation foreach ($DB->request("glpi_profilerights", "`name` = 'create_request_validation' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketValidation::CREATEREQUEST . " | " . PURGE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticketvalidation'"; $DB->queryOrDie($query, "0.85 update ticketvalidation with create_request_validation right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'create_request_validation'"; $DB->queryOrDie($query, "0.85 delete create_request_validation right"); // delete create_incident_validation foreach ($DB->request("glpi_profilerights", "`name` = 'create_incident_validation' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketValidation::CREATEINCIDENT . " | " . PURGE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticketvalidation'"; $DB->queryOrDie($query, "0.85 update ticketvalidation with create_incident_validation right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'create_incident_validation'"; $DB->queryOrDie($query, "0.85 delete create_incident_validation right"); // delete validate_request foreach ($DB->request("glpi_profilerights", "`name` = 'validate_request' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketValidation::VALIDATEREQUEST . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticketvalidation'"; $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_request right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'validate_request'"; $DB->queryOrDie($query, "0.85 delete validate_request right"); // delete validate_incident foreach ($DB->request("glpi_profilerights", "`name` = 'validate_incident' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . TicketValidation::VALIDATEINCIDENT . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'ticketvalidation'"; $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_incident right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'validate_incident'"; $DB->queryOrDie($query, "0.85 delete validate_incident right"); // must be done after ticket right // pour que la procédure soit ré-entrante if (countElementsInTable("glpi_profilerights", "`name` = 'change'") == 0) { ProfileRight::addProfileRights(array('change')); ProfileRight::updateProfileRightAsOtherRight('change', Change::READMY, "`name` = 'ticket'\n AND `rights` & " . Ticket::OWN); ProfileRight::updateProfileRightAsOtherRight('change', Change::READALL, "`name` = 'ticket'\n AND `rights` & " . Ticket::READALL); ProfileRight::updateProfileRightAsOtherRight('change', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE, "`name` = 'ticket' AND `rights` & " . UPDATE); } if (countElementsInTable("glpi_profilerights", "`name` = 'changevalidation'") == 0) { ProfileRight::addProfileRights(array('changevalidation')); ProfileRight::updateProfileRightAsOtherRight('changevalidation', CREATE, "`name` = 'ticketvalidation'\n AND `rights` & " . TicketValidation::CREATEINCIDENT . "\n AND `rights` & " . TicketValidation::CREATEREQUEST); ProfileRight::updateProfileRightAsOtherRight('changevalidation', ChangeValidation::VALIDATE, "`name` = 'ticketvalidation'\n AND `rights` & " . TicketValidation::VALIDATEINCIDENT . "\n AND `rights` & " . TicketValidation::VALIDATEREQUEST); ProfileRight::updateProfileRightAsOtherRight('changevalidation', PURGE, "`name` = 'ticketvalidation'\n AND `rights` & " . PURGE); } // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'planning'") == 0) { // rename show_planning $query = "UPDATE `glpi_profilerights`\n SET `name` = 'planning'\n WHERE `name` = 'show_planning'"; $DB->queryOrDie($query, "0.85 rename show_planning to planning"); // READMY = 1 => do update needed } // delete show_group_planning foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_planning' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Planning::READGROUP . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'planning'"; $DB->queryOrDie($query, "0.85 update planning with show_group_planning right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_group_planning'"; $DB->queryOrDie($query, "0.85 delete show_group_planning right"); // delete show_all_planning foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_planning' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Planning::READALL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'planning'"; $DB->queryOrDie($query, "0.85 update planning with show_all_planning right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_all_planning'"; $DB->queryOrDie($query, "0.85 delete show_all_planning right"); // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'problem'") == 0) { // rename show_my_problem $query = "UPDATE `glpi_profilerights`\n SET `name` = 'problem'\n WHERE `name` = 'show_my_problem'"; $DB->queryOrDie($query, "0.85 rename show_my_problem to problem"); // READMY = 1 => do update needed } // delete show_all_problem foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_problem' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Problem::READALL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'problem'"; $DB->queryOrDie($query, "0.85 update problem with show_all_problem right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'show_all_problem'"; $DB->queryOrDie($query, "0.85 delete show_all_problem right"); // delete edit_all_problem foreach ($DB->request("glpi_profilerights", "`name` = 'edit_all_problem' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . CREATE . " | " . UPDATE . " | " . PURGE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'problem'"; $DB->queryOrDie($query, "0.85 update problem with edit_all_problem right"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'edit_all_problem'"; $DB->queryOrDie($query, "0.85 delete edit_all_problem right"); // delete delete_problem foreach ($DB->request("glpi_profilerights", "`name` = 'delete_problem' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . DELETE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'problem'"; $DB->queryOrDie($query, "0.85 update problem with delete_problem"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'delete_problem'"; $DB->queryOrDie($query, "0.85 delete problem right"); // update search_config foreach ($DB->request("glpi_profilerights", "`name` = 'search_config' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . DisplayPreference::PERSONAL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'search_config'"; $DB->queryOrDie($query, "0.85 update search_config with search_config"); } // delete search_config_global foreach ($DB->request("glpi_profilerights", "`name` = 'search_config_global' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . DisplayPreference::GENERAL . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'search_config'"; $DB->queryOrDie($query, "0.85 update search_config with search_config_global"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'search_config_global'"; $DB->queryOrDie($query, "0.85 delete search_config_global right"); // delete check_update foreach ($DB->request("glpi_profilerights", "`name` = 'check_update' AND `rights` = '1'") as $profrights) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . Backup::CHECKUPDATE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = 'backup'"; $DB->queryOrDie($query, "0.85 update backup with check_update"); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'check_update'"; $DB->queryOrDie($query, "0.85 delete check_update right"); // entity_dropdown => right by object // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile if (countElementsInTable("glpi_profilerights", "`name` = 'domain'") == 0) { ProfileRight::addProfileRights(array('domain')); ProfileRight::updateProfileRightsAsOtherRights('domain', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'location'") == 0) { ProfileRight::addProfileRights(array('location')); ProfileRight::updateProfileRightsAsOtherRights('location', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'itilcategory'") == 0) { ProfileRight::addProfileRights(array('itilcategory')); ProfileRight::updateProfileRightsAsOtherRights('itilcategory', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'knowbasecategory'") == 0) { ProfileRight::addProfileRights(array('knowbasecategory')); ProfileRight::updateProfileRightsAsOtherRights('knowbasecategory', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'netpoint'") == 0) { ProfileRight::addProfileRights(array('netpoint')); ProfileRight::updateProfileRightsAsOtherRights('netpoint', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'taskcategory'") == 0) { ProfileRight::addProfileRights(array('taskcategory')); ProfileRight::updateProfileRightsAsOtherRights('taskcategory', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'state'") == 0) { ProfileRight::addProfileRights(array('state')); ProfileRight::updateProfileRightsAsOtherRights('state', 'entity_dropdown'); } if (countElementsInTable("glpi_profilerights", "`name` = 'solutiontemplate'") == 0) { ProfileRight::addProfileRights(array('solutiontemplate')); ProfileRight::updateProfileRightsAsOtherRights('solutiontemplate', 'entity_dropdown'); } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'entity_dropdown'"; $DB->queryOrDie($query, "0.85 delete entity_dropdown right"); // delete notes $tables = array('budget', 'cartridge', 'change', 'computer', 'consumable', 'contact_enterprise', 'contract', 'document', 'entity', 'monitor', 'networking', 'peripheral', 'phone', 'printer', 'problem', 'software'); foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '1'") as $profrights) { foreach ($tables as $table) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . READNOTE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = '{$table}'"; $DB->queryOrDie($query, "0.85 update {$table} with read notes right"); } } foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) { foreach ($tables as $table) { $query = "UPDATE `glpi_profilerights`\n SET `rights` = `rights` | " . READNOTE . " | " . UPDATENOTE . "\n WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n AND `name` = '{$table}'"; $DB->queryOrDie($query, "0.85 update {$table} with update notes right"); } } $query = "DELETE\n FROM `glpi_profilerights`\n WHERE `name` = 'notes'"; $DB->queryOrDie($query, "0.85 delete notes right"); $DELFROMDISPLAYPREF['Profile'] = array(29, 35, 37, 43, 53, 54, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 88, 93, 94, 95, 96, 97, 98, 99, 104, 113, 114, 116, 117, 121, 122, 123); $migration->displayMessage('Update for mailqueue'); if (!TableExists('glpi_queuedmails')) { $query = "CREATE TABLE `glpi_queuedmails` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n `notificationtemplates_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n `sent_try` int(11) NOT NULL DEFAULT '0',\n `create_time` datetime DEFAULT NULL,\n `send_time` datetime DEFAULT NULL,\n `sent_time` datetime DEFAULT NULL,\n `name` TEXT DEFAULT NULL,\n `sender` TEXT DEFAULT NULL,\n `sendername` TEXT DEFAULT NULL,\n `recipient` TEXT DEFAULT NULL,\n `recipientname` TEXT DEFAULT NULL,\n `replyto` TEXT DEFAULT NULL,\n `replytoname` TEXT DEFAULT NULL,\n `headers` TEXT DEFAULT NULL,\n `body_html` LONGTEXT DEFAULT NULL,\n `body_text` LONGTEXT DEFAULT NULL,\n `messageid` TEXT DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `item` (`itemtype`,`items_id`, `notificationtemplates_id`),\n KEY `is_deleted` (`is_deleted`),\n KEY `entities_id` (`entities_id`),\n KEY `sent_try` (`sent_try`),\n KEY `create_time` (`create_time`),\n KEY `send_time` (`send_time`),\n KEY `sent_time` (`sent_time`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add glpi_queuedmails"); $ADDTODISPLAYPREF['QueueMail'] = array(16, 7, 20, 21, 22, 15); } if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmail'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('QueuedMail', 'queuedmail', 60, 50, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail"); } if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmailclean'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('QueuedMail', 'queuedmailclean', 86400, 30, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail"); } if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='temp'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('Crontask', 'temp', 3600, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.85 populate glpi_crontasks for clean temporary files"); } if ($migration->addField("glpi_entities", "delay_send_emails", "integer", array('value' => -2))) { $migration->migrationOneTable('glpi_entities'); // Set directly to root entity $query = 'UPDATE `glpi_entities` SET `delay_send_emails` = 0 WHERE `id` = 0'; $DB->queryOrDie($query, "0.85 default value for delay_send_emails for root entity"); } // pour que la procédure soit ré-entrante if (countElementsInTable("glpi_profilerights", "`name` = 'queuedmail'") == 0) { ProfileRight::addProfileRights(array('queuedmail')); ProfileRight::updateProfileRightsAsOtherRights('queuedmail', 'notification'); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Change')); // changes management if (!TableExists('glpi_changes')) { $query = "CREATE TABLE `glpi_changes` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) DEFAULT NULL,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n `status` int(11) NOT NULL DEFAULT '1',\n `content` longtext DEFAULT NULL,\n `date_mod` DATETIME DEFAULT NULL,\n `date` DATETIME DEFAULT NULL,\n `solvedate` DATETIME DEFAULT NULL,\n `closedate` DATETIME DEFAULT NULL,\n `due_date` DATETIME DEFAULT NULL,\n `users_id_recipient` int(11) NOT NULL DEFAULT '0',\n `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n `urgency` int(11) NOT NULL DEFAULT '1',\n `impact` int(11) NOT NULL DEFAULT '1',\n `priority` int(11) NOT NULL DEFAULT '1',\n `itilcategories_id` int(11) NOT NULL DEFAULT '0',\n `impactcontent` longtext DEFAULT NULL,\n `controlistcontent` longtext DEFAULT NULL,\n `rolloutplancontent` longtext DEFAULT NULL,\n `backoutplancontent` longtext DEFAULT NULL,\n `checklistcontent` longtext DEFAULT NULL,\n `global_validation` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'none',\n `validation_percent` int(11) NOT NULL DEFAULT '0',\n `solutiontypes_id` int(11) NOT NULL DEFAULT '0',\n `solution` text COLLATE utf8_unicode_ci,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `begin_waiting_date` datetime DEFAULT NULL,\n `waiting_duration` int(11) NOT NULL DEFAULT '0',\n `close_delay_stat` int(11) NOT NULL DEFAULT '0',\n `solve_delay_stat` int(11) NOT NULL DEFAULT '0',\n `notepad` LONGTEXT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `is_deleted` (`is_deleted`),\n KEY `date` (`date`),\n KEY `closedate` (`closedate`),\n KEY `status` (`status`),\n KEY `priority` (`priority`),\n KEY `date_mod` (`date_mod`),\n KEY `itilcategories_id` (`itilcategories_id`),\n KEY `users_id_recipient` (`users_id_recipient`),\n KEY `solvedate` (`solvedate`),\n KEY `solutiontypes_id` (`solutiontypes_id`),\n KEY `urgency` (`urgency`),\n KEY `impact` (`impact`),\n KEY `due_date` (`due_date`),\n KEY `global_validation` (`global_validation`),\n KEY `users_id_lastupdater` (`users_id_lastupdater`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 create glpi_changes"); } $migration->addField('glpi_itilcategories', 'is_change', 'bool', array('value' => 1)); $migration->addKey('glpi_itilcategories', 'is_change'); if (!TableExists('glpi_changes_users')) { $query = "CREATE TABLE `glpi_changes_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`type`,`users_id`,`alternative_email`),\n KEY `user` (`users_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_users"); } if (!TableExists('glpi_changes_groups')) { $query = "CREATE TABLE `glpi_changes_groups` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`type`,`groups_id`),\n KEY `group` (`groups_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_groups"); } if (!TableExists('glpi_changes_suppliers')) { $query = "CREATE TABLE `glpi_changes_suppliers` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `suppliers_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`type`,`suppliers_id`),\n KEY `group` (`suppliers_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_suppliers"); } if (!TableExists('glpi_changes_items')) { $query = "CREATE TABLE `glpi_changes_items` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`itemtype`,`items_id`),\n KEY `item` (`itemtype`,`items_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_items"); } if (!TableExists('glpi_changes_tickets')) { $query = "CREATE TABLE `glpi_changes_tickets` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`tickets_id`),\n KEY `tickets_id` (`tickets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_tickets"); } if (!TableExists('glpi_changes_problems')) { $query = "CREATE TABLE `glpi_changes_problems` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `problems_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`problems_id`),\n KEY `problems_id` (`problems_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_problems"); } if (!TableExists('glpi_changetasks')) { $query = "CREATE TABLE `glpi_changetasks` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n `state` int(11) NOT NULL DEFAULT '0',\n `date` datetime DEFAULT NULL,\n `begin` datetime DEFAULT NULL,\n `end` datetime DEFAULT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `users_id_tech` int(11) NOT NULL DEFAULT '0',\n `content` longtext COLLATE utf8_unicode_ci,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `changes_id` (`changes_id`),\n KEY `state` (`state`),\n KEY `users_id` (`users_id`),\n KEY `users_id_tech` (`users_id_tech`),\n KEY `date` (`date`),\n KEY `begin` (`begin`),\n KEY `end` (`end`),\n KEY `taskcategories_id` (taskcategories_id)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changetasks"); } if (!TableExists('glpi_changecosts')) { $query = "CREATE TABLE `glpi_changecosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `changes_id` (`changes_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_changecosts"); } if (!TableExists('glpi_changevalidations')) { $query = "CREATE TABLE `glpi_changevalidations` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `users_id_validate` int(11) NOT NULL DEFAULT '0',\n `comment_submission` text COLLATE utf8_unicode_ci,\n `comment_validation` text COLLATE utf8_unicode_ci,\n `status` int(11) NOT NULL DEFAULT '2',\n `submission_date` datetime DEFAULT NULL,\n `validation_date` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `users_id` (`users_id`),\n KEY `users_id_validate` (`users_id_validate`),\n KEY `changes_id` (`changes_id`),\n KEY `submission_date` (`submission_date`),\n KEY `validation_date` (`validation_date`),\n KEY `status` (`status`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_changevalidations"); } // Change notifications $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'Change'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Changes', 'Change', NOW())"; $DB->queryOrDie($query, "0.85 add change notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##change.action## ##change.title##',\n '##IFchange.storestatus=5##\n ##lang.change.url## : ##change.urlapprove##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description## ##ENDIFchange.storestatus##\n ##ELSEchange.storestatus## ##lang.change.url## : ##change.url## ##ENDELSEchange.storestatus##\n\n ##lang.change.description##\n\n ##lang.change.title## :##change.title##\n ##lang.change.authors## :##IFchange.authors## ##change.authors## ##ENDIFchange.authors## ##ELSEchange.authors##--##ENDELSEchange.authors##\n ##lang.change.creationdate## :##change.creationdate##\n ##IFchange.assigntousers## ##lang.change.assigntousers## : ##change.assigntousers## ##ENDIFchange.assigntousers##\n ##lang.change.status## : ##change.status##\n ##IFchange.assigntogroups## ##lang.change.assigntogroups## : ##change.assigntogroups## ##ENDIFchange.assigntogroups##\n ##lang.change.urgency## : ##change.urgency##\n ##lang.change.impact## : ##change.impact##\n ##lang.change.priority## : ##change.priority##\n##IFchange.category## ##lang.change.category## :##change.category## ##ENDIFchange.category## ##ELSEchange.category## ##lang.change.nocategoryassigned## ##ENDELSEchange.category##\n ##lang.change.content## : ##change.content##\n\n##IFchange.storestatus=6##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description##\n##ENDIFchange.storestatus##\n ##lang.change.numberofproblems## : ##change.numberofproblems##\n\n##FOREACHproblems##\n [##problem.date##] ##lang.change.title## : ##problem.title##\n ##lang.change.content## ##problem.content##\n\n##ENDFOREACHproblems##\n ##lang.change.numberoftasks## : ##change.numberoftasks##\n\n##FOREACHtasks##\n [##task.date##]\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##\n',\n '<p>##IFchange.storestatus=5##</p>\n<div>##lang.change.url## : <a href=\"##change.urlapprove##\">##change.urlapprove##</a></div>\n<div><span style=\"color: #888888;\"><strong><span style=\"text-decoration: underline;\">##lang.change.solvedate##</span></strong></span> : ##change.solvedate##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.change.solution.type##</strong></span> : ##change.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.change.solution.description##</strong></span> : ##change.solution.description## ##ENDIFchange.storestatus##</div>\n<div>##ELSEchange.storestatus## ##lang.change.url## : <a href=\"##change.url##\">##change.url##</a> ##ENDELSEchange.storestatus##</div>\n<p class=\"description b\"><strong>##lang.change.description##</strong></p>\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.title##</span> :##change.title## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.authors##</span> :##IFchange.authors## ##change.authors## ##ENDIFchange.authors## ##ELSEchange.authors##--##ENDELSEchange.authors## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.creationdate##</span> :##change.creationdate## <br /> ##IFchange.assigntousers## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.assigntousers##</span> : ##change.assigntousers## ##ENDIFchange.assigntousers##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.change.status## </span> : ##change.status##<br /> ##IFchange.assigntogroups## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.assigntogroups##</span> : ##change.assigntogroups## ##ENDIFchange.assigntogroups##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.urgency##</span> : ##change.urgency##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.impact##</span> : ##change.impact##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.priority##</span> : ##change.priority## <br />##IFchange.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.change.category## </span> :##change.category## ##ENDIFchange.category## ##ELSEchange.category## ##lang.change.nocategoryassigned## ##ENDELSEchange.category## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.content##</span> : ##change.content##</p>\n<p>##IFchange.storestatus=6##<br /><span style=\"text-decoration: underline;\"><strong><span style=\"color: #888888;\">##lang.change.solvedate##</span></strong></span> : ##change.solvedate##<br /><span style=\"color: #888888;\"><strong><span style=\"text-decoration: underline;\">##lang.change.solution.type##</span></strong></span> : ##change.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.change.solution.description##</strong></span> : ##change.solution.description##<br />##ENDIFchange.storestatus##</p>\n<div class=\"description b\">##lang.change.numberofproblems## : ##change.numberofproblems##</div>\n<p>##FOREACHproblems##</p>\n<div><strong> [##problem.date##] <em>##lang.change.title## : <a href=\"##problem.url##\">##problem.title## </a></em></strong><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> </span><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.change.content## </span> ##problem.content##\n<p>##ENDFOREACHproblems##</p>\n<div class=\"description b\">##lang.change.numberoftasks## : ##change.numberoftasks##</div>\n<p>##FOREACHtasks##</p>\n<div class=\"description b\"><strong>[##task.date##] </strong><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.author##</span> ##task.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.description##</span> ##task.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.time##</span> ##task.time##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.category##</span> ##task.category##</div>\n<p>##ENDFOREACHtasks##</p>\n</div>')"; $DB->queryOrDie($query, "0.85 add change notification translation"); $notifications = array('new' => array(), 'update' => array(Notification::ASSIGN_TECH, Notification::OLD_TECH_IN_CHARGE), 'solved' => array(), 'add_task' => array(), 'update_task' => array(), 'delete_task' => array(), 'closed' => array(), 'delete' => array()); $notif_names = array('new' => 'New Change', 'update' => 'Update Change', 'solved' => 'Resolve Change', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Change', 'delete' => 'Delete Change'); foreach ($notifications as $key => $val) { $notifications[$key][] = Notification::AUTHOR; $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR; $notifications[$key][] = Notification::OBSERVER; } foreach ($notifications as $type => $targets) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . $notif_names[$type] . "', 0, 'Change', '{$type}', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.85 add change {$type} notification"); $notifid = $DB->insert_id(); foreach ($targets as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});"; $DB->queryOrDie($query, "0.85 add change {$type} notification target"); } } } } $ADDTODISPLAYPREF['Change'] = array(12, 19, 15, 7, 18); $migration->addField('glpi_profiles', 'change_status', "text", array('comment' => "json encoded array of from/dest allowed status change")); // Add problem costs if (!TableExists('glpi_problemcosts')) { $query = "CREATE TABLE `glpi_problemcosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `problems_id` (`problems_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_problemcosts"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'drop rules cache')); $migration->dropTable('glpi_rulecachecomputermodels'); $migration->dropTable('glpi_rulecachecomputertypes'); $migration->dropTable('glpi_rulecachemanufacturers'); $migration->dropTable('glpi_rulecachemonitormodels'); $migration->dropTable('glpi_rulecachemonitortypes'); $migration->dropTable('glpi_rulecachenetworkequipmentmodels'); $migration->dropTable('glpi_rulecachenetworkequipmenttypes'); $migration->dropTable('glpi_rulecacheoperatingsystems'); $migration->dropTable('glpi_rulecacheoperatingsystemservicepacks'); $migration->dropTable('glpi_rulecacheoperatingsystemversions'); $migration->dropTable('glpi_rulecacheperipheralmodels'); $migration->dropTable('glpi_rulecacheperipheraltypes'); $migration->dropTable('glpi_rulecachephonemodels'); $migration->dropTable('glpi_rulecachephonetypes'); $migration->dropTable('glpi_rulecacheprintermodels'); $migration->dropTable('glpi_rulecacheprinters'); $migration->dropTable('glpi_rulecacheprintertypes'); $migration->dropTable('glpi_rulecachesoftwares'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_rules')); $migration->addField("glpi_rules", 'uuid', "string"); $migration->addField("glpi_slalevels", 'uuid', "string"); $migration->migrationOneTable('glpi_rules'); $migration->migrationOneTable('glpi_slalevels'); // Dropdown translations $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_knowbaseitemtranslations')); Config::setConfigurationValues('core', array('translate_kb' => 0)); if (!TableExists("glpi_knowbaseitemtranslations")) { $query = "CREATE TABLE IF NOT EXISTS `glpi_knowbaseitemtranslations` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n `name` text COLLATE utf8_unicode_ci,\n `answer` longtext COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `item` (`knowbaseitems_id`, `language`),\n FULLTEXT KEY `fulltext` (`name`,`answer`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_knowbaseitemtranslations"); } // kb translations $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_dropdowntranslations')); Config::setConfigurationValues('core', array('translate_dropdowns' => 0)); if (!TableExists("glpi_dropdowntranslations")) { $query = "CREATE TABLE IF NOT EXISTS `glpi_dropdowntranslations` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `items_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n `field` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n `value` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`itemtype`,`items_id`,`language`,`field`),\n KEY `typeid` (`itemtype`,`items_id`),\n KEY `language` (`language`),\n KEY `field` (`field`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_dropdowntranslations"); } //generate uuid for the basic rules of glpi // we use a complete sql where for cover all migration case (0.78 -> 0.85) $rules = array(array('sub_type' => 'RuleImportEntity', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleRight', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply X-Auto-Response-Suppress', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using X-Auto-Response-Suppress header'), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply Auto-Submitted', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using Auto-Submitted header'), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from item', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from user', 'match' => 'AND', 'description' => '')); $i = 0; foreach ($rules as $rule) { $query = "UPDATE `glpi_rules`\n SET `uuid` = 'STATIC-UUID-{$i}'\n WHERE `entities_id` = 0\n AND `is_recursive` = 0\n AND `sub_type` = '" . $rule['sub_type'] . "'\n AND `name` = '" . $rule['name'] . "'\n AND `description` = '" . $rule['description'] . "'\n AND `match` = '" . $rule['match'] . "'\n ORDER BY id ASC\n LIMIT 1"; $DB->queryOrDie($query, "0.85 add uuid to basic rules (STATIC-UUID-{$i})"); $i++; } //generate uuid for the rules of user foreach ($DB->request('glpi_rules', array('uuid' => NULL)) as $data) { $uuid = Rule::getUuid(); $query = "UPDATE `glpi_rules`\n SET `uuid` = '{$uuid}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query, "0.85 add uuid to existing rules"); } foreach ($DB->request('glpi_slalevels', array('uuid' => NULL)) as $data) { $uuid = Rule::getUuid(); $query = "UPDATE `glpi_slalevels`\n SET `uuid` = '{$uuid}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query, "0.85 add uuid to existing slalevels"); } $migration->addField('glpi_users', 'is_deleted_ldap', 'bool'); $migration->addKey('glpi_users', 'is_deleted_ldap'); Config::deleteConfigurationValues('core', array('use_ajax')); Config::deleteConfigurationValues('core', array('ajax_min_textsearch_load')); Config::deleteConfigurationValues('core', array('ajax_buffertime_load')); Config::deleteConfigurationValues('core', array('is_categorized_soft_expanded')); Config::deleteConfigurationValues('core', array('is_not_categorized_soft_expanded')); $migration->dropField("glpi_users", 'is_categorized_soft_expanded'); $migration->dropField("glpi_users", 'is_not_categorized_soft_expanded'); // Config::setConfigurationValues('core', array('use_unicodefont' => 0)); // $migration->addField("glpi_users", 'use_unicodefont', "int(11) DEFAULT NULL"); Config::deleteConfigurationValues('core', array('use_unicodefont')); $migration->dropField("glpi_users", 'use_unicodefont'); Config::setConfigurationValues('core', array('pdffont' => 'helvetica')); $migration->addField("glpi_users", 'pdffont', "string"); $migration->addField("glpi_users", 'picture', "string"); $migration->addField("glpi_authldaps", 'picture_field', 'string'); $migration->addField('glpi_links', 'open_window', 'bool', array('value' => 1)); $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_states')); foreach (array('is_visible_computer', 'is_visible_monitor', 'is_visible_networkequipment', 'is_visible_peripheral', 'is_visible_phone', 'is_visible_printer', 'is_visible_softwareversion') as $field) { $migration->addField('glpi_states', $field, 'bool', array('value' => '1')); $migration->addKey('glpi_states', $field); } // glpi_domains by entity $migration->addField('glpi_domains', 'entities_id', 'integer', array('after' => 'name')); $migration->addField('glpi_domains', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id')); // glpi_states by entity $migration->addField('glpi_states', 'entities_id', 'integer', array('after' => 'name')); $migration->addField('glpi_states', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id')); // add validity date for a user $migration->addField('glpi_users', 'begin_date', 'datetime'); $migration->addField('glpi_users', 'end_date', 'datetime'); // add validity date for a knowbaseitem $migration->addField('glpi_knowbaseitems', 'begin_date', 'datetime'); $migration->addField('glpi_knowbaseitems', 'end_date', 'datetime'); // Add validation percent for tickets $migration->addField('glpi_tickets', 'validation_percent', 'integer', array('value' => 0)); // Add missing key $migration->addKey('glpi_tickettasks', 'state'); $migration->addKey('glpi_tickettasks', 'users_id_tech'); $migration->addKey('glpi_tickettasks', 'begin'); $migration->addKey('glpi_tickettasks', 'end'); // Create notification for reply to satisfaction survey based on satisfaction notif // Check if notifications already exists if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n AND `event` = 'replysatisfaction'") == 0) { // No notifications duplicate all $query = "SELECT *\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Ticket'\n AND `event` = 'satisfaction'"; foreach ($DB->request($query) as $notif) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . addslashes($notif['name']) . " Answer',\n '" . $notif['entities_id'] . "', 'Ticket',\n 'replysatisfaction', '" . $notif['mode'] . "',\n '" . $notif['notificationtemplates_id'] . "',\n '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n '" . $notif['is_active'] . "', NOW());"; $DB->queryOrDie($query, "0.85 insert replysatisfaction notification"); $newID = $DB->insert_id(); $query2 = "SELECT *\n FROM `glpi_notificationtargets`\n WHERE `notifications_id` = '" . $notif['id'] . "'"; // Add same recipent of satisfaction foreach ($DB->request($query2) as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`notifications_id`, `type`, `items_id`)\n VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')"; $DB->queryOrDie($query, "0.85 insert targets for replysatisfaction notification"); } // Add Tech in charge $query = "INSERT INTO `glpi_notificationtargets`\n (`notifications_id`, `type`, `items_id`)\n VALUES ({$newID}, '" . Notification::USER_TYPE . "', '" . Notification::ASSIGN_TECH . "')"; $DB->queryOrDie($query, "0.85 insert tech in charge target for replysatisfaction notification"); } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_slas')); // * Convert SLA resolution time to new system (ticket #4346) if (!FieldExists("glpi_slas", "definition_time")) { $migration->addField("glpi_slas", 'definition_time', "string"); $migration->addField("glpi_slas", 'end_of_working_day', "bool"); $migration->migrationOneTable('glpi_slas'); // Minutes $query = "SELECT *\n FROM `glpi_slas`\n WHERE `resolution_time` <= '3000'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $a_ids = array(); while ($data = $DB->fetch_assoc($result)) { $a_ids[] = $data['id']; } $DB->query("UPDATE `glpi_slas`\n SET `definition_time` = 'minute',\n `resolution_time` = `resolution_time`/60\n WHERE `id` IN (" . implode(",", $a_ids) . ")"); } } // Hours $query = "SELECT *\n FROM `glpi_slas`\n WHERE `resolution_time` > '3000'\n AND `resolution_time` <= '82800'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $a_ids = array(); while ($data = $DB->fetch_assoc($result)) { $a_ids[] = $data['id']; } $DB->query("UPDATE `glpi_slas`\n SET `definition_time` = 'hour',\n `resolution_time` = `resolution_time`/3600\n WHERE `id` IN (" . implode(",", $a_ids) . ")"); } } // Days $query = "SELECT *\n FROM `glpi_slas`\n WHERE `resolution_time` > '82800'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $a_ids = array(); while ($data = $DB->fetch_assoc($result)) { $a_ids[] = $data['id']; } $DB->query("UPDATE `glpi_slas`\n SET `definition_time` = 'day',\n `resolution_time` = `resolution_time`/86400\n WHERE `id` IN (" . implode(",", $a_ids) . ")"); } } } Config::setConfigurationValues('core', array('keep_devices_when_purging_item' => 0)); $migration->addField("glpi_users", "keep_devices_when_purging_item", "int(11) DEFAULT NULL"); Config::setConfigurationValues('core', array('maintenance_mode' => 0)); Config::setConfigurationValues('core', array('maintenance_text' => '')); $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'MailCollector'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Receiver errors', 'MailCollector', NOW())"; $DB->queryOrDie($query, "0.85 add mail collector notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##mailcollector.action##',\n '##FOREACHmailcollectors##\n##lang.mailcollector.name## : ##mailcollector.name##\n##lang.mailcollector.errors## : ##mailcollector.errors##\n##mailcollector.url##\n##ENDFOREACHmailcollectors##',\n'<p>##FOREACHmailcollectors##<br />##lang.mailcollector.name## : ##mailcollector.name##<br /> ##lang.mailcollector.errors## : ##mailcollector.errors##<br /><a href=\"##mailcollector.url##\">##mailcollector.url##</a><br /> ##ENDFOREACHmailcollectors##</p>\n<p></p>')"; $DB->queryOrDie($query, "0.85 add mail collector notification translation"); $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('Receiver errors', 0, 'MailCollector', 'error', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.85 add mail collector notification"); $notifid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::GLOBAL_ADMINISTRATOR . ");"; $DB->queryOrDie($query, "0.85 add mail collector notification target"); } } if (!countElementsInTable('glpi_crontasks', "`itemtype`='MailCollector' AND `name`='mailgateerror'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('MailCollector', 'mailgateerror', " . DAY_TIMESTAMP . ", NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.85 populate glpi_crontasks for mailgateerror"); } if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='circularlogs'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('Crontask', 'circularlogs', " . DAY_TIMESTAMP . ", 4, " . CronTask::STATE_DISABLE . ", 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.85 populate glpi_crontasks for circularlogs"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_documents')); $migration->addField('glpi_documents', 'is_blacklisted', 'bool'); if (!TableExists("glpi_blacklistedmailcontents")) { $query = "CREATE TABLE IF NOT EXISTS `glpi_blacklistedmailcontents` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) DEFAULT NULL,\n `content` text COLLATE utf8_unicode_ci,\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_blacklistedmailcontents"); } $migration->addField('glpi_documents', 'tag', 'string'); $migration->addField('glpi_queuedmails', 'documents', 'text'); $migration->addKey('glpi_documents', 'tag'); Config::setConfigurationValues('core', array('use_rich_text' => 0)); Config::setConfigurationValues('core', array('attach_ticket_documents_to_mail' => 0)); $migration->migrationOneTable('glpi_documents'); $query = "UPDATE `glpi_documents`\n SET `tag` = `id`"; $DB->queryOrDie($query, "0.85 set tag to all documents"); // increase password length $migration->changeField('glpi_users', 'password', 'password', 'string'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_softwarecategories')); // Hierarchical software category $migration->addField('glpi_softwarecategories', 'softwarecategories_id', 'integer'); $migration->addField("glpi_softwarecategories", 'completename', "text"); $migration->addField("glpi_softwarecategories", 'level', "integer"); $migration->addField("glpi_softwarecategories", 'ancestors_cache', "longtext"); $migration->addField("glpi_softwarecategories", 'sons_cache', "longtext"); $migration->migrationOneTable('glpi_softwarecategories'); $migration->addKey('glpi_softwarecategories', 'softwarecategories_id'); regenerateTreeCompleteName("glpi_softwarecategories"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various')); // glpi_cartridgeitems glpi_consumableitems by entity $migration->addField('glpi_consumableitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id')); $migration->addField('glpi_cartridgeitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id')); // Fix events $query = "UPDATE `glpi_events`\n SET `type` = 'consumableitems'\n WHERE `type` = 'consumables'"; $DB->queryOrDie($query, "0.85 fix events for consumables"); $query = "UPDATE `glpi_events`\n SET `type` = 'cartridgeitems'\n WHERE `type` = 'cartridges';"; $DB->queryOrDie($query, "0.85 fix events for cartridges"); // Bookmark order : $migration->addField('glpi_users', 'privatebookmarkorder', 'longtext'); // Pref to comme back ticket created if ($migration->addField('glpi_users', 'backcreated', 'TINYINT(1) DEFAULT NULL')) { $query = "INSERT INTO `glpi_configs`\n (`context`, `name`, `value`)\n VALUES ('core', 'backcreated', 0)"; $DB->queryOrDie($query, "update glpi_configs with backcreated"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_projects')); if (!TableExists("glpi_projects")) { $query = "CREATE TABLE IF NOT EXISTS `glpi_projects` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `priority` int(11) NOT NULL DEFAULT '1',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n `projects_id` int(11) NOT NULL DEFAULT '0',\n `projectstates_id` int(11) NOT NULL DEFAULT '0',\n `projecttypes_id` int(11) NOT NULL DEFAULT '0',\n `date` datetime DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `plan_start_date` datetime DEFAULT NULL,\n `plan_end_date` datetime DEFAULT NULL,\n `real_start_date` datetime DEFAULT NULL,\n `real_end_date` datetime DEFAULT NULL,\n `percent_done` int(11) NOT NULL DEFAULT '0',\n `show_on_global_gantt` tinyint(1) NOT NULL DEFAULT '0',\n `content` longtext DEFAULT NULL,\n `comment` longtext DEFAULT NULL,\n `notepad` longtext DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `code` (`code`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `projects_id` (`projects_id`),\n KEY `projectstates_id` (`projectstates_id`),\n KEY `projecttypes_id` (`projecttypes_id`),\n KEY `priority` (`priority`),\n KEY `date` (`date`),\n KEY `date_mod` (`date_mod`),\n KEY `users_id` (`users_id`),\n KEY `groups_id` (`groups_id`),\n KEY `plan_start_date` (`plan_start_date`),\n KEY `plan_end_date` (`plan_end_date`),\n KEY `real_start_date` (`real_start_date`),\n KEY `real_end_date` (`real_end_date`),\n KEY `percent_done` (`percent_done`),\n KEY `show_on_global_gantt` (`show_on_global_gantt`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_projects"); $ADDTODISPLAYPREF['Project'] = array(3, 4, 12, 5, 15, 21); } $migration->addField("glpi_projects", 'is_deleted', "bool"); if (countElementsInTable("glpi_profilerights", "`name` = 'project'") == 0) { ProfileRight::addProfileRights(array('project')); ProfileRight::updateProfileRightAsOtherRight('project', Project::READMY, "`name` = 'change'\n AND `rights` & " . Change::READMY); ProfileRight::updateProfileRightAsOtherRight('project', Project::READALL, "`name` = 'change'\n AND `rights` & " . Change::READALL); ProfileRight::updateProfileRightAsOtherRight('project', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . " | " . READNOTE . " | " . UPDATENOTE, "`name` = 'change'\n AND `rights` & (" . CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . ')'); } if (countElementsInTable("glpi_profilerights", "`name` = 'projecttask'") == 0) { ProfileRight::addProfileRights(array('projecttask')); ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::READMY, "`name` = 'change'\n AND `rights` & " . Change::READMY); ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::UPDATEMY, "`name` = 'change'\n AND `rights` & " . Change::READMY); } if (!TableExists('glpi_projectcosts')) { $query = "CREATE TABLE `glpi_projectcosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `projects_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `projects_id` (`projects_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_projectcosts"); } if (!TableExists('glpi_projectstates')) { $query = "CREATE TABLE `glpi_projectstates` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `color` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `is_finished` tinyint(1) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `is_finished` (`is_finished`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 create glpi_projectstates"); $ADDTODISPLAYPREF['ProjectState'] = array(12, 11); $states = array('new' => array('name' => _x('ticket', 'New'), 'color' => '#06ff00', 'is_finished' => 0), 'do' => array('name' => __('Processing'), 'color' => '#ffb800', 'is_finished' => 0), 'end' => array('name' => __('Closed'), 'color' => '#ff0000', 'is_finished' => 1)); foreach ($states as $key => $val) { $query = "INSERT INTO `glpi_projectstates`\n (`name`,`color`,`is_finished`)\n VALUES ('" . addslashes($val['name']) . "','" . addslashes($val['color']) . "',\n '" . addslashes($val['is_finished']) . "')"; $DB->queryOrDie($query, "0.85 insert default project state {$key}"); } } if (!TableExists('glpi_projecttypes')) { $query = "CREATE TABLE `glpi_projecttypes` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 create glpi_projecttypes"); } $migration->addField("glpi_groups", 'is_manager', "bool", array('update' => "`is_assign`", 'value' => 1)); $migration->addKey('glpi_groups', 'is_manager'); if (!TableExists('glpi_changes_projects')) { $query = "CREATE TABLE `glpi_changes_projects` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `changes_id` int(11) NOT NULL DEFAULT '0',\n `projects_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`changes_id`,`projects_id`),\n KEY `projects_id` (`projects_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_changes_projects"); } if (!TableExists('glpi_projectteams')) { $query = "CREATE TABLE `glpi_projectteams` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `projects_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n KEY `item` (`itemtype`,`items_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_projectteams"); } if (!TableExists('glpi_items_projects')) { $query = "CREATE TABLE `glpi_items_projects` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `projects_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n KEY `item` (`itemtype`,`items_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_items_projects"); } if (!TableExists("glpi_projecttasks")) { $query = "CREATE TABLE IF NOT EXISTS `glpi_projecttasks` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `content` longtext DEFAULT NULL,\n `comment` longtext DEFAULT NULL,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n `projects_id` int(11) NOT NULL DEFAULT '0',\n `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n `date` datetime DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n `plan_start_date` datetime DEFAULT NULL,\n `plan_end_date` datetime DEFAULT NULL,\n `real_start_date` datetime DEFAULT NULL,\n `real_end_date` datetime DEFAULT NULL,\n `planned_duration` int(11) NOT NULL DEFAULT '0',\n `effective_duration` int(11) NOT NULL DEFAULT '0',\n `projectstates_id` int(11) NOT NULL DEFAULT '0',\n `projecttasktypes_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n `percent_done` int(11) NOT NULL DEFAULT '0',\n `notepad` longtext DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `projects_id` (`projects_id`),\n KEY `projecttasks_id` (`projecttasks_id`),\n KEY `date` (`date`),\n KEY `date_mod` (`date_mod`),\n KEY `users_id` (`users_id`),\n KEY `plan_start_date` (`plan_start_date`),\n KEY `plan_end_date` (`plan_end_date`),\n KEY `real_start_date` (`real_start_date`),\n KEY `real_end_date` (`real_end_date`),\n KEY `percent_done` (`percent_done`),\n KEY `projectstates_id` (`projectstates_id`),\n KEY `projecttasktypes_id` (`projecttasktypes_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.85 add table glpi_projecttasks"); $ADDTODISPLAYPREF['ProjectTask'] = array(2, 12, 14, 5, 7, 8, 13); } if (!TableExists('glpi_projecttasktypes')) { $query = "CREATE TABLE `glpi_projecttasktypes` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 create glpi_projecttasktypes"); } if (!TableExists('glpi_projecttaskteams')) { $query = "CREATE TABLE `glpi_projecttaskteams` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`projecttasks_id`,`itemtype`,`items_id`),\n KEY `item` (`itemtype`,`items_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_projecttaskteams"); } if (!TableExists('glpi_projecttasks_tickets')) { $query = "CREATE TABLE `glpi_projecttasks_tickets` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`tickets_id`,`projecttasks_id`),\n KEY `projects_id` (`projecttasks_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_projecttasks_tickets"); } // Project notifications $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'Project'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Projects', 'Project', NOW())"; $DB->queryOrDie($query, "0.85 add project notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##project.action## ##project.name## ##project.code##',\n '##lang.project.url## : ##project.url##\n\n##lang.project.description##\n\n##lang.project.name## : ##project.name##\n##lang.project.code## : ##project.code##\n##lang.project.manager## : ##project.manager##\n##lang.project.managergroup## : ##project.managergroup##\n##lang.project.creationdate## : ##project.creationdate##\n##lang.project.priority## : ##project.priority##\n##lang.project.state## : ##project.state##\n##lang.project.type## : ##project.type##\n##lang.project.description## : ##project.description##\n\n##lang.project.numberoftasks## : ##project.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n '<p>##lang.project.url## : <a href=\"##project.url##\">##project.url##</a></p>\n<p><strong>##lang.project.description##</strong></p>\n<p>##lang.project.name## : ##project.name##<br />##lang.project.code## : ##project.code##<br /> ##lang.project.manager## : ##project.manager##<br />##lang.project.managergroup## : ##project.managergroup##<br /> ##lang.project.creationdate## : ##project.creationdate##<br />##lang.project.priority## : ##project.priority## <br />##lang.project.state## : ##project.state##<br />##lang.project.type## : ##project.type##<br />##lang.project.description## : ##project.description##</p>\n<p>##lang.project.numberoftasks## : ##project.numberoftasks##</p>\n<div>\n<p>##FOREACHtasks##</p>\n<div><strong>[##task.creationdate##] </strong><br /> ##lang.task.name## : ##task.name##<br />##lang.task.state## : ##task.state##<br />##lang.task.type## : ##task.type##<br />##lang.task.percent## : ##task.percent##<br />##lang.task.description## : ##task.description##</div>\n<p>##ENDFOREACHtasks##</p>\n</div>')"; $DB->queryOrDie($query, "0.85 add project notification translation"); $notifications = array('new' => array(), 'update' => array(), 'delete' => array()); $notif_names = array('new' => 'New Project', 'update' => 'Update Project', 'delete' => 'Delete Project'); foreach ($notifications as $key => $val) { $notifications[$key][] = Notification::MANAGER_USER; $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR; $notifications[$key][] = Notification::MANAGER_GROUP; } foreach ($notifications as $type => $targets) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . $notif_names[$type] . "', 0, 'Project', '{$type}', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.85 add project {$type} notification"); $notifid = $DB->insert_id(); foreach ($targets as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});"; $DB->queryOrDie($query, "0.85 add project {$type} notification target"); } } } } // Project Task notifications $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'ProjectTask'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Project Tasks', 'ProjectTask', NOW())"; $DB->queryOrDie($query, "0.85 add project task notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##projecttask.action## ##projecttask.name##',\n '##lang.projecttask.url## : ##projecttask.url##\n\n##lang.projecttask.description##\n\n##lang.projecttask.name## : ##projecttask.name##\n##lang.projecttask.project## : ##projecttask.name##\n##lang.projecttask.creationdate## : ##projecttask.creationdate##\n##lang.projecttask.state## : ##projecttask.state##\n##lang.projecttask.type## : ##projecttask.type##\n##lang.projecttask.description## : ##projecttask.description##\n\n##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n '<p>##lang.projecttask.url## : <a href=\"##projecttask.url##\">##projecttask.url##</a></p>\n<p><strong>##lang.projecttask.description##</strong></p>\n<p>##lang.projecttask.name## : ##projecttask.name##<br />##lang.projecttask.project## : <a href=\"##projecttask.projecturl##\">##projecttask.name##</a><br />##lang.projecttask.creationdate## : ##projecttask.creationdate##<br />##lang.projecttask.state## : ##projecttask.state##<br />##lang.projecttask.type## : ##projecttask.type##<br />##lang.projecttask.description## : ##projecttask.description##</p>\n<p>##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##</p>\n<div>\n<p>##FOREACHtasks##</p>\n<div><strong>[##task.creationdate##] </strong><br />##lang.task.name## : ##task.name##<br />##lang.task.state## : ##task.state##<br />##lang.task.type## : ##task.type##<br />##lang.task.percent## : ##task.percent##<br />##lang.task.description## : ##task.description##</div>\n<p>##ENDFOREACHtasks##</p>\n</div>')"; $DB->queryOrDie($query, "0.85 add project task notification translation"); $notifications = array('new' => array(), 'update' => array(), 'delete' => array()); $notif_names = array('new' => 'New Project Task', 'update' => 'Update Project Task', 'delete' => 'Delete Project Task'); foreach ($notifications as $key => $val) { $notifications[$key][] = Notification::TEAM_USER; $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR; $notifications[$key][] = Notification::TEAM_GROUP; } foreach ($notifications as $type => $targets) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . $notif_names[$type] . "', 0, 'ProjectTask', '{$type}', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.85 add project task {$type} notification"); $notifid = $DB->insert_id(); foreach ($targets as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});"; $DB->queryOrDie($query, "0.85 add project task {$type} notification target"); } } } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'notepad')); // Create new notepad table if (!TableExists('glpi_notepads')) { $query = "CREATE TABLE `glpi_notepads` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n `date` datetime DEFAULT NULL,\n `date_mod` datetime DEFAULT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n `content` LONGTEXT DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `item` (`itemtype`,`items_id`),\n KEY `date_mod` (`date_mod`),\n KEY `date` (`date`),\n KEY `users_id_lastupdater` (`users_id_lastupdater`),\n KEY `users_id` (`users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_notepads"); $notepad_tables = array('glpi_budgets', 'glpi_cartridgeitems', 'glpi_changes', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_entities', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_problems', 'glpi_projects', 'glpi_projecttasks', 'glpi_softwares', 'glpi_suppliers'); foreach ($notepad_tables as $t) { // Migrate data if (FieldExists($t, 'notepad')) { $query = "SELECT id, notepad\n FROM `{$t}`\n WHERE notepad IS NOT NULL\n AND notepad <>'';"; foreach ($DB->request($query) as $data) { $iq = "INSERT INTO `glpi_notepads`\n (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\n VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\n '" . addslashes($data['notepad']) . "', NOW(), NOW())"; $DB->queryOrDie($iq, "0.85 migrate notepad data"); } $migration->dropField($t, 'notepad'); } } } $migration->addField('glpi_deviceprocessors', 'nbcores_default', 'int'); $migration->addField('glpi_deviceprocessors', 'nbthreads_default', 'int'); $migration->addField('glpi_items_deviceprocessors', 'nbcores', 'int'); $migration->addField('glpi_items_deviceprocessors', 'nbthreads', 'int'); $migration->addKey('glpi_items_deviceprocessors', 'nbcores'); $migration->addKey('glpi_items_deviceprocessors', 'nbthreads'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticketvalidations status')); $status = array('none' => CommonITILValidation::NONE, 'waiting' => CommonITILValidation::WAITING, 'accepted' => CommonITILValidation::ACCEPTED, 'rejected' => CommonITILValidation::REFUSED); // Migrate datas foreach ($status as $old => $new) { $query = "UPDATE `glpi_ticketvalidations`\n SET `status` = '{$new}'\n WHERE `status` = '{$old}'"; $DB->queryOrDie($query, "0.85 status in glpi_ticketvalidations {$old} to {$new}"); } $migration->changeField('glpi_ticketvalidations', 'status', 'status', 'integer', array('value' => CommonITILValidation::WAITING)); $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and changes global_validation')); $tables = array('glpi_tickets', 'glpi_changes'); foreach ($tables as $table) { foreach ($status as $old => $new) { $query = "UPDATE `" . $table . "`\n SET `global_validation` = '{$new}'\n WHERE `global_validation` = '{$old}'"; $DB->queryOrDie($query, "0.85 global_validation in {$table} {$old} to {$new}"); } $migration->changeField($table, 'global_validation', 'global_validation', 'integer', array('value' => CommonITILValidation::NONE)); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickettemplatepredefinedfields value')); foreach ($status as $old => $new) { $query = "UPDATE `glpi_tickettemplatepredefinedfields`\n SET `value` = '{$new}'\n WHERE `num` = '52'\n AND `value` = '{$old}'"; $DB->queryOrDie($query, "0.85 value in glpi_tickettemplatepredefinedfields {$old} to {$new}"); } // Migrate templates $query = "SELECT `glpi_notificationtemplatetranslations`.*\n FROM `glpi_notificationtemplatetranslations`\n INNER JOIN `glpi_notificationtemplates`\n ON (`glpi_notificationtemplates`.`id`\n = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n WHERE `glpi_notificationtemplatetranslations`.`content_text` LIKE '%validation.storestatus=%'\n OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%validation.storestatus=%'\n OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%validation.storestatus=%'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $subject = $data['subject']; $text = $data['content_text']; $html = $data['content_html']; foreach ($status as $old => $new) { $subject = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $subject); $text = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $text); $html = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $html); } $query = "UPDATE `glpi_notificationtemplatetranslations`\n SET `subject` = '" . addslashes($subject) . "',\n `content_text` = '" . addslashes($text) . "',\n `content_html` = '" . addslashes($html) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->queryOrDie($query, "0.85 fix tags usage for storestatus"); } } } // Upgrade ticket bookmarks $query = "SELECT *\n FROM `glpi_bookmarks`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $num = 0; $num2 = 0; $options = array(); parse_str($data["query"], $options); if (isset($options['field'])) { // update ticket statuses if (($data['itemtype'] = 'Ticket') && $data['type'] == Bookmark::SEARCH) { foreach ($options['field'] as $key => $val) { if (($val == 55 || $val == 52) && isset($options['contains'][$key])) { if (isset($status[$options['contains'][$key]])) { $options['contains'][$key] = $status[$options['contains'][$key]]; } } } } } $query2 = "UPDATE `glpi_bookmarks`\n SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query2, "0.85 update bookmarks"); } } } ////////////////////////////////////////////////// // Device update $migration->displayMessage(sprintf(__('Data migration - %s'), 'Devices')); foreach (array_merge(CommonDevice::getDeviceTypes(), Item_Devices::getDeviceTypes()) as $itemtype) { $table = $itemtype::getTable(); if (!FieldExists($table, 'entities_id')) { $migration->addField($table, 'entities_id', 'integer'); $migration->addKey($table, array('entities_id'), 'entities_id'); } if (!FieldExists($table, 'is_recursive')) { $migration->addField($table, 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id')); $migration->addKey($table, array('is_recursive'), 'is_recursive'); } } // Adding the Registered ID class that contains PCI IDs and USB IDs for vendors // as well devices if (!TableExists('glpi_registeredids')) { $query = "CREATE TABLE `glpi_registeredids` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) DEFAULT NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n `device_type` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'USB, PCI ...',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `item` (`items_id`, `itemtype`),\n KEY `device_type` (`device_type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.85 add table glpi_registeredids"); } // Complete the item_devices foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_devicesoundcards') as $table) { if (!FieldExists($table, 'serial')) { $migration->addField($table, 'serial', 'string'); $migration->addKey($table, 'serial'); } } foreach (array('glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) { if (!FieldExists($table, 'busID')) { $migration->addField($table, 'busID', 'string'); $migration->addKey($table, 'busID'); } } // Add key foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) { $migration->dropKey($table, 'item'); $migration->migrationOneTable($table); $migration->addKey($table, array('itemtype', 'items_id'), 'item'); } if (!FieldExists('glpi_devicegraphiccards', 'chipset')) { $migration->addField('glpi_devicegraphiccards', 'chipset', 'string'); $migration->addKey('glpi_devicegraphiccards', 'chipset'); } $migration->addField("glpi_suppliers_tickets", "use_notification", "bool"); $migration->addField("glpi_suppliers_tickets", "alternative_email", "string"); $migration->addField("glpi_problems_suppliers", "use_notification", "bool"); $migration->addField("glpi_problems_suppliers", "alternative_email", "string"); $migration->addField("glpi_changes_suppliers", "use_notification", "bool"); $migration->addField("glpi_changes_suppliers", "alternative_email", "string"); // Add field for locations $migration->addField("glpi_locations", "latitude", "string"); $migration->addField("glpi_locations", "longitude", "string"); $migration->addField("glpi_locations", "altitude", "string"); // Add fixed columns as variables : $ADDTODISPLAYPREF['CartridgeItem'] = array(9); $ADDTODISPLAYPREF['ConsumableItem'] = array(9); $ADDTODISPLAYPREF['ReservationItem'] = array(9); $migration->displayMessage(sprintf(__('Data migration - %s'), 'License validity')); // for licence validity if ($migration->addField("glpi_softwarelicenses", "is_valid", "bool", array("value" => 1))) { $migration->migrationOneTable("glpi_softwarelicenses"); // Force all entities if (!isset($_SESSION['glpishowallentities'])) { $_SESSION['glpishowallentities'] = 0; } $savesession = $_SESSION['glpishowallentities']; $_SESSION['glpishowallentities'] = 1; $queryl = "SELECT `id`, `number`\n FROM `glpi_softwarelicenses`"; foreach ($DB->request($queryl) as $datal) { if ($datal['number'] >= 0 && $datal['number'] < Computer_SoftwareLicense::countForLicense($datal['id'], -1)) { $queryl2 = "UPDATE `glpi_softwarelicenses`\n SET `is_valid` = 0\n WHERE `id` = '" . $datal['id'] . "'"; $DB->queryOrDie($queryl2, "0.85 update softwarelicense"); } } $_SESSION['glpishowallentities'] = $savesession; } if ($migration->addField("glpi_softwares", "is_valid", "bool", array("value" => 1))) { $migration->migrationOneTable("glpi_softwares"); $querys = "SELECT `glpi_softwares`.`id`\n FROM `glpi_softwares`\n LEFT JOIN `glpi_softwarelicenses`\n ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n WHERE `glpi_softwarelicenses`.`is_valid` = 0"; foreach ($DB->request($querys) as $datas) { $querys2 = "UPDATE `glpi_softwares`\n SET `is_valid` = 0\n WHERE `id` = '" . $datas['id'] . "'"; $DB->queryOrDie($querys2, "0.85 update software"); } } // Add condition to rules $migration->addField('glpi_rules', 'condition', 'integer'); $migration->addKey('glpi_rules', 'condition'); $migration->migrationOneTable('glpi_rules'); // Update condition for RuleTicket : only on add $query = "UPDATE `glpi_rules`\n SET `condition` = 1\n WHERE `sub_type` = 'RuleTicket'"; $DB->queryOrDie($query, "0.85 update condition for RuleTicket"); // Update ticket_status for helpdeks profiles $newcycle = array(1 => array(2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 2 => array(1 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 3 => array(1 => 0, 2 => 0, 4 => 0, 5 => 0, 6 => 0), 4 => array(1 => 0, 2 => 0, 3 => 0, 5 => 0, 6 => 0), 5 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0), 6 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0)); $query = "UPDATE `glpi_profiles`\n SET `ticket_status` = '" . exportArrayToDB($newcycle) . "'\n WHERE `interface` = 'helpdesk'"; $DB->queryOrDie($query, "0.85 update default life cycle for helpdesk"); //Add comment field to a virtualmachine $migration->addField('glpi_computervirtualmachines', 'comment', 'text'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'IP improvment')); // Ip search improve $migration->addField('glpi_ipaddresses', 'mainitems_id', 'integer'); $migration->addField('glpi_ipaddresses', 'mainitemtype', 'string', array('after' => 'mainitems_id')); $migration->migrationOneTable('glpi_ipaddresses'); $migration->addKey('glpi_ipaddresses', array('mainitemtype', 'mainitems_id', 'is_deleted'), 'mainitem'); $query_doc_i = "UPDATE `glpi_ipaddresses` as `ip`\n INNER JOIN `glpi_networknames` as `netname`\n ON (`ip`.`items_id` = `netname`.`id`\n AND `ip`.`itemtype` = 'NetworkName')\n INNER JOIN `glpi_networkports` as `netport`\n ON (`netname`.`items_id` = `netport`.`id`\n AND `netname`.`itemtype` = 'NetworkPort')\n SET `ip`.`mainitemtype` = `netport`.`itemtype`,\n `ip`.`mainitems_id` = `netport`.`items_id`"; $DB->queryOrDie($query_doc_i, "0.85 update mainitems fields of ipaddresses"); // Upgrade ticket bookmarks $query = "SELECT *\n FROM `glpi_bookmarks`\n WHERE `type` = '" . Bookmark::SEARCH . "'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $num = 0; $num2 = 0; $options = array(); parse_str($data["query"], $options); // Copy itemtype if not set if (!isset($options['itemtype'])) { $options['itemtype'] = $data['itemtype']; } // Move criteria if (isset($options['field']) && is_array($options['field'])) { $newkey = 0; foreach ($options['field'] as $key => $val) { $options['criteria'][$newkey]['field'] = $val; // other field if (isset($options['link'][$key])) { $options['criteria'][$newkey]['link'] = $options['link'][$key]; } if (isset($options['searchtype'][$key])) { $options['criteria'][$newkey]['searchtype'] = $options['searchtype'][$key]; } else { $options['criteria'][$newkey]['searchtype'] = 'contains'; } if (isset($options['contains'][$key])) { $options['criteria'][$newkey]['value'] = $options['contains'][$key]; } else { $options['criteria'][$newkey]['value'] = ''; } $newkey++; } unset($options['field']); unset($options['contains']); unset($options['searchtype']); unset($options['link']); } if (isset($options['glpisearchcount'])) { unset($options['glpisearchcount']); } if (isset($options['field2']) && is_array($options['field2'])) { $newkey = 0; foreach ($options['field2'] as $key => $val) { $options['metacriteria'][$newkey]['field'] = $val; // other field if (isset($options['itemtype2'][$key])) { $options['metacriteria'][$newkey]['itemtype'] = $options['itemtype2'][$key]; } if (isset($options['link2'][$newkey])) { $options['metacriteria'][$newkey]['link'] = $options['link2'][$key]; } if (isset($options['searchtype2'][$key])) { $options['metacriteria'][$newkey]['searchtype'] = $options['searchtype2'][$key]; } else { $options['metacriteria'][$newkey]['searchtype'] = 'contains'; } if (isset($options['contains2'][$key])) { $options['metacriteria'][$newkey]['value'] = $options['contains2'][$key]; } else { $options['metacriteria'][$newkey]['value'] = ''; } $newkey++; } unset($options['field2']); unset($options['contains2']); unset($options['searchtype2']); unset($options['link2']); unset($options['itemtype2']); } if (isset($options['glpisearchcount2'])) { unset($options['glpisearchcount2']); } $query2 = "UPDATE `glpi_bookmarks`\n SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query2, "0.85 update bookmarks for reorg search"); } } } // ************ Keep it at the end ************** //TRANS: %s is the table or item to migrate $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences')); // Clean display prefs // Notepad $query = "UPDATE `glpi_displaypreferences`\n SET `num` = 90\n WHERE `itemtype` = 'Entity'\n AND `num` = 28"; $DB->query($query); $query = "UPDATE `glpi_displaypreferences`\n SET `num` = 200\n WHERE `num` = 90"; $DB->query($query); $migration->updateDisplayPrefs($ADDTODISPLAYPREF, $DELFROMDISPLAYPREF); // must always be at the end $migration->executeMigration(); return $updateresult; }
You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief * @since version 0.84 */ include '../inc/includes.php'; if (isset($_POST['itemtype']) && isset($_POST["unlock"])) { $itemtype = $_POST['itemtype']; $source_item = new $itemtype(); if ($source_item->canCreate()) { $source_item->check($_POST['id'], UPDATE); $actions = array("Computer_Item", "Computer_SoftwareLicense", "Computer_SoftwareVersion", "ComputerDisk", "ComputerVirtualMachine", "NetworkPort", "NetworkName", "IPAddress"); $devices = Item_Devices::getDeviceTypes(); $actions = array_merge($actions, array_values($devices)); foreach ($actions as $type) { if (isset($_POST[$type]) && count($_POST[$type])) { $item = new $type(); foreach ($_POST[$type] as $key => $val) { //Force unlock $item->restore(array('id' => $key)); } } } } } //Execute hook to unlock fields managed by a plugin, if needed Plugin::doHookFunction('unlock_fields', $_POST); Html::back();
function cleanDBonPurge() { global $DB; $ci = new Computer_Item(); $ci->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ip = new Item_Problem(); $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ci = new Change_Item(); $ci->cleanDBonItemDelete(__CLASS__, $this->fields['id']); $ip = new Item_Project(); $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']); Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'], !empty($this->input['keep_devices'])); }
/** * Get all the types that can have an infocom * * @since version 0.85 * * @return array of the itemtypes **/ static function getItemtypesThatCanHave() { global $CFG_GLPI; return array_merge($CFG_GLPI['infocom_types'], Item_Devices::getDeviceTypes()); }
/** * @since version 0.85 **/ static function getSpecificities($specif = '') { return array('capacity' => array('long name' => sprintf(__('%1$s (%2$s)'), __('Capacity'), __('Mio')), 'short name' => __('Capacity'), 'size' => 10, 'id' => 20), 'serial' => parent::getSpecificities('serial'), 'busID' => parent::getSpecificities('busID')); }
/** * Return the instance fields of itemtype identified by id * * @since version 9.1 * * @param string $itemtype itemtype (class) of object * @param integer $id identifier of object * @param array $params array with theses options : * - 'expand_dropdowns' : show dropdown's names instead of id. default: false. Optionnal * - 'get_hateoas' : show relation of current item in a links attribute. default: true. Optionnal * - 'with_components' : Only for [Computer, NetworkEquipment, Peripheral, Phone, Printer], Optionnal. * - 'with_disks' : Only for Computer, retrieve the associated filesystems. Optionnal. * - 'with_softwares' : Only for Computer, retrieve the associated softwares installations. Optionnal. * - 'with_connections' : Only for Computer, retrieve the associated direct connections (like peripherals and printers) .Optionnal. * - 'with_networkports' :Retrieve all network connections and advanced network informations. Optionnal. * - 'with_infocoms' : Retrieve financial and administrative informations. Optionnal. * - 'with_contracts' : Retrieve associated contracts. Optionnal. * - 'with_documents' : Retrieve associated external documents. Optionnal. * - 'with_tickets' : Retrieve associated itil tickets. Optionnal. * - 'with_problems' : Retrieve associated itil problems. Optionnal. * - 'with_changes' : Retrieve associated itil changes. Optionnal. * - 'with_notes' : Retrieve Notes (if exists, not all itemtypes have notes). Optionnal. * - 'with_logs' : Retrieve historical. Optionnal. * * @return array fields of found object */ protected function getItem($itemtype, $id, $params = array()) { global $CFG_GLPI, $DB; $this->initEndpoint(); // default params $default = array('expand_dropdowns' => false, 'get_hateoas' => true, 'with_components' => false, 'with_disks' => false, 'with_softwares' => false, 'with_connections' => false, 'with_networkports' => false, 'with_infocoms' => false, 'with_contracts' => false, 'with_documents' => false, 'with_tickets' => false, 'with_problems' => false, 'with_changes' => false, 'with_notes' => false, 'with_logs' => false); $params = array_merge($default, $params); $item = new $itemtype(); if (!$item->getFromDB($id)) { return $this->messageNotfoundError(); } if (!$item->can($id, READ)) { return $this->messageRightError(); } $fields = $item->fields; // retrieve devices if (isset($params['with_devices']) && $params['with_devices'] && in_array($itemtype, Item_Devices::getConcernedItems())) { $all_devices = array(); foreach (Item_Devices::getItemAffinities($item->getType()) as $device_type) { $found_devices = getAllDatasFromTable($device_type::getTable(), "`items_id` = '" . $item->getID() . "'\n AND `itemtype` = '" . $item->getType() . "'\n AND `is_deleted` = '0'", true); foreach ($found_devices as $devices_id => &$device) { unset($device['items_id']); unset($device['itemtype']); unset($device['is_deleted']); } if (!empty($found_devices)) { $all_devices[$device_type] = $found_devices; } } $fields['_devices'] = $all_devices; } // retrieve computer disks if (isset($params['with_disks']) && $params['with_disks'] && $itemtype == "Computer") { // build query to retrive filesystems $query = "SELECT `glpi_filesystems`.`name` AS fsname,\n `glpi_computerdisks`.*\n FROM `glpi_computerdisks`\n LEFT JOIN `glpi_filesystems`\n ON (`glpi_computerdisks`.`filesystems_id` = `glpi_filesystems`.`id`)\n WHERE `computers_id` = '{$id}'\n AND `is_deleted` = '0'"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { unset($data['computers_id']); unset($data['is_deleted']); $fields['_disks'][] = array('name' => $data); } } } // retrieve computer softwares if (isset($params['with_softwares']) && $params['with_softwares'] && $itemtype == "Computer") { $fields['_softwares'] = array(); if (!Software::canView()) { $fields['_softwares'] = self::arrayRightError(); } else { $query = "SELECT `glpi_softwares`.`softwarecategories_id`,\n `glpi_softwares`.`id` AS softwares_id,\n `glpi_softwareversions`.`id` AS softwareversions_id,\n `glpi_computers_softwareversions`.`is_dynamic`,\n `glpi_softwareversions`.`states_id`,\n `glpi_softwares`.`is_valid`\n FROM `glpi_computers_softwareversions`\n LEFT JOIN `glpi_softwareversions`\n ON (`glpi_computers_softwareversions`.`softwareversions_id`\n = `glpi_softwareversions`.`id`)\n LEFT JOIN `glpi_softwares`\n ON (`glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`)\n WHERE `glpi_computers_softwareversions`.`computers_id` = '{$id}'\n AND `glpi_computers_softwareversions`.`is_deleted` = '0'\n ORDER BY `glpi_softwares`.`name`, `glpi_softwareversions`.`name`"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_softwares'][] = $data; } } } } // retrieve item connections if (isset($params['with_connections']) && $params['with_connections'] && $itemtype == "Computer") { $fields['_connections'] = array(); foreach ($CFG_GLPI["directconnect_types"] as $connect_type) { $connect_item = new $connect_type(); if ($connect_item->canView()) { $query = "SELECT `glpi_computers_items`.`id` AS assoc_id,\n `glpi_computers_items`.`computers_id` AS assoc_computers_id,\n `glpi_computers_items`.`itemtype` AS assoc_itemtype,\n `glpi_computers_items`.`items_id` AS assoc_items_id,\n `glpi_computers_items`.`is_dynamic` AS assoc_is_dynamic,\n " . getTableForItemType($connect_type) . ".*\n FROM `glpi_computers_items`\n LEFT JOIN `" . getTableForItemType($connect_type) . "`\n ON (`" . getTableForItemType($connect_type) . "`.`id`\n = `glpi_computers_items`.`items_id`)\n WHERE `computers_id` = '{$id}'\n AND `itemtype` = '" . $connect_type . "'\n AND `glpi_computers_items`.`is_deleted` = '0'"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_connections'][$connect_type][] = $data; } } } } } // retrieve item networkports if (isset($params['with_networkports']) && $params['with_networkports']) { $fields['_networkports'] = array(); if (!NetworkEquipment::canView()) { $fields['_networkports'] = self::arrayRightError(); } else { foreach (NetworkPort::getNetworkPortInstantiations() as $networkport_type) { $query = "SELECT\n netp.`entities_id`,\n netp.`is_recursive`,\n netp.`logical_number`,\n netp.`name`,\n netp.`mac`,\n netp.`comment`,\n netp.`is_dynamic`,\n netp_subtable.*\n FROM glpi_networkports AS netp\n LEFT JOIN " . $networkport_type::getTable() . " AS netp_subtable\n ON netp_subtable.`networkports_id` = netp.`id`\n WHERE netp.`instantiation_type` = '{$networkport_type}'\n AND netp.`items_id` = '{$id}'\n AND netp.`itemtype` = '{$itemtype}'\n AND netp.`is_deleted` = '0'"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_networkports'][$networkport_type][] = $data; } } } } } // retrieve item infocoms if (isset($params['with_infocoms']) && $params['with_infocoms']) { $fields['_infocoms'] = array(); if (!Infocom::canView()) { $fields['_infocoms'] = self::arrayRightError(); } else { $ic = new Infocom(); if ($ic->getFromDBforDevice($itemtype, $id)) { $fields['_infocoms'] = $ic->fields; } } } // retrieve item contracts if (isset($params['with_contracts']) && $params['with_contracts']) { $fields['_contracts'] = array(); if (!Contract::canView()) { $fields['_contracts'] = self::arrayRightError(); } else { $query = "SELECT `glpi_contracts_items`.*\n FROM `glpi_contracts_items`,\n `glpi_contracts`\n LEFT JOIN `glpi_entities` ON (`glpi_contracts`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_contracts`.`id`=`glpi_contracts_items`.`contracts_id`\n AND `glpi_contracts_items`.`items_id` = '{$id}'\n AND `glpi_contracts_items`.`itemtype` = '{$itemtype}'" . getEntitiesRestrictRequest(" AND", "glpi_contracts", '', '', true) . "\n ORDER BY `glpi_contracts`.`name`"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_contracts'][] = $data; } } } } // retrieve item contracts if (isset($params['with_documents']) && $params['with_documents']) { $fields['_documents'] = array(); if (!$itemtype != 'Ticket' && $itemtype != 'KnowbaseItem' && $itemtype != 'Reminder' && !Document::canView()) { $fields['_documents'] = self::arrayRightError(); } else { $query = "SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_documents_items`.`date_mod` AS assocdate,\n `glpi_entities`.`id` AS entityID,\n `glpi_entities`.`completename` AS entity,\n `glpi_documentcategories`.`completename` AS headings,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n LEFT JOIN `glpi_documentcategories`\n ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)\n WHERE `glpi_documents_items`.`items_id` = '{$id}'\n AND `glpi_documents_items`.`itemtype` = '{$itemtype}' "; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_documents'][] = $data; } } } } // retrieve item tickets if (isset($params['with_tickets']) && $params['with_tickets']) { $fields['_tickets'] = array(); if (!Ticket::canView()) { $fields['_tickets'] = self::arrayRightError(); } else { $query = "SELECT " . Ticket::getCommonSelect() . "\n FROM `glpi_tickets` " . Ticket::getCommonLeftJoin() . "\n WHERE `glpi_items_tickets`.`items_id` = '{$id}'\n AND `glpi_items_tickets`.`itemtype` = '{$itemtype}' " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n ORDER BY `glpi_tickets`.`date_mod` DESC"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_tickets'][] = $data; } } } } // retrieve item problems if (isset($params['with_problems']) && $params['with_problems']) { $fields['_problems'] = array(); if (!Problem::canView()) { $fields['_problems'] = self::arrayRightError(); } else { $query = "SELECT " . Problem::getCommonSelect() . "\n FROM `glpi_problems`\n LEFT JOIN `glpi_items_problems`\n ON (`glpi_problems`.`id` = `glpi_items_problems`.`problems_id`) " . Problem::getCommonLeftJoin() . "\n WHERE `items_id` = '{$id}'\n AND `itemtype` = '{$itemtype}' " . getEntitiesRestrictRequest("AND", "glpi_problems") . "\n ORDER BY `glpi_problems`.`date_mod` DESC"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_problems'][] = $data; } } } } // retrieve item changes if (isset($params['with_changes']) && $params['with_changes']) { $fields['_changes'] = array(); if (!Change::canView()) { $fields['_changes'] = self::arrayRightError(); } else { $query = "SELECT " . Change::getCommonSelect() . "\n FROM `glpi_changes`\n LEFT JOIN `glpi_changes_items`\n ON (`glpi_changes`.`id` = `glpi_changes_items`.`problems_id`) " . Change::getCommonLeftJoin() . "\n WHERE `items_id` = '{$id}'\n AND `itemtype` = '{$itemtype}' " . getEntitiesRestrictRequest("AND", "glpi_changes") . "\n ORDER BY `glpi_changes`.`date_mod` DESC"; if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $fields['_changes'][] = $data; } } } } // retrieve item notes if (isset($params['with_notes']) && $params['with_notes']) { $fields['_notes'] = array(); if (!Session::haveRight($itemtype::$rightname, READNOTE)) { $fields['_notes'] = self::arrayRightError(); } else { $fields['_notes'] = Notepad::getAllForItem($itemtype); } } // retrieve item logs if (isset($params['with_logs']) && $params['with_logs']) { $fields['_logs'] = array(); if (!Session::haveRight($itemtype::$rightname, READNOTE)) { $fields['_logs'] = self::arrayRightError(); } else { $fields['_logs'] = getAllDatasFromTable("glpi_logs", "`items_id` = '" . $item->getID() . "'\n AND `itemtype` = '" . $item->getType() . "'"); } } // expand dropdown (retrieve name of dropdowns) and get hateoas from foreign keys $fields = self::parseDropdowns($fields, $params); // get hateoas from children if ($params['get_hateoas']) { $hclasses = self::getHatoasClasses($itemtype); foreach ($hclasses as $hclass) { $fields['links'][] = array('rel' => $hclass, 'href' => self::$api_url . "/{$itemtype}/" . $item->getID() . "/{$hclass}/"); } } return $fields; }