function getSqlSubRequest($itemtype, $loc, $obj) { $table = getTableForItemType($itemtype); $models_id = getForeignKeyFieldForTable(getTableForItemType($itemtype . 'Model')); $types_id = getForeignKeyFieldForTable(getTableForItemType($itemtype . 'Type')); $fields = array('name' => 'name', 'serial' => 'serial', 'otherserial' => 'otherserial', $models_id => 'models_id', $types_id => 'types_id'); $query_where = "SELECT '{$itemtype}' AS itemtype,\n `{$table}`.`id` AS items_id,\n `{$table}`.`locations_id`"; foreach ($fields as $field => $alias) { if ($obj->isField($field)) { $query_where .= ", `{$table}`.`{$field}` AS {$alias}"; } else { $query_where .= ", '' AS {$alias}"; } } $query_where .= " FROM `{$table}` "; if ($obj->isEntityAssign()) { $query_where .= getEntitiesRestrictRequest('WHERE', "{$table}"); } else { $query_where .= 'WHERE 1'; } if ($obj->maybeTemplate()) { $query_where .= " AND `is_template`='0'"; } if ($obj->maybeDeleted()) { $query_where .= " AND `is_deleted`='0'"; } $query_where .= $loc->getSqlCriteriasRestriction(); return $query_where; }
static function postClone(NotificationTemplate $clone, $oldid) { global $DB; $trad = new NotificationTemplateTranslation(); $fkey = getForeignKeyFieldForTable($clone->getTable()); $crit = array($fkey => $oldid); foreach ($DB->request($trad->getTable(), $crit) as $data) { unset($data['id']); $data[$fkey] = $clone->getID(); $trad->add(Toolbox::addslashes_deep($data)); } }
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(); }
/** * @param $values * @param $add (true by default) * @param $rights array **/ function processAfterInsertOrUpdate($values, $add = true, $rights = array()) { if (isset($values['Computer']['id'])) { $class = "Item_" . get_parent_class($this); $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); if (!countElementsInTable($item->getTable(), "`{$foreign}`='" . $values[get_parent_class($this)]['id'] . "'\n AND `itemtype`='Computer'\n AND `items_id`='" . $values['Computer']['id'] . "'")) { $tmp[$foreign] = $values[get_parent_class($this)]['id']; $tmp['items_id'] = $values['Computer']['id']; $tmp['itemtype'] = 'Computer'; $item->add($tmp); } } }
static function postClone(Rule $clone, $oldid) { global $DB; $fkey = getForeignKeyFieldForTable($clone->getTable()); $crit = array($fkey => $oldid); $criteria = new RuleCriteria(); foreach ($DB->request($criteria->getTable(), $crit) as $data) { unset($data['id']); $data[$fkey] = $clone->getID(); $criteria->add(Toolbox::addslashes_deep($data)); } $action = new RuleAction(); foreach ($DB->request($action->getTable(), $crit) as $data) { unset($data['id']); $data[$fkey] = $clone->getID(); $action->add(Toolbox::addslashes_deep($data)); } }
function dropdown_getTypeName($class, $nb = 0) { global $GO_FIELDS; $fk = getForeignKeyFieldForTable(getTableForItemType($class)); $instance = new $class(); $options = PluginGenericobjectField::getFieldOptions($fk, $instance->linked_itemtype); $dropdown_type = isset($options['dropdown_type']) ? $options['dropdown_type'] : null; $label = $options['name']; if (!is_null($dropdown_type) and $dropdown_type === 'isolated') { $linked_itemtype_object = new $instance->linked_itemtype(); $label .= " (" . __($linked_itemtype_object::getTypeName(), 'genericobject') . ")"; } if ($label != '') { return $label; } else { return $class; } }
/** * @see plugins/datainjection/inc/PluginDatainjectionInjectionInterface::getOptions() **/ function getOptions($primary_type = '') { $tab = Search::getOptions(get_parent_class($this)); $tab[4]['checktype'] = 'mac'; //To manage vlans : relies on a CommonDBRelation object ! $tab[51]['name'] = sprintf(__('%1$s: %2$s'), __('Connected to'), __('Device name')); $tab[51]['field'] = 'netname'; $tab[51]['table'] = getTableForItemType('NetworkPort'); $tab[51]['linkfield'] = "netname"; $tab[51]['injectable'] = true; $tab[51]['displaytype'] = 'text'; $tab[51]['checktype'] = 'text'; $tab[52]['name'] = sprintf(__('%1$s: %2$s'), __('Connected to'), __('Port number')); $tab[52]['field'] = 'netport'; $tab[52]['table'] = getTableForItemType('NetworkPort'); $tab[52]['linkfield'] = "netport"; $tab[52]['injectable'] = true; $tab[52]['displaytype'] = 'text'; $tab[52]['checktype'] = 'text'; $tab[53]['name'] = sprintf(__('%1$s: %2$s'), __('Connected to'), __('Port MAC address', 'datainjection')); $tab[53]['field'] = 'netmac'; $tab[53]['table'] = getTableForItemType('NetworkPort'); $tab[53]['linkfield'] = "netmac"; $tab[53]['injectable'] = true; $tab[53]['displaytype'] = 'text'; $tab[53]['checktype'] = 'text'; //To manage vlans : relies on a CommonDBRelation object ! $tab[100]['name'] = __('VLAN'); $tab[100]['field'] = 'name'; $tab[100]['table'] = getTableForItemType('Vlan'); $tab[100]['linkfield'] = getForeignKeyFieldForTable($tab[100]['table']); $tab[100]['displaytype'] = 'relation'; $tab[100]['relationclass'] = 'NetworkPort_Vlan'; $tab[100]['storevaluein'] = $tab[100]['linkfield']; $blacklist = PluginDatainjectionCommonInjectionLib::getBlacklistedOptions(get_parent_class($this)); $notimportable = array(20, 21); $options['ignore_fields'] = array_merge($blacklist, $notimportable); $options['displaytype'] = array("dropdown" => array(9), "multiline_text" => array(16), "instantiation_type" => array(87)); return PluginDatainjectionCommonInjectionLib::addToSearchOptions($tab, $options, $this); }
/** * @see plugins/datainjection/inc/PluginDatainjectionInjectionInterface::getOptions() **/ function getOptions($primary_type = '') { $tab = Search::getOptions(get_parent_class($this)); //Specific to location $tab[1]['linkfield'] = 'name'; $tab[3]['linkfield'] = 'locations_id'; //Manage password $tab[4]['table'] = $this->getTable(); $tab[4]['field'] = 'password'; $tab[4]['linkfield'] = 'password'; $tab[4]['name'] = __('Password'); $tab[4]['displaytype'] = 'password'; $tab[5]['displaytype'] = 'text'; //To manage groups : relies on a CommonDBRelation object ! $tab[100]['name'] = __('Group'); $tab[100]['field'] = 'name'; $tab[100]['table'] = getTableForItemType('Group'); $tab[100]['linkfield'] = getForeignKeyFieldForTable($tab[100]['table']); $tab[100]['displaytype'] = 'relation'; $tab[100]['relationclass'] = 'Group_User'; $tab[100]['relationfield'] = $tab[100]['linkfield']; //To manage groups : relies on a CommonDBRelation object ! $tab[101]['name'] = __('Profile'); $tab[101]['field'] = 'name'; $tab[101]['table'] = getTableForItemType('Profile'); $tab[101]['linkfield'] = getForeignKeyFieldForTable($tab[101]['table']); $tab[101]['displaytype'] = 'relation'; $tab[101]['relationclass'] = 'Profile_User'; $tab[101]['relationfield'] = $tab[101]['linkfield']; //Remove some options because some fields cannot be imported $blacklist = PluginDatainjectionCommonInjectionLib::getBlacklistedOptions(get_parent_class($this)); $notimportable = array(13, 14, 15, 17, 20, 23, 30, 31, 60, 61, 77, 91, 92, 93); $options['ignore_fields'] = array_merge($blacklist, $notimportable); //Add displaytype value $options['displaytype'] = array("dropdown" => array(3, 79, 81, 82), "multiline_text" => array(16), "bool" => array(8), "password" => array(4)); return PluginDatainjectionCommonInjectionLib::addToSearchOptions($tab, $options, $this); }
/** * Get the SEARCH_OPTION array * * @param $itemtype * @param $withplugins boolean get search options from plugins (true by default) * * @return the reference to array of search options for the given item type **/ static function &getOptions($itemtype, $withplugins = true) { global $CFG_GLPI; static $search = array(); $item = NULL; if (!isset($search[$itemtype])) { // standard type first switch ($itemtype) { case 'Internet': $search[$itemtype]['common'] = __('Characteristics'); $search[$itemtype][1]['table'] = 'networkport_types'; $search[$itemtype][1]['field'] = 'name'; $search[$itemtype][1]['name'] = __('Name'); $search[$itemtype][1]['datatype'] = 'itemlink'; $search[$itemtype][1]['searchtype'] = 'contains'; $search[$itemtype][2]['table'] = 'networkport_types'; $search[$itemtype][2]['field'] = 'id'; $search[$itemtype][2]['name'] = __('ID'); $search[$itemtype][2]['searchtype'] = 'contains'; $search[$itemtype][31]['table'] = 'glpi_states'; $search[$itemtype][31]['field'] = 'completename'; $search[$itemtype][31]['name'] = __('Status'); $search[$itemtype] += NetworkPort::getSearchOptionsToAdd('networkport_types'); break; case 'AllAssets': $search[$itemtype]['common'] = __('Characteristics'); $search[$itemtype][1]['table'] = 'asset_types'; $search[$itemtype][1]['field'] = 'name'; $search[$itemtype][1]['name'] = __('Name'); $search[$itemtype][1]['datatype'] = 'itemlink'; $search[$itemtype][1]['searchtype'] = 'contains'; $search[$itemtype][2]['table'] = 'asset_types'; $search[$itemtype][2]['field'] = 'id'; $search[$itemtype][2]['name'] = __('ID'); $search[$itemtype][2]['searchtype'] = 'contains'; $search[$itemtype][31]['table'] = 'glpi_states'; $search[$itemtype][31]['field'] = 'completename'; $search[$itemtype][31]['name'] = __('Status'); $search[$itemtype] += Location::getSearchOptionsToAdd(); $search[$itemtype][5]['table'] = 'asset_types'; $search[$itemtype][5]['field'] = 'serial'; $search[$itemtype][5]['name'] = __('Serial number'); $search[$itemtype][6]['table'] = 'asset_types'; $search[$itemtype][6]['field'] = 'otherserial'; $search[$itemtype][6]['name'] = __('Inventory number'); $search[$itemtype][16]['table'] = 'asset_types'; $search[$itemtype][16]['field'] = 'comment'; $search[$itemtype][16]['name'] = __('Comments'); $search[$itemtype][16]['datatype'] = 'text'; $search[$itemtype][70]['table'] = 'glpi_users'; $search[$itemtype][70]['field'] = 'name'; $search[$itemtype][70]['name'] = __('User'); $search[$itemtype][7]['table'] = 'asset_types'; $search[$itemtype][7]['field'] = 'contact'; $search[$itemtype][7]['name'] = __('Alternate username'); $search[$itemtype][7]['datatype'] = 'string'; $search[$itemtype][8]['table'] = 'asset_types'; $search[$itemtype][8]['field'] = 'contact_num'; $search[$itemtype][8]['name'] = __('Alternate username number'); $search[$itemtype][8]['datatype'] = 'string'; $search[$itemtype][71]['table'] = 'glpi_groups'; $search[$itemtype][71]['field'] = 'completename'; $search[$itemtype][71]['name'] = __('Group'); $search[$itemtype][19]['table'] = 'asset_types'; $search[$itemtype][19]['field'] = 'date_mod'; $search[$itemtype][19]['name'] = __('Last update'); $search[$itemtype][19]['datatype'] = 'datetime'; $search[$itemtype][19]['massiveaction'] = false; $search[$itemtype][23]['table'] = 'glpi_manufacturers'; $search[$itemtype][23]['field'] = 'name'; $search[$itemtype][23]['name'] = __('Manufacturer'); $search[$itemtype][24]['table'] = 'glpi_users'; $search[$itemtype][24]['field'] = 'name'; $search[$itemtype][24]['linkfield'] = 'users_id_tech'; $search[$itemtype][24]['name'] = __('Technician in charge of the hardware'); $search[$itemtype][80]['table'] = 'glpi_entities'; $search[$itemtype][80]['field'] = 'completename'; $search[$itemtype][80]['name'] = __('Entity'); break; default: if ($item = getItemForItemtype($itemtype)) { $search[$itemtype] = $item->getSearchOptions(); } break; } if (Session::getLoginUserID() && in_array($itemtype, $CFG_GLPI["ticket_types"])) { $search[$itemtype]['tracking'] = __('Assistance'); $search[$itemtype][60]['table'] = 'glpi_tickets'; $search[$itemtype][60]['field'] = 'id'; $search[$itemtype][60]['datatype'] = 'count'; $search[$itemtype][60]['name'] = _x('quantity', 'Number of tickets'); $search[$itemtype][60]['forcegroupby'] = true; $search[$itemtype][60]['usehaving'] = true; $search[$itemtype][60]['massiveaction'] = false; $search[$itemtype][60]['joinparams'] = array('beforejoin' => array('table' => 'glpi_items_tickets', 'joinparams' => array('jointype' => 'itemtype_item')), 'condition' => getEntitiesRestrictRequest('AND', 'NEWTABLE')); $search[$itemtype][140]['table'] = 'glpi_problems'; $search[$itemtype][140]['field'] = 'id'; $search[$itemtype][140]['datatype'] = 'count'; $search[$itemtype][140]['name'] = _x('quantity', 'Number of problems'); $search[$itemtype][140]['forcegroupby'] = true; $search[$itemtype][140]['usehaving'] = true; $search[$itemtype][140]['massiveaction'] = false; $search[$itemtype][140]['joinparams'] = array('beforejoin' => array('table' => 'glpi_items_problems', 'joinparams' => array('jointype' => 'itemtype_item')), 'condition' => getEntitiesRestrictRequest('AND', 'NEWTABLE')); } if (in_array($itemtype, $CFG_GLPI["networkport_types"]) || $itemtype == 'AllAssets') { $search[$itemtype] += NetworkPort::getSearchOptionsToAdd($itemtype); } if (in_array($itemtype, $CFG_GLPI["contract_types"]) || $itemtype == 'AllAssets') { $search[$itemtype] += Contract::getSearchOptionsToAdd(); } if (Document::canApplyOn($itemtype) || $itemtype == 'AllAssets') { $search[$itemtype] += Document::getSearchOptionsToAdd(); } if (InfoCom::canApplyOn($itemtype) || $itemtype == 'AllAssets') { $search[$itemtype] += Infocom::getSearchOptionsToAdd($itemtype); } if (in_array($itemtype, $CFG_GLPI["link_types"])) { $search[$itemtype]['link'] = _n('External link', 'External links', Session::getPluralNumber()); $search[$itemtype] += Link::getSearchOptionsToAdd($itemtype); } if ($withplugins) { // Search options added by plugins $plugsearch = Plugin::getAddSearchOptions($itemtype); if (count($plugsearch)) { $search[$itemtype] += array('plugins' => _n('Plugin', 'Plugins', Session::getPluralNumber())); $search[$itemtype] += $plugsearch; } } // Complete linkfield if not define if (is_null($item)) { // Special union type $itemtable = $CFG_GLPI['union_search_type'][$itemtype]; } else { if ($item = getItemForItemtype($itemtype)) { $itemtable = $item->getTable(); } } foreach ($search[$itemtype] as $key => $val) { if (!is_array($val)) { // skip sub-menu continue; } // Compatibility before 0.80 : Force massive action to false if linkfield is empty : if (isset($val['linkfield']) && empty($val['linkfield'])) { $search[$itemtype][$key]['massiveaction'] = false; } // Set default linkfield if (!isset($val['linkfield']) || empty($val['linkfield'])) { if (strcmp($itemtable, $val['table']) == 0 && (!isset($val['joinparams']) || count($val['joinparams']) == 0)) { $search[$itemtype][$key]['linkfield'] = $val['field']; } else { $search[$itemtype][$key]['linkfield'] = getForeignKeyFieldForTable($val['table']); } } // Set default datatype // if (!isset($val['datatype']) || empty($val['datatype'])) { // if ((strcmp($itemtable,$val['table']) != 0) // && ($val['field'] == 'name' || $val['field'] == 'completename')) { // $search[$itemtype][$key]['datatype'] = 'dropdown'; // } else { // $search[$itemtype][$key]['datatype'] = 'string'; // } // } // Add default joinparams if (!isset($val['joinparams'])) { $search[$itemtype][$key]['joinparams'] = array(); } } } return $search[$itemtype]; }
/** * Add a new dropdown table * @param table the table name * @param entity_assign can the dropdown be assigned to an entity * @param recursive can the dropdown be recursive * @param tree can the dropdown be a tree dropdown * @return nothing */ public static function addDropdownTable($table, $options = array()) { global $DB; $params['entities_id'] = false; $params['is_recursive'] = false; $params['is_tree'] = false; foreach ($options as $key => $value) { $params[$key] = $value; } if (!TableExists($table)) { $query = "CREATE TABLE IF NOT EXISTS `{$table}` (\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->query($query); } if ($params['entities_id']) { $query = "ALTER TABLE `{$table}` ADD `entities_id` INT(11) NOT NULL DEFAULT '0'"; $DB->query($query); if ($params['is_recursive']) { $query = "ALTER TABLE `{$table}` " . "ADD `is_recursive` TINYINT(1) NOT NULL DEFAULT '0' AFTER `entities_id`"; $DB->query($query); } } if ($params['is_tree']) { $fk = getForeignKeyFieldForTable($table); $query = "ALTER TABLE `{$table}` ADD `completename` text COLLATE utf8_unicode_ci,\n ADD `{$fk}` int(11) NOT NULL DEFAULT '0',\n ADD `level` int(11) NOT NULL DEFAULT '0',\n ADD `ancestors_cache` longtext COLLATE utf8_unicode_ci,\n ADD `sons_cache` longtext COLLATE utf8_unicode_ci"; $DB->query($query); } }
/** * Update from 0.72.3 to 0.78 * * @return bool for success (will die for most error) **/ function update0723to078() { global $DB, $migration; $updateresult = true; //TRANS: %s is the number of new version $migration->displayTitle(sprintf(__('Update to %s'), '0.78')); $migration->setVersion('0.78'); //TRANS: %s is 'Clean DB : rename tables' $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB : rename tables')); $changes = array(); $glpi_tables = array('glpi_alerts' => 'glpi_alerts', 'glpi_auth_ldap' => 'glpi_authldaps', 'glpi_auth_ldap_replicate' => 'glpi_authldapreplicates', 'glpi_auth_mail' => 'glpi_authmails', 'glpi_dropdown_auto_update' => 'glpi_autoupdatesystems', 'glpi_bookmark' => 'glpi_bookmarks', 'glpi_display_default' => 'glpi_bookmarks_users', 'glpi_dropdown_budget' => 'glpi_budgets', 'glpi_cartridges' => 'glpi_cartridges', 'glpi_cartridges_type' => 'glpi_cartridgeitems', 'glpi_cartridges_assoc' => 'glpi_cartridges_printermodels', 'glpi_dropdown_cartridge_type' => 'glpi_cartridgeitemtypes', 'glpi_computers' => 'glpi_computers', 'glpi_computerdisks' => 'glpi_computerdisks', 'glpi_dropdown_model' => 'glpi_computermodels', 'glpi_type_computers' => 'glpi_computertypes', 'glpi_connect_wire' => 'glpi_computers_items', 'glpi_inst_software' => 'glpi_computers_softwareversions', 'glpi_config' => 'glpi_configs', 'glpi_consumables' => 'glpi_consumables', 'glpi_consumables_type' => 'glpi_consumableitems', 'glpi_dropdown_consumable_type' => 'glpi_consumableitemtypes', 'glpi_contact_enterprise' => 'glpi_contacts_suppliers', 'glpi_contacts' => 'glpi_contacts', 'glpi_dropdown_contact_type' => 'glpi_contacttypes', 'glpi_contracts' => 'glpi_contracts', 'glpi_dropdown_contract_type' => 'glpi_contracttypes', 'glpi_contract_device' => 'glpi_contracts_items', 'glpi_contract_enterprise' => 'glpi_contracts_suppliers', 'glpi_device_case' => 'glpi_devicecases', 'glpi_dropdown_case_type' => 'glpi_devicecasetypes', 'glpi_device_control' => 'glpi_devicecontrols', 'glpi_device_drive' => 'glpi_devicedrives', 'glpi_device_gfxcard' => 'glpi_devicegraphiccards', 'glpi_device_hdd' => 'glpi_deviceharddrives', 'glpi_device_iface' => 'glpi_devicenetworkcards', 'glpi_device_moboard' => 'glpi_devicemotherboards', 'glpi_device_pci' => 'glpi_devicepcis', 'glpi_device_power' => 'glpi_devicepowersupplies', 'glpi_device_processor' => 'glpi_deviceprocessors', 'glpi_device_ram' => 'glpi_devicememories', 'glpi_dropdown_ram_type' => 'glpi_devicememorytypes', 'glpi_device_sndcard' => 'glpi_devicesoundcards', 'glpi_display' => 'glpi_displaypreferences', 'glpi_docs' => 'glpi_documents', 'glpi_dropdown_rubdocs' => 'glpi_documentcategories', 'glpi_type_docs' => 'glpi_documenttypes', 'glpi_doc_device' => 'glpi_documents_items', 'glpi_dropdown_domain' => 'glpi_domains', 'glpi_entities' => 'glpi_entities', 'glpi_entities_data' => 'glpi_entitydatas', 'glpi_event_log' => 'glpi_events', 'glpi_dropdown_filesystems' => 'glpi_filesystems', 'glpi_groups' => 'glpi_groups', 'glpi_users_groups' => 'glpi_groups_users', 'glpi_infocoms' => 'glpi_infocoms', 'glpi_dropdown_interface' => 'glpi_interfacetypes', 'glpi_kbitems' => 'glpi_knowbaseitems', 'glpi_dropdown_kbcategories' => 'glpi_knowbaseitemcategories', 'glpi_links' => 'glpi_links', 'glpi_links_device' => 'glpi_links_itemtypes', 'glpi_dropdown_locations' => 'glpi_locations', 'glpi_history' => 'glpi_logs', 'glpi_mailgate' => 'glpi_mailcollectors', 'glpi_mailing' => 'glpi_mailingsettings', 'glpi_dropdown_manufacturer' => 'glpi_manufacturers', 'glpi_monitors' => 'glpi_monitors', 'glpi_dropdown_model_monitors' => 'glpi_monitormodels', 'glpi_type_monitors' => 'glpi_monitortypes', 'glpi_dropdown_netpoint' => 'glpi_netpoints', 'glpi_networking' => 'glpi_networkequipments', 'glpi_dropdown_firmware' => 'glpi_networkequipmentfirmwares', 'glpi_dropdown_model_networking' => 'glpi_networkequipmentmodels', 'glpi_type_networking' => 'glpi_networkequipmenttypes', 'glpi_dropdown_iface' => 'glpi_networkinterfaces', 'glpi_networking_ports' => 'glpi_networkports', 'glpi_networking_vlan' => 'glpi_networkports_vlans', 'glpi_networking_wire' => 'glpi_networkports_networkports', 'glpi_dropdown_network' => 'glpi_networks', 'glpi_ocs_admin_link' => 'glpi_ocsadmininfoslinks', 'glpi_ocs_link' => 'glpi_ocslinks', 'glpi_ocs_config' => 'glpi_ocsservers', 'glpi_dropdown_os' => 'glpi_operatingsystems', 'glpi_dropdown_os_sp' => 'glpi_operatingsystemservicepacks', 'glpi_dropdown_os_version' => 'glpi_operatingsystemversions', 'glpi_peripherals' => 'glpi_peripherals', 'glpi_dropdown_model_peripherals' => 'glpi_peripheralmodels', 'glpi_type_peripherals' => 'glpi_peripheraltypes', 'glpi_phones' => 'glpi_phones', 'glpi_dropdown_model_phones' => 'glpi_phonemodels', 'glpi_dropdown_phone_power' => 'glpi_phonepowersupplies', 'glpi_type_phones' => 'glpi_phonetypes', 'glpi_plugins' => 'glpi_plugins', 'glpi_printers' => 'glpi_printers', 'glpi_dropdown_model_printers' => 'glpi_printermodels', 'glpi_type_printers' => 'glpi_printertypes', 'glpi_profiles' => 'glpi_profiles', 'glpi_users_profiles' => 'glpi_profiles_users', 'glpi_registry' => 'glpi_registrykeys', 'glpi_reminder' => 'glpi_reminders', 'glpi_reservation_resa' => 'glpi_reservations', 'glpi_reservation_item' => 'glpi_reservationitems', 'glpi_rules_descriptions' => 'glpi_rules', 'glpi_rules_actions' => 'glpi_ruleactions', 'glpi_rule_cache_model_computer' => 'glpi_rulecachecomputermodels', 'glpi_rule_cache_type_computer' => 'glpi_rulecachecomputertypes', 'glpi_rule_cache_manufacturer' => 'glpi_rulecachemanufacturers', 'glpi_rule_cache_model_monitor' => 'glpi_rulecachemonitormodels', 'glpi_rule_cache_type_monitor' => 'glpi_rulecachemonitortypes', 'glpi_rule_cache_model_networking' => 'glpi_rulecachenetworkequipmentmodels', 'glpi_rule_cache_type_networking' => 'glpi_rulecachenetworkequipmenttypes', 'glpi_rule_cache_os' => 'glpi_rulecacheoperatingsystems', 'glpi_rule_cache_os_sp' => 'glpi_rulecacheoperatingsystemservicepacks', 'glpi_rule_cache_os_version' => 'glpi_rulecacheoperatingsystemversions', 'glpi_rule_cache_model_peripheral' => 'glpi_rulecacheperipheralmodels', 'glpi_rule_cache_type_peripheral' => 'glpi_rulecacheperipheraltypes', 'glpi_rule_cache_model_phone' => 'glpi_rulecachephonemodels', 'glpi_rule_cache_type_phone' => 'glpi_rulecachephonetypes', 'glpi_rule_cache_model_printer' => 'glpi_rulecacheprintermodels', 'glpi_rule_cache_type_printer' => 'glpi_rulecacheprintertypes', 'glpi_rule_cache_software' => 'glpi_rulecachesoftwares', 'glpi_rules_criterias' => 'glpi_rulecriterias', 'glpi_rules_ldap_parameters' => 'glpi_rulerightparameters', 'glpi_software' => 'glpi_softwares', 'glpi_dropdown_software_category' => 'glpi_softwarecategories', 'glpi_softwarelicenses' => 'glpi_softwarelicenses', 'glpi_dropdown_licensetypes' => 'glpi_softwarelicensetypes', 'glpi_softwareversions' => 'glpi_softwareversions', 'glpi_dropdown_state' => 'glpi_states', 'glpi_enterprises' => 'glpi_suppliers', 'glpi_dropdown_enttype' => 'glpi_suppliertypes', 'glpi_tracking' => 'glpi_tickets', 'glpi_dropdown_tracking_category' => 'glpi_ticketcategories', 'glpi_followups' => 'glpi_ticketfollowups', 'glpi_tracking_planning' => 'glpi_ticketplannings', 'glpi_transfers' => 'glpi_transfers', 'glpi_users' => 'glpi_users', 'glpi_dropdown_user_titles' => 'glpi_usertitles', 'glpi_dropdown_user_types' => 'glpi_usercategories', 'glpi_dropdown_vlan' => 'glpi_vlans'); $backup_tables = false; foreach ($glpi_tables as $original_table => $new_table) { if (strcmp($original_table, $new_table) != 0) { // Original table exists ? if (TableExists($original_table)) { // rename new tables if exists ? if (TableExists($new_table)) { if (TableExists("backup_{$new_table}")) { $query = "DROP TABLE `backup_" . $new_table . "`"; $DB->queryOrDie($query, "0.78 drop backup table backup_{$new_table}"); } $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}."); $backup_tables = true; $query = "RENAME TABLE `{$new_table}`\n TO `backup_{$new_table}`"; $DB->queryOrDie($query, "0.78 backup table {$new_table}"); } // rename original table $query = "RENAME TABLE `{$original_table}`\n TO `{$new_table}`"; $DB->queryOrDie($query, "0.78 rename {$original_table} to {$new_table}"); } } if (FieldExists($new_table, 'ID', false)) { // ALTER ID -> id $changes[$new_table][] = "CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT"; } } if ($backup_tables) { $migration->displayWarning("You can delete backup tables if you have no need of them.", true); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: rename foreign keys')); $foreignkeys = array('assign' => array(array('to' => 'users_id_assign', 'tables' => array('glpi_tickets'))), 'assign_group' => array(array('to' => 'groups_id_assign', 'tables' => array('glpi_tickets'))), 'assign_ent' => array(array('to' => 'suppliers_id_assign', 'tables' => array('glpi_tickets'))), 'auth_method' => array(array('to' => 'authtype', 'noindex' => array('glpi_users'), 'tables' => array('glpi_users'))), 'author' => array(array('to' => 'users_id', 'tables' => array('glpi_ticketfollowups', 'glpi_knowbaseitems', 'glpi_tickets'))), 'auto_update' => array(array('to' => 'autoupdatesystems_id', 'tables' => array('glpi_computers'))), 'budget' => array(array('to' => 'budgets_id', 'tables' => array('glpi_infocoms'))), 'buy_version' => array(array('to' => 'softwareversions_id_buy', 'tables' => array('glpi_softwarelicenses'))), 'category' => array(array('to' => 'ticketcategories_id', 'tables' => array('glpi_tickets')), array('to' => 'softwarecategories_id', 'tables' => array('glpi_softwares'))), 'categoryID' => array(array('to' => 'knowbaseitemcategories_id', 'tables' => array('glpi_knowbaseitems'))), 'category_on_software_delete' => array(array('to' => 'softwarecategories_id_ondelete', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'category applyed when a software is deleted'))), 'cID' => array(array('to' => 'computers_id', 'tables' => array('glpi_computers_softwareversions'))), 'computer' => array(array('to' => 'items_id', 'noindex' => array('glpi_tickets'), 'tables' => array('glpi_tickets'))), 'computer_id' => array(array('to' => 'computers_id', 'tables' => array('glpi_registrykeys'))), 'contract_type' => array(array('to' => 'contracttypes_id', 'tables' => array('glpi_contracts'))), 'default_rubdoc_tracking' => array(array('to' => 'documentcategories_id_forticket', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'default category for documents added with a ticket'))), 'default_state' => array(array('to' => 'states_id_default', 'noindex' => array('glpi_ocsservers'), 'tables' => array('glpi_ocsservers'))), 'device_type' => array(array('to' => 'itemtype', 'noindex' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_bookmarks_users', 'glpi_documents_items', 'glpi_infocoms', 'glpi_links_itemtypes', 'glpi_networkports', 'glpi_reservationitems', 'glpi_tickets'), 'tables' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms', 'glpi_bookmarks', 'glpi_bookmarks_users', 'glpi_links_itemtypes', 'glpi_networkports', 'glpi_reservationitems', 'glpi_tickets'))), 'domain' => array(array('to' => 'domains_id', 'tables' => array('glpi_computers', 'glpi_networkequipments', 'glpi_printers'))), 'end1' => array(array('to' => 'items_id', 'noindex' => array('glpi_computers_items'), 'tables' => array('glpi_computers_items'), 'comments' => array('glpi_computers_items' => 'RELATION to various table, according to itemtype (ID)')), array('to' => 'networkports_id_1', 'noindex' => array('glpi_networkports_networkports'), 'tables' => array('glpi_networkports_networkports'))), 'end2' => array(array('to' => 'computers_id', 'tables' => array('glpi_computers_items')), array('to' => 'networkports_id_2', 'tables' => array('glpi_networkports_networkports'))), 'extra_ldap_server' => array(array('to' => 'authldaps_id_extra', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'extra server'))), 'firmware' => array(array('to' => 'networkequipmentfirmwares_id', 'tables' => array('glpi_networkequipments'))), 'FK_bookmark' => array(array('to' => 'bookmarks_id', 'tables' => array('glpi_bookmarks_users'))), 'FK_computers' => array(array('to' => 'computers_id', 'tables' => array('glpi_computerdisks', 'glpi_softwarelicenses'))), 'FK_contact' => array(array('to' => 'contacts_id', 'tables' => array('glpi_contacts_suppliers'))), 'FK_contract' => array(array('to' => 'contracts_id', 'noindex' => array('glpi_contracts_items'), 'tables' => array('glpi_contracts_suppliers', 'glpi_contracts_items'))), 'FK_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms'), 'tables' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms'))), 'FK_doc' => array(array('to' => 'documents_id', 'noindex' => array('glpi_documents_items'), 'tables' => array('glpi_documents_items'))), 'FK_enterprise' => array(array('to' => 'suppliers_id', 'noindex' => array('glpi_contacts_suppliers', 'glpi_contracts_suppliers'), 'tables' => array('glpi_contacts_suppliers', 'glpi_contracts_suppliers', 'glpi_infocoms'))), 'FK_entities' => array(array('to' => 'entities_id', 'noindex' => array('glpi_locations', 'glpi_netpoints', 'glpi_entitydatas'), 'tables' => array('glpi_bookmarks', 'glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_locations', 'glpi_netpoints', 'glpi_suppliers', 'glpi_entitydatas', 'glpi_groups', 'glpi_knowbaseitems', 'glpi_links', 'glpi_mailcollectors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_reminders', 'glpi_rules', 'glpi_softwares', 'glpi_softwarelicenses', 'glpi_tickets', 'glpi_users', 'glpi_profiles_users'), 'default' => array('glpi_bookmarks' => "-1"))), 'FK_filesystems' => array(array('to' => 'filesystems_id', 'tables' => array('glpi_computerdisks'))), 'FK_glpi_cartridges_type' => array(array('to' => 'cartridgeitems_id', 'tables' => array('glpi_cartridges', 'glpi_cartridges_printermodels'))), 'FK_glpi_consumables_type' => array(array('to' => 'consumableitems_id', 'noindex' => array(''), 'tables' => array('glpi_consumables'))), 'FK_glpi_dropdown_model_printers' => array(array('to' => 'printermodels_id', 'noindex' => array('glpi_cartridges_printermodels'), 'tables' => array('glpi_cartridges_printermodels'))), 'FK_glpi_enterprise' => array(array('to' => 'manufacturers_id', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_devicecases', 'glpi_devicecontrols', 'glpi_devicedrives', 'glpi_devicegraphiccards', 'glpi_deviceharddrives', 'glpi_devicenetworkcards', 'glpi_devicemotherboards', 'glpi_devicepcis', 'glpi_devicepowersupplies', 'glpi_deviceprocessors', 'glpi_devicememories', 'glpi_devicesoundcards', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'FK_glpi_printers' => array(array('to' => 'printers_id', 'tables' => array('glpi_cartridges'))), 'FK_group' => array(array('to' => 'groups_id', 'tables' => array('glpi_tickets'))), 'FK_groups' => array(array('to' => 'groups_id', 'tables' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares', 'glpi_groups_users'))), 'FK_interface' => array(array('to' => 'interfacetypes_id', 'tables' => array('glpi_devicegraphiccards'))), 'FK_item' => array(array('to' => 'items_id', 'noindex' => array('glpi_mailingsettings'), 'tables' => array('glpi_mailingsettings'))), 'FK_links' => array(array('to' => 'links_id', 'tables' => array('glpi_links_itemtypes'))), 'FK_port' => array(array('to' => 'networkports_id', 'noindex' => array('glpi_networkports_vlans'), 'tables' => array('glpi_networkports_vlans'))), 'FK_profiles' => array(array('to' => 'profiles_id', 'tables' => array('glpi_profiles_users', 'glpi_users'))), 'FK_rules' => array(array('to' => 'rules_id', 'tables' => array('glpi_rulecriterias', 'glpi_ruleactions'))), 'FK_tracking' => array(array('to' => 'tickets_id', 'tables' => array('glpi_documents'))), 'FK_users' => array(array('to' => 'users_id', 'noindex' => array('glpi_displaypreferences', 'glpi_bookmarks_users', 'glpi_groups_users'), 'tables' => array('glpi_bookmarks', 'glpi_displaypreferences', 'glpi_documents', 'glpi_groups', 'glpi_reminders', 'glpi_bookmarks_users', 'glpi_groups_users', 'glpi_profiles_users', 'glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'FK_vlan' => array(array('to' => 'vlans_id', 'tables' => array('glpi_networkports_vlans'))), 'glpi_id' => array(array('to' => 'computers_id', 'tables' => array('glpi_ocslinks'))), 'id_assign' => array(array('to' => 'users_id', 'tables' => array('glpi_ticketplannings'))), 'id_auth' => array(array('to' => 'auths_id', 'noindex' => array('glpi_users'), 'tables' => array('glpi_users'))), 'id_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_reservationitems'), 'tables' => array('glpi_reservationitems'))), 'id_followup' => array(array('to' => 'ticketfollowups_id', 'tables' => array('glpi_ticketplannings'))), 'id_item' => array(array('to' => 'reservationitems_id', 'tables' => array('glpi_reservations'))), 'id_user' => array(array('to' => 'users_id', 'tables' => array('glpi_consumables', 'glpi_reservations'))), 'iface' => array(array('to' => 'networkinterfaces_id', 'tables' => array('glpi_networkports'))), 'interface' => array(array('to' => 'interfacetypes_id', 'tables' => array('glpi_devicecontrols', 'glpi_deviceharddrives', 'glpi_devicedrives'))), 'item' => array(array('to' => 'items_id', 'noindex' => array('glpi_events'), 'tables' => array('glpi_events'))), 'link_if_status' => array(array('to' => 'states_id_linkif', 'noindex' => array('glpi_ocsservers'), 'tables' => array('glpi_ocsservers'))), 'location' => array(array('to' => 'locations_id', 'noindex' => array('glpi_netpoints'), 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_netpoints', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_users', 'glpi_softwares'))), 'model' => array(array('to' => 'computermodels_id', 'tables' => array('glpi_computers')), array('to' => 'monitormodels_id', 'tables' => array('glpi_monitors')), array('to' => 'networkequipmentmodels_id', 'tables' => array('glpi_networkequipments')), array('to' => 'peripheralmodels_id', 'tables' => array('glpi_peripherals')), array('to' => 'phonemodels_id', 'tables' => array('glpi_phones')), array('to' => 'printermodels_id', 'tables' => array('glpi_printers'))), 'netpoint' => array(array('to' => 'netpoints_id', 'tables' => array('glpi_networkports'))), 'network' => array(array('to' => 'networks_id', 'tables' => array('glpi_computers', 'glpi_networkequipments', 'glpi_printers'))), 'ocs_id' => array(array('to' => 'ocsid', 'noindex' => array('glpi_ocslinks'), 'tables' => array('glpi_ocslinks'))), 'ocs_server_id' => array(array('to' => 'ocsservers_id', 'noindex' => array('glpi_ocslinks'), 'tables' => array('glpi_ocsadmininfoslinks', 'glpi_ocslinks'))), 'on_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_networkports'), 'tables' => array('glpi_networkports'))), 'os' => array(array('to' => 'operatingsystems_id', 'tables' => array('glpi_computers'))), 'os_sp' => array(array('to' => 'operatingsystemservicepacks_id', 'tables' => array('glpi_computers'))), 'os_version' => array(array('to' => 'operatingsystemversions_id', 'tables' => array('glpi_computers'))), 'parentID' => array(array('to' => 'knowbaseitemcategories_id', 'noindex' => array('glpi_knowbaseitemcategories'), 'tables' => array('glpi_knowbaseitemcategories')), array('to' => 'locations_id', 'tables' => array('glpi_locations')), array('to' => 'ticketcategories_id', 'tables' => array('glpi_ticketcategories')), array('to' => 'entities_id', 'tables' => array('glpi_entities'))), 'platform' => array(array('to' => 'operatingsystems_id', 'tables' => array('glpi_softwares'))), 'power' => array(array('to' => 'phonepowersupplies_id', 'tables' => array('glpi_phones'))), 'recipient' => array(array('to' => 'users_id_recipient', 'tables' => array('glpi_tickets'))), 'rubrique' => array(array('to' => 'documentcategories_id', 'tables' => array('glpi_documents'))), 'rule_id' => array(array('to' => 'rules_id', 'tables' => array('glpi_rulecachemanufacturers', 'glpi_rulecachecomputermodels', 'glpi_rulecachemonitormodels', 'glpi_rulecachenetworkequipmentmodels', 'glpi_rulecacheperipheralmodels', 'glpi_rulecachephonemodels', 'glpi_rulecacheprintermodels', 'glpi_rulecacheoperatingsystems', 'glpi_rulecacheoperatingsystemservicepacks', 'glpi_rulecacheoperatingsystemversions', 'glpi_rulecachesoftwares', 'glpi_rulecachecomputertypes', 'glpi_rulecachemonitortypes', 'glpi_rulecachenetworkequipmenttypes', 'glpi_rulecacheperipheraltypes', 'glpi_rulecachephonetypes', 'glpi_rulecacheprintertypes'))), 'server_id' => array(array('to' => 'authldaps_id', 'tables' => array('glpi_authldapreplicates'))), 'sID' => array(array('to' => 'softwares_id', 'tables' => array('glpi_softwarelicenses', 'glpi_softwareversions'))), 'state' => array(array('to' => 'states_id', 'tables' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwareversions'))), 'tech_num' => array(array('to' => 'users_id_tech', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'title' => array(array('to' => 'usertitles_id', 'tables' => array('glpi_users'))), 'tracking' => array(array('to' => 'tickets_id', 'tables' => array('glpi_ticketfollowups'))), 'type' => array(array('to' => 'cartridgeitemtypes_id', 'tables' => array('glpi_cartridgeitems')), array('to' => 'computertypes_id', 'tables' => array('glpi_computers')), array('to' => 'consumableitemtypes_id', 'tables' => array('glpi_consumableitems')), array('to' => 'contacttypes_id', 'tables' => array('glpi_contacts')), array('to' => 'devicecasetypes_id', 'tables' => array('glpi_devicecases')), array('to' => 'devicememorytypes_id', 'tables' => array('glpi_devicememories')), array('to' => 'suppliertypes_id', 'tables' => array('glpi_suppliers')), array('to' => 'monitortypes_id', 'tables' => array('glpi_monitors')), array('to' => 'networkequipmenttypes_id', 'tables' => array('glpi_networkequipments')), array('to' => 'peripheraltypes_id', 'tables' => array('glpi_peripherals')), array('to' => 'phonetypes_id', 'tables' => array('glpi_phones')), array('to' => 'printertypes_id', 'tables' => array('glpi_printers')), array('to' => 'softwarelicensetypes_id', 'tables' => array('glpi_softwarelicenses')), array('to' => 'usercategories_id', 'tables' => array('glpi_users')), array('to' => 'itemtype', 'noindex' => array('glpi_computers_items'), 'tables' => array('glpi_computers_items', 'glpi_displaypreferences'))), 'update_software' => array(array('to' => 'softwares_id', 'tables' => array('glpi_softwares'))), 'use_version' => array(array('to' => 'softwareversions_id_use', 'tables' => array('glpi_softwarelicenses'))), 'vID' => array(array('to' => 'softwareversions_id', 'tables' => array('glpi_computers_softwareversions')))); foreach ($foreignkeys as $oldname => $newnames) { foreach ($newnames as $tab) { $newname = $tab['to']; foreach ($tab['tables'] as $table) { $doindex = true; if (isset($tab['noindex']) && in_array($table, $tab['noindex'])) { $doindex = false; } // Rename field if (FieldExists($table, $oldname, false)) { $addcomment = ''; if (isset($tab['comments']) && isset($tab['comments'][$table])) { $addcomment = " COMMENT '" . $tab['comments'][$table] . "' "; } $default_value = 0; if (isset($tab['default']) && isset($tab['default'][$table])) { $default_value = $tab['default'][$table]; } // Manage NULL fields $query = "UPDATE `{$table}`\n SET `{$oldname}` = '{$default_value}'\n WHERE `{$oldname}` IS NULL "; $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}"); $changes[$table][] = "CHANGE COLUMN `{$oldname}` `{$newname}` INT( 11 ) NOT NULL\n DEFAULT '{$default_value}' {$addcomment}"; } else { $updateresult = false; $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true); } // If do index : delete old one / create new one if ($doindex) { if (!isIndex($table, $newname)) { $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)"; } if ($oldname != $newname && isIndex($table, $oldname)) { $changes[$table][] = "DROP INDEX `{$oldname}`"; } } } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: rename bool values')); $boolfields = array('glpi_authldaps' => array(array('from' => 'ldap_use_tls', 'to' => 'use_tls', 'default' => 0, 'noindex ' => true), array('from' => 'use_dn', 'to' => 'use_dn', 'default' => 1, 'noindex' => true)), 'glpi_bookmarks' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 1), array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0)), 'glpi_cartridgeitems' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_computers' => array(array('from' => 'is_template', 'to' => 'is_template', 'default' => 0), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'ocs_import', 'to' => 'is_ocs_import', 'default' => 0)), 'glpi_configs' => array(array('from' => 'jobs_at_login', 'to' => 'show_jobs_at_login', 'default' => 0, 'noindex' => true), array('from' => 'mailing', 'to' => 'use_mailing', 'default' => 0, 'noindex' => true), array('from' => 'permit_helpdesk', 'to' => 'use_anonymous_helpdesk', 'default' => 0, 'noindex' => true), array('from' => 'existing_auth_server_field_clean_domain', 'to' => 'existing_auth_server_field_clean_domain', 'default' => 0, 'noindex' => true), array('from' => 'auto_assign', 'to' => 'use_auto_assign_to_tech', 'default' => 0, 'noindex' => true), array('from' => 'public_faq', 'to' => 'use_public_faq', 'default' => 0, 'noindex' => true), array('from' => 'url_in_mail', 'to' => 'show_link_in_mail', 'default' => 0, 'noindex' => true), array('from' => 'use_ajax', 'to' => 'use_ajax', 'default' => 0, 'noindex' => true), array('from' => 'ajax_autocompletion', 'to' => 'use_ajax_autocompletion', 'default' => 1, 'noindex' => true), array('from' => 'auto_add_users', 'to' => 'is_users_auto_add', 'default' => 1, 'noindex' => true), array('from' => 'view_ID', 'to' => 'is_ids_visible', 'default' => 0, 'noindex' => true), array('from' => 'ocs_mode', 'to' => 'use_ocs_mode', 'default' => 0, 'noindex' => true), array('from' => 'followup_on_update_ticket', 'to' => 'add_followup_on_update_ticket', 'default' => 1, 'noindex' => true), array('from' => 'licenses_alert', 'to' => 'use_licenses_alert', 'default' => 0, 'noindex' => true), array('from' => 'keep_tracking_on_delete', 'to' => 'keep_tickets_on_delete', 'default' => 1, 'noindex' => true), array('from' => 'use_errorlog', 'to' => 'use_log_in_files', 'default' => 0, 'noindex ' => true), array('from' => 'autoupdate_link_contact', 'to' => 'is_contact_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoupdate_link_user', 'to' => 'is_user_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoupdate_link_group', 'to' => 'is_group_autoupdate', 'default' => 1, 'noindex ' => true), array('from' => 'autoupdate_link_location', 'to' => 'is_location_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoclean_link_contact', 'to' => 'is_contact_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_user', 'to' => 'is_user_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_group', 'to' => 'is_group_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_location', 'to' => 'is_location_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'flat_dropdowntree', 'to' => 'use_flat_dropdowntree', 'default' => 0, 'noindex' => true), array('from' => 'autoname_entity', 'to' => 'use_autoname_by_entity', 'default' => 1, 'noindex' => true), array('from' => 'expand_soft_categorized', 'to' => 'is_categorized_soft_expanded', 'default' => 1, 'noindex' => true), array('from' => 'expand_soft_not_categorized', 'to' => 'is_not_categorized_soft_expanded', 'default' => 1, 'noindex' => true), array('from' => 'ticket_title_mandatory', 'to' => 'is_ticket_title_mandatory', 'default' => 0, 'noindex' => true), array('from' => 'ticket_content_mandatory', 'to' => 'is_ticket_content_mandatory', 'default' => 1, 'noindex' => true), array('from' => 'ticket_category_mandatory', 'to' => 'is_ticket_category_mandatory', 'default' => 0, 'noindex' => true), array('from' => 'followup_private', 'to' => 'followup_private', 'default' => 0, 'noindex' => true), array('from' => 'software_helpdesk_visible', 'to' => 'default_software_helpdesk_visible', 'default' => 1, 'noindex' => true)), 'glpi_consumableitems' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_contacts' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_contracts' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'monday', 'to' => 'use_monday', 'default' => 0), array('from' => 'saturday', 'to' => 'use_saturday', 'default' => 0)), 'glpi_devicecontrols' => array(array('from' => 'raid', 'to' => 'is_raid', 'default' => 0, 'noindex' => true)), 'glpi_devicedrives' => array(array('from' => 'is_writer', 'to' => 'is_writer', 'default' => 1, 'noindex' => true)), 'glpi_devicepowersupplies' => array(array('from' => 'atx', 'to' => 'is_atx', 'default' => 1, 'noindex' => true)), 'glpi_documents' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_documenttypes' => array(array('from' => 'upload', 'to' => 'is_uploadable', 'default' => 1)), 'glpi_groups' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true)), 'glpi_knowbaseitems' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1, 'noindex' => true), array('from' => 'faq', 'to' => 'is_faq', 'default' => 0)), 'glpi_links' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1, 'noindex' => true)), 'glpi_monitors' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_micro', 'to' => 'have_micro', 'default' => 0, 'noindex' => true), array('from' => 'flags_speaker', 'to' => 'have_speaker', 'default' => 0, 'noindex' => true), array('from' => 'flags_subd', 'to' => 'have_subd', 'default' => 0, 'noindex' => true), array('from' => 'flags_bnc', 'to' => 'have_bnc', 'default' => 0, 'noindex' => true), array('from' => 'flags_dvi', 'to' => 'have_dvi', 'default' => 0, 'noindex' => true), array('from' => 'flags_pivot', 'to' => 'have_pivot', 'default' => 0, 'noindex' => true)), 'glpi_networkequipments' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true)), 'glpi_ocslinks' => array(array('from' => 'auto_update', 'to' => 'use_auto_update', 'default' => 1)), 'glpi_ocsservers' => array(array('from' => 'import_periph', 'to' => 'import_periph', 'default' => 0, 'noindex' => true), array('from' => 'import_monitor', 'to' => 'import_monitor', 'default' => 0, 'noindex' => true), array('from' => 'import_software', 'to' => 'import_software', 'default' => 0, 'noindex' => true), array('from' => 'import_printer', 'to' => 'import_printer', 'default' => 0, 'noindex' => true), array('from' => 'import_general_name', 'to' => 'import_general_name', 'default' => 0, 'noindex' => true), array('from' => 'import_general_os', 'to' => 'import_general_os', 'default' => 0, 'noindex' => true), array('from' => 'import_general_serial', 'to' => 'import_general_serial', 'default' => 0, 'noindex' => true), array('from' => 'import_general_model', 'to' => 'import_general_model', 'default' => 0, 'noindex' => true), array('from' => 'import_general_enterprise', 'to' => 'import_general_manufacturer', 'default' => 0, 'noindex' => true), array('from' => 'import_general_type', 'to' => 'import_general_type', 'default' => 0, 'noindex' => true), array('from' => 'import_general_domain', 'to' => 'import_general_domain', 'default' => 0, 'noindex' => true), array('from' => 'import_general_contact', 'to' => 'import_general_contact', 'default' => 0, 'noindex' => true), array('from' => 'import_general_comments', 'to' => 'import_general_comment', 'default' => 0, 'noindex' => true), array('from' => 'import_device_processor', 'to' => 'import_device_processor', 'default' => 0, 'noindex' => true), array('from' => 'import_device_memory', 'to' => 'import_device_memory', 'default' => 0, 'noindex' => true), array('from' => 'import_device_hdd', 'to' => 'import_device_hdd', 'default' => 0, 'noindex' => true), array('from' => 'import_device_iface', 'to' => 'import_device_iface', 'default' => 0, 'noindex' => true), array('from' => 'import_device_gfxcard', 'to' => 'import_device_gfxcard', 'default' => 0, 'noindex' => true), array('from' => 'import_device_sound', 'to' => 'import_device_sound', 'default' => 0, 'noindex' => true), array('from' => 'import_device_drives', 'to' => 'import_device_drive', 'default' => 0, 'noindex' => true), array('from' => 'import_device_ports', 'to' => 'import_device_port', 'default' => 0, 'noindex' => true), array('from' => 'import_device_modems', 'to' => 'import_device_modem', 'default' => 0, 'noindex' => true), array('from' => 'import_registry', 'to' => 'import_registry', 'default' => 0, 'noindex' => true), array('from' => 'import_os_serial', 'to' => 'import_os_serial', 'default' => 0, 'noindex' => true), array('from' => 'import_ip', 'to' => 'import_ip', 'default' => 0, 'noindex' => true), array('from' => 'import_disk', 'to' => 'import_disk', 'default' => 0, 'noindex' => true), array('from' => 'import_monitor_comments', 'to' => 'import_monitor_comment', 'default' => 0, 'noindex' => true), array('from' => 'glpi_link_enabled', 'to' => 'is_glpi_link_enabled', 'default' => 0, 'noindex' => true), array('from' => 'link_ip', 'to' => 'use_ip_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_name', 'to' => 'use_name_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_mac_address', 'to' => 'use_mac_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_serial', 'to' => 'use_serial_to_link', 'default' => 0, 'noindex' => true), array('from' => 'use_soft_dict', 'to' => 'use_soft_dict', 'default' => 0, 'noindex' => true)), 'glpi_peripherals' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true)), 'glpi_phones' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_hp', 'to' => 'have_hp', 'default' => 0, 'noindex' => true), array('from' => 'flags_casque', 'to' => 'have_headset', 'default' => 0, 'noindex' => true)), 'glpi_printers' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_usb', 'to' => 'have_usb', 'default' => 0, 'noindex' => true), array('from' => 'flags_par', 'to' => 'have_parallel', 'default' => 0, 'noindex' => true), array('from' => 'flags_serial', 'to' => 'have_serial', 'default' => 0, 'noindex' => true)), 'glpi_profiles_users' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1), array('from' => 'dynamic', 'to' => 'is_dynamic', 'default' => 0)), 'glpi_profiles' => array(array('from' => 'is_default', 'to' => 'is_default', 'default' => 0)), 'glpi_reminders' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 1), array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0), array('from' => 'rv', 'to' => 'is_planned', 'default' => 0)), 'glpi_reservationitems' => array(array('from' => 'active', 'to' => 'is_active', 'default' => 1)), 'glpi_rules' => array(array('from' => 'active', 'to' => 'is_active', 'default' => 1)), 'glpi_suppliers' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_softwares' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'helpdesk_visible', 'to' => 'is_helpdesk_visible', 'default' => 1), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_update', 'to' => 'is_update', 'default' => 0, 'noindex' => true)), 'glpi_softwarelicenses' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true)), 'glpi_tickets' => array(array('from' => 'emailupdates', 'to' => 'use_email_notification', 'default' => 0, 'noindex' => true)), 'glpi_ticketfollowups' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 0)), 'glpi_users' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'active', 'to' => 'is_active', 'default' => 1), array('from' => 'jobs_at_login', 'to' => 'show_jobs_at_login', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'followup_private', 'to' => 'followup_private', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'expand_soft_categorized', 'to' => 'is_categorized_soft_expanded', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'expand_soft_not_categorized', 'to' => 'is_not_categorized_soft_expanded', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'flat_dropdowntree', 'to' => 'use_flat_dropdowntree', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'view_ID', 'to' => 'is_ids_visible', 'default' => NULL, 'maybenull' => true, 'noindex' => true))); foreach ($boolfields as $table => $tab) { foreach ($tab as $update) { $newname = $update['to']; $oldname = $update['from']; $doindex = true; if (isset($update['noindex']) && $update['noindex']) { $doindex = false; } // Rename field if (FieldExists($table, $oldname, false)) { $NULL = "NOT NULL"; if (isset($update['maybenull']) && $update['maybenull']) { $NULL = "NULL"; // Manage not zero values $query = "UPDATE `{$table}`\n SET `{$oldname}` = 1\n WHERE `{$oldname}` <> 0\n AND `{$oldname}` IS NOT NULL"; $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}"); } else { // Manage NULL fields $query = "UPDATE `{$table}`\n SET `{$oldname}` = 0\n WHERE `{$oldname}` IS NULL"; $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}"); // Manage not zero values $query = "UPDATE `{$table}`\n SET `{$oldname}` = 1\n WHERE `{$oldname}` <> 0"; $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}"); } $default = "DEFAULT NULL"; if (isset($update['default']) && !is_null($update['default'])) { $default = "DEFAULT " . $update['default']; } $changes[$table][] = "CHANGE `{$oldname}` `{$newname}` TINYINT( 1 ) {$NULL} {$default}"; } else { $updateresult = false; $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true); } // If do index : delete old one / create new one if ($doindex) { if (!isIndex($table, $newname)) { $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)"; } if ($newname != $oldname && isIndex($table, $oldname)) { $changes[$table][] = "DROP INDEX `{$oldname}`"; } } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: update text fields')); $textfields = array('comments' => array('to' => 'comment', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_autoupdatesystems', 'glpi_budgets', 'glpi_cartridgeitemtypes', 'glpi_devicecasetypes', 'glpi_consumableitemtypes', 'glpi_contacttypes', 'glpi_contracttypes', 'glpi_domains', 'glpi_suppliertypes', 'glpi_filesystems', 'glpi_networkequipmentfirmwares', 'glpi_networkinterfaces', 'glpi_interfacetypes', 'glpi_knowbaseitemcategories', 'glpi_softwarelicensetypes', 'glpi_locations', 'glpi_manufacturers', 'glpi_computermodels', 'glpi_monitormodels', 'glpi_networkequipmentmodels', 'glpi_peripheralmodels', 'glpi_phonemodels', 'glpi_printermodels', 'glpi_netpoints', 'glpi_networks', 'glpi_operatingsystems', 'glpi_operatingsystemservicepacks', 'glpi_operatingsystemversions', 'glpi_phonepowersupplies', 'glpi_devicememorytypes', 'glpi_documentcategories', 'glpi_softwarecategories', 'glpi_states', 'glpi_ticketcategories', 'glpi_usertitles', 'glpi_usercategories', 'glpi_vlans', 'glpi_suppliers', 'glpi_entities', 'glpi_groups', 'glpi_infocoms', 'glpi_monitors', 'glpi_phones', 'glpi_printers', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_reservationitems', 'glpi_rules', 'glpi_softwares', 'glpi_softwarelicenses', 'glpi_softwareversions', 'glpi_computertypes', 'glpi_monitortypes', 'glpi_networkequipmenttypes', 'glpi_peripheraltypes', 'glpi_phonetypes', 'glpi_printertypes', 'glpi_users')), 'notes' => array('to' => 'notepad', 'long' => true, 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_suppliers', 'glpi_entitydatas', 'glpi_printers', 'glpi_monitors', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_softwares')), 'ldap_condition' => array('to' => 'condition', 'tables' => array('glpi_authldaps')), 'import_printers' => array('to' => 'import_printer', 'long' => true, 'tables' => array('glpi_ocslinks')), 'contents' => array('to' => 'content', 'long' => true, 'tables' => array('glpi_tickets', 'glpi_ticketfollowups'))); foreach ($textfields as $oldname => $tab) { $newname = $tab['to']; $type = "TEXT"; if (isset($tab['long']) && $tab['long']) { $type = "LONGTEXT"; } foreach ($tab['tables'] as $table) { // Rename field if (FieldExists($table, $oldname, false)) { $query = "ALTER TABLE `{$table}`\n CHANGE `{$oldname}` `{$newname}` {$type} NULL DEFAULT NULL "; $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}"); } else { $updateresult = false; $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true); } } } $varcharfields = array('glpi_authldaps' => array(array('from' => 'ldap_host', 'to' => 'host', 'noindex' => true), array('from' => 'ldap_basedn', 'to' => 'basedn', 'noindex' => true), array('from' => 'ldap_rootdn', 'to' => 'rootdn', 'noindex' => true), array('from' => 'ldap_pass', 'to' => 'rootdn_password', 'noindex' => true), array('from' => 'ldap_login', 'to' => 'login_field', 'default' => 'uid', 'noindex' => true), array('from' => 'ldap_field_group', 'to' => 'group_field', 'noindex' => true), array('from' => 'ldap_group_condition', 'to' => 'group_condition', 'noindex' => true), array('from' => 'ldap_field_group_member', 'to' => 'group_member_field', 'noindex' => true), array('from' => 'ldap_field_email', 'to' => 'email_field', 'noindex' => true), array('from' => 'ldap_field_realname', 'to' => 'realname_field', 'noindex' => true), array('from' => 'ldap_field_firstname', 'to' => 'firstname_field', 'noindex' => true), array('from' => 'ldap_field_phone', 'to' => 'phone_field', 'noindex' => true), array('from' => 'ldap_field_phone2', 'to' => 'phone2_field', 'noindex' => true), array('from' => 'ldap_field_mobile', 'to' => 'mobile_field', 'noindex' => true), array('from' => 'ldap_field_comments', 'to' => 'comment_field', 'noindex' => true), array('from' => 'ldap_field_title', 'to' => 'title_field', 'noindex' => true), array('from' => 'ldap_field_type', 'to' => 'category_field', 'noindex' => true), array('from' => 'ldap_field_language', 'to' => 'language_field', 'noindex' => true)), 'glpi_authldapreplicates' => array(array('from' => 'ldap_host', 'to' => 'host', 'noindex' => true)), 'glpi_authmails' => array(array('from' => 'imap_auth_server', 'to' => 'connect_string', 'noindex' => true), array('from' => 'imap_host', 'to' => 'host', 'noindex' => true)), 'glpi_computers' => array(array('from' => 'os_license_id', 'to' => 'os_licenseid', 'noindex' => true), array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_configs' => array(array('from' => 'helpdeskhelp_url', 'to' => 'helpdesk_doc_url', 'noindex' => true), array('from' => 'centralhelp_url', 'to' => 'central_doc_url', 'noindex' => true)), 'glpi_contracts' => array(array('from' => 'compta_num', 'to' => 'accounting_number', 'noindex' => true)), 'glpi_events' => array(array('from' => 'itemtype', 'to' => 'type', 'noindex' => true)), 'glpi_infocoms' => array(array('from' => 'num_commande', 'to' => 'order_number', 'noindex' => true), array('from' => 'bon_livraison', 'to' => 'delivery_number', 'noindex' => true), array('from' => 'num_immo', 'to' => 'immo_number', 'noindex' => true), array('from' => 'facture', 'to' => 'bill', 'noindex' => true)), 'glpi_monitors' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_networkequipments' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true), array('from' => 'ifmac', 'to' => 'mac', 'noindex' => true), array('from' => 'ifaddr', 'to' => 'ip', 'noindex' => true)), 'glpi_networkports' => array(array('from' => 'ifmac', 'to' => 'mac', 'noindex' => true), array('from' => 'ifaddr', 'to' => 'ip', 'noindex' => true)), 'glpi_peripherals' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_phones' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_printers' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true), array('from' => 'ramSize', 'to' => 'memory_size', 'noindex' => true)), 'glpi_registrykeys' => array(array('from' => 'registry_hive', 'to' => 'hive', 'noindex' => true), array('from' => 'registry_path', 'to' => 'path', 'noindex' => true), array('from' => 'registry_value', 'to' => 'value', 'noindex' => true), array('from' => 'registry_ocs_name', 'to' => 'ocs_name', 'noindex' => true)), 'glpi_softwares' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_tickets' => array(array('from' => 'uemail', 'to' => 'user_email', 'noindex' => true))); foreach ($varcharfields as $table => $tab) { foreach ($tab as $update) { $newname = $update['to']; $oldname = $update['from']; $doindex = true; if (isset($update['noindex']) && $update['noindex']) { $doindex = false; } $default = "DEFAULT NULL"; if (isset($update['default']) && !is_null($update['default'])) { $default = "DEFAULT '" . $update['default'] . "'"; } // Rename field if (FieldExists($table, $oldname, false)) { $query = "ALTER TABLE `{$table}`\n CHANGE `{$oldname}` `{$newname}` VARCHAR( 255 ) NULL {$default} "; $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}"); } else { $updateresult = false; $migration->displayWarning("Error: {$table}.{$oldname} does not exist."); } // If do index : delete old one / create new one if ($doindex) { if (!isIndex($table, $newname)) { $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)"; } if ($newname != $oldname && isIndex($table, $oldname)) { $changes[$table][] = "DROP INDEX `{$oldname}`"; } } } } $charfields = array('glpi_profiles' => array(array('from' => 'user_auth_method', 'to' => 'user_authtype', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_tracking', 'to' => 'rule_ticket', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_softwarecategories', 'to' => 'rule_softwarecategories', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_dictionnary_software', 'to' => 'rule_dictionnary_software', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_dictionnary_dropdown', 'to' => 'rule_dictionnary_dropdown', 'length' => 1, 'default' => NULL, 'noindex' => true)), 'glpi_configs' => array(array('from' => 'version', 'to' => 'version', 'length' => 10, 'default' => NULL, 'noindex' => true), array('from' => 'version', 'to' => 'version', 'length' => 10, 'default' => NULL, 'noindex' => true), array('from' => 'language', 'to' => 'language', 'length' => 10, 'default' => 'en_GB', 'noindex' => true, 'comments' => 'see define.php CFG_GLPI[language] array'), array('from' => 'priority_1', 'to' => 'priority_1', 'length' => 20, 'default' => '#fff2f2', 'noindex' => true), array('from' => 'priority_2', 'to' => 'priority_2', 'length' => 20, 'default' => '#ffe0e0', 'noindex' => true), array('from' => 'priority_3', 'to' => 'priority_3', 'length' => 20, 'default' => '#ffcece', 'noindex' => true), array('from' => 'priority_4', 'to' => 'priority_4', 'length' => 20, 'default' => '#ffbfbf', 'noindex' => true), array('from' => 'priority_5', 'to' => 'priority_5', 'length' => 20, 'default' => '#ffadad', 'noindex' => true), array('from' => 'founded_new_version', 'to' => 'founded_new_version', 'length' => 10, 'default' => NULL, 'noindex' => true)), 'glpi_rules' => array(array('from' => 'match', 'to' => 'match', 'length' => 10, 'default' => NULL, 'noindex' => true, 'comments' => 'see define.php *_MATCHING constant')), 'glpi_users' => array(array('from' => 'language', 'to' => 'language', 'length' => 10, 'default' => NULL, 'noindex' => true, 'comments' => 'see define.php CFG_GLPI[language] array'), array('from' => 'priority_1', 'to' => 'priority_1', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_2', 'to' => 'priority_2', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_3', 'to' => 'priority_3', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_4', 'to' => 'priority_4', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_5', 'to' => 'priority_5', 'length' => 20, 'default' => NULL, 'noindex' => true))); foreach ($charfields as $table => $tab) { foreach ($tab as $update) { $newname = $update['to']; $oldname = $update['from']; $length = $update['length']; $doindex = true; if (isset($update['noindex']) && $update['noindex']) { $doindex = false; } $default = "DEFAULT NULL"; if (isset($update['default']) && !is_null($update['default'])) { $default = "DEFAULT '" . $update['default'] . "'"; } $addcomment = ""; if (isset($update['comments'])) { $addcomment = "COMMENT '" . $update['comments'] . "'"; } // Rename field if (FieldExists($table, $oldname, false)) { $query = "ALTER TABLE `{$table}`\n CHANGE `{$oldname}` `{$newname}` CHAR( {$length} ) NULL {$default} {$addcomment} "; $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}"); } else { $updateresult = false; $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true); } // If do index : delete old one / create new one if ($doindex) { if (!isIndex($table, $newname)) { $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)"; } if ($oldname != $newname && isIndex($table, $oldname)) { $changes[$table][] = "DROP INDEX `{$oldname}`"; } } } } $intfields = array('glpi_authldaps' => array(array('from' => 'ldap_port', 'to' => 'port', 'default' => 389, 'noindex' => true, 'checkdatas' => true), array('from' => 'ldap_search_for_groups', 'to' => 'group_search_type', 'default' => 0, 'noindex' => true), array('from' => 'ldap_opt_deref', 'to' => 'deref_option', 'default' => 0, 'noindex' => true), array('from' => 'timezone', 'to' => 'time_offset', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds')), 'glpi_authldapreplicates' => array(array('from' => 'ldap_port', 'to' => 'port', 'default' => 389, 'noindex' => true, 'checkdatas' => true)), 'glpi_bookmarks' => array(array('from' => 'type', 'to' => 'type', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php BOOKMARK_* constant')), 'glpi_cartridgeitems' => array(array('from' => 'alarm', 'to' => 'alarm_threshold', 'default' => 10)), 'glpi_configs' => array(array('from' => 'glpi_timezone', 'to' => 'time_offset', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'cartridges_alarm', 'to' => 'default_alarm_threshold', 'default' => 10, 'noindex' => true), array('from' => 'event_loglevel', 'to' => 'event_loglevel', 'default' => 5, 'noindex' => true), array('from' => 'cas_port', 'to' => 'cas_port', 'default' => 443, 'noindex' => true, 'checkdatas' => true), array('from' => 'auto_update_check', 'to' => 'auto_update_check', 'default' => 0, 'noindex' => true), array('from' => 'dateformat', 'to' => 'date_format', 'default' => 0, 'noindex' => true), array('from' => 'numberformat', 'to' => 'number_format', 'default' => 0, 'noindex' => true), array('from' => 'proxy_port', 'to' => 'proxy_port', 'default' => 8080, 'noindex' => true, 'checkdatas' => true), array('from' => 'contract_alerts', 'to' => 'default_contract_alert', 'default' => 0, 'noindex' => true), array('from' => 'infocom_alerts', 'to' => 'default_infocom_alert', 'default' => 0, 'noindex' => true), array('from' => 'cartridges_alert', 'to' => 'cartridges_alert_repeat', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'consumables_alert', 'to' => 'consumables_alert_repeat', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'monitors_management_restrict', 'to' => 'monitors_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'phones_management_restrict', 'to' => 'phones_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'peripherals_management_restrict', 'to' => 'peripherals_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'printers_management_restrict', 'to' => 'printers_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'autoupdate_link_state', 'to' => 'state_autoupdate_mode', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_state', 'to' => 'state_autoclean_mode', 'default' => 0, 'noindex' => true), array('from' => 'name_display_order', 'to' => 'names_format', 'default' => 0, 'noindex' => true, 'comments' => 'see *NAME_BEFORE constant in define.php'), array('from' => 'dropdown_limit', 'to' => 'dropdown_chars_limit', 'default' => 50, 'noindex' => true), array('from' => 'smtp_mode', 'to' => 'smtp_mode', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php MAIL_* constant'), array('from' => 'mailgate_filesize_max', 'to' => 'default_mailcollector_filesize_max', 'default' => 2097152, 'noindex' => true)), 'glpi_consumableitems' => array(array('from' => 'alarm', 'to' => 'alarm_threshold', 'default' => 10)), 'glpi_contracts' => array(array('from' => 'duration', 'to' => 'duration', 'default' => 0, 'noindex' => true), array('from' => 'notice', 'to' => 'notice', 'default' => 0, 'noindex' => true), array('from' => 'periodicity', 'to' => 'periodicity', 'default' => 0, 'noindex' => true), array('from' => 'facturation', 'to' => 'billing', 'default' => 0, 'noindex' => true), array('from' => 'device_countmax', 'to' => 'max_links_allowed', 'default' => 0, 'noindex' => true), array('from' => 'alert', 'to' => 'alert', 'default' => 0), array('from' => 'renewal', 'to' => 'renewal', 'default' => 0, 'noindex' => true)), 'glpi_displaypreferences' => array(array('from' => 'num', 'to' => 'num', 'default' => 0), array('from' => 'rank', 'to' => 'rank', 'default' => 0)), 'glpi_events' => array(array('from' => 'level', 'to' => 'level', 'default' => 0)), 'glpi_infocoms' => array(array('from' => 'warranty_duration', 'to' => 'warranty_duration', 'default' => 0, 'noindex' => true), array('from' => 'amort_time', 'to' => 'sink_time', 'default' => 0, 'noindex' => true), array('from' => 'amort_type', 'to' => 'sink_type', 'default' => 0, 'noindex' => true), array('from' => 'alert', 'to' => 'alert', 'default' => 0)), 'glpi_mailingsettings' => array(array('from' => 'item_type', 'to' => 'mailingtype', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php *_MAILING_TYPE constant')), 'glpi_monitors' => array(array('from' => 'size', 'to' => 'size', 'default' => 0, 'noindex' => true)), 'glpi_printers' => array(array('from' => 'initial_pages', 'to' => 'init_pages_counter', 'default' => 0, 'noindex' => true, 'checkdatas' => true)), 'glpi_profiles' => array(array('from' => 'helpdesk_hardware', 'to' => 'helpdesk_hardware', 'default' => 0, 'noindex' => true)), 'glpi_plugins' => array(array('from' => 'state', 'to' => 'state', 'default' => 0, 'comments' => 'see define.php PLUGIN_* constant')), 'glpi_reminders' => array(array('from' => 'state', 'to' => 'state', 'default' => 0)), 'glpi_ticketplannings' => array(array('from' => 'state', 'to' => 'state', 'default' => 1)), 'glpi_rulecriterias' => array(array('from' => 'condition', 'to' => 'condition', 'default' => 0, 'comments' => 'see define.php PATTERN_* and REGEX_* constant')), 'glpi_rules' => array(array('from' => 'sub_type', 'to' => 'sub_type', 'default' => 0, 'comments' => 'see define.php RULE_* constant')), 'glpi_tickets' => array(array('from' => 'request_type', 'to' => 'request_type', 'default' => 0, 'noindex' => true), array('from' => 'priority', 'to' => 'priority', 'default' => 1, 'noindex' => true)), 'glpi_transfers' => array(array('from' => 'keep_tickets', 'to' => 'keep_ticket', 'default' => 0, 'noindex' => true), array('from' => 'keep_networklinks', 'to' => 'keep_networklink', 'default' => 0, 'noindex' => true), array('from' => 'keep_reservations', 'to' => 'keep_reservation', 'default' => 0, 'noindex' => true), array('from' => 'keep_history', 'to' => 'keep_history', 'default' => 0, 'noindex' => true), array('from' => 'keep_devices', 'to' => 'keep_device', 'default' => 0, 'noindex' => true), array('from' => 'keep_infocoms', 'to' => 'keep_infocom', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_monitor', 'to' => 'keep_dc_monitor', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_monitor', 'to' => 'clean_dc_monitor', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_phone', 'to' => 'keep_dc_phone', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_phone', 'to' => 'clean_dc_phone', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_peripheral', 'to' => 'keep_dc_peripheral', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_peripheral', 'to' => 'clean_dc_peripheral', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_printer', 'to' => 'keep_dc_printer', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_printer', 'to' => 'clean_dc_printer', 'default' => 0, 'noindex' => true), array('from' => 'keep_enterprises', 'to' => 'keep_supplier', 'default' => 0, 'noindex' => true), array('from' => 'clean_enterprises', 'to' => 'clean_supplier', 'default' => 0, 'noindex' => true), array('from' => 'keep_contacts', 'to' => 'keep_contact', 'default' => 0, 'noindex' => true), array('from' => 'clean_contacts', 'to' => 'clean_contact', 'default' => 0, 'noindex' => true), array('from' => 'keep_contracts', 'to' => 'keep_contract', 'default' => 0, 'noindex' => true), array('from' => 'clean_contracts', 'to' => 'clean_contract', 'default' => 0, 'noindex' => true), array('from' => 'keep_softwares', 'to' => 'keep_software', 'default' => 0, 'noindex' => true), array('from' => 'clean_softwares', 'to' => 'clean_software', 'default' => 0, 'noindex' => true), array('from' => 'keep_documents', 'to' => 'keep_document', 'default' => 0, 'noindex' => true), array('from' => 'clean_documents', 'to' => 'clean_document', 'default' => 0, 'noindex' => true), array('from' => 'keep_cartridges_type', 'to' => 'keep_cartridgeitem', 'default' => 0, 'noindex' => true), array('from' => 'clean_cartridges_type', 'to' => 'clean_cartridgeitem', 'default' => 0, 'noindex' => true), array('from' => 'keep_cartridges', 'to' => 'keep_cartridge', 'default' => 0, 'noindex' => true), array('from' => 'keep_consumables', 'to' => 'keep_consumable', 'default' => 0, 'noindex' => true)), 'glpi_users' => array(array('from' => 'dateformat', 'to' => 'date_format', 'default' => NULL, 'noindex' => true, 'maybenull' => true), array('from' => 'numberformat', 'to' => 'number_format', 'default' => NULL, 'noindex' => true, 'maybenull' => true), array('from' => 'use_mode', 'to' => 'use_mode', 'default' => 0, 'noindex' => true), array('from' => 'dropdown_limit', 'to' => 'dropdown_chars_limit', 'default' => NULL, 'maybenull' => true, 'noindex' => true))); foreach ($intfields as $table => $tab) { foreach ($tab as $update) { $newname = $update['to']; $oldname = $update['from']; $doindex = true; if (isset($update['noindex']) && $update['noindex']) { $doindex = false; } $default = "DEFAULT NULL"; if (isset($update['default']) && !is_null($update['default'])) { $default = "DEFAULT " . $update['default'] . ""; } $NULL = "NOT NULL"; if (isset($update['maybenull']) && $update['maybenull']) { $NULL = "NULL"; } $check_datas = false; if (isset($update['checkdatas'])) { $check_datas = $update['checkdatas']; } $addcomment = ""; if (isset($update['comments'])) { $addcomment = "COMMENT '" . $update['comments'] . "'"; } // Rename field if (FieldExists($table, $oldname, false)) { if ($check_datas) { $query = "SELECT `id`, `{$oldname}`\n FROM `{$table}`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { if (empty($data[$oldname]) && isset($update['default'])) { $data[$oldname] = $update['default']; } $query = "UPDATE `{$table}`\n SET `{$oldname}` = '" . intval($data[$oldname]) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->query($query); } } } } $changes[$table][] = "CHANGE `{$oldname}` `{$newname}` INT( 11 ) {$NULL} {$default} {$addcomment}"; } else { $updateresult = false; $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true); } // If do index : delete old one / create new one if ($doindex) { if (!isIndex($table, $newname)) { $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)"; } if ($newname != $oldname && isIndex($table, $oldname)) { $changes[$table][] = "DROP INDEX `{$oldname}`"; } } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: others field changes')); if (FieldExists('glpi_alerts', 'date', false)) { $changes['glpi_alerts'][] = "CHANGE `date` `date` DATETIME NOT NULL"; } if (FieldExists('glpi_configs', 'date_fiscale', false)) { $changes['glpi_configs'][] = "CHANGE `date_fiscale` `date_tax` DATE NOT NULL\n DEFAULT '2005-12-31'"; } if (FieldExists('glpi_configs', 'sendexpire', false)) { $changes['glpi_configs'][] = "DROP `sendexpire`"; } if (FieldExists('glpi_configs', 'show_admin_doc', false)) { $changes['glpi_configs'][] = "DROP `show_admin_doc`"; } if (FieldExists('glpi_configs', 'licenses_management_restrict', false)) { $changes['glpi_configs'][] = "DROP `licenses_management_restrict`"; } if (FieldExists('glpi_configs', 'nextprev_item', false)) { $changes['glpi_configs'][] = "DROP `nextprev_item`"; } if (FieldExists('glpi_configs', 'logotxt', false)) { $changes['glpi_configs'][] = "DROP `logotxt`"; } if (FieldExists('glpi_configs', 'num_of_events', false)) { $changes['glpi_configs'][] = "DROP `num_of_events`"; } if (FieldExists('glpi_configs', 'tracking_order', false)) { $changes['glpi_configs'][] = "DROP `tracking_order`"; } if (FieldExists('glpi_contracts', 'bill_type', false)) { $changes['glpi_contracts'][] = "DROP `bill_type`"; } if (FieldExists('glpi_infocoms', 'amort_coeff', false)) { $changes['glpi_infocoms'][] = "CHANGE `amort_coeff` `sink_coeff` FLOAT NOT NULL DEFAULT '0'"; } if (FieldExists('glpi_ocsservers', 'import_software_comments', false)) { $changes['glpi_ocsservers'][] = "DROP `import_software_comments`"; } if (FieldExists('glpi_users', 'nextprev_item', false)) { $changes['glpi_users'][] = "DROP `nextprev_item`"; } if (FieldExists('glpi_users', 'num_of_events', false)) { $changes['glpi_users'][] = "DROP `num_of_events`"; } if (FieldExists('glpi_users', 'tracking_order', false)) { $changes['glpi_users'][] = "DROP `tracking_order`"; } if (FieldExists('glpi_rulerightparameters', 'sub_type', false)) { $changes['glpi_rulerightparameters'][] = "DROP `sub_type`"; } if (FieldExists('glpi_softwares', 'oldstate', false)) { $changes['glpi_softwares'][] = "DROP `oldstate`"; } if (FieldExists('glpi_users', 'password', false)) { $changes['glpi_users'][] = "DROP `password`"; } if (FieldExists('glpi_users', 'password_md5', false)) { $changes['glpi_users'][] = "CHANGE `password_md5` `password` CHAR( 40 ) NULL DEFAULT NULL"; } if (!FieldExists('glpi_mailcollectors', 'filesize_max', false)) { $changes['glpi_mailcollectors'][] = "ADD `filesize_max` INT(11) NOT NULL DEFAULT 2097152"; } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: index management')); if (!isIndex('glpi_alerts', 'unicity')) { $changes['glpi_alerts'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`, `type`)"; } if (!isIndex('glpi_cartridges_printermodels', 'unicity')) { $changes['glpi_cartridges_printermodels'][] = "ADD UNIQUE `unicity` (`printermodels_id`,\n `cartridgeitems_id`)"; } if (!isIndex('glpi_computers_items', 'unicity')) { $changes['glpi_computers_items'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`,\n `computers_id`)"; } if (!isIndex('glpi_contacts_suppliers', 'unicity')) { $changes['glpi_contacts_suppliers'][] = "ADD UNIQUE `unicity` (`suppliers_id`, `contacts_id`)"; } if (!isIndex('glpi_contracts_items', 'unicity')) { $changes['glpi_contracts_items'][] = "ADD UNIQUE `unicity` (`contracts_id`, `itemtype`,\n `items_id`)"; } if (!isIndex('glpi_contracts_items', 'item')) { $changes['glpi_contracts_items'][] = "ADD INDEX `item` (`itemtype`, `items_id`)"; } if (!isIndex('glpi_contracts_suppliers', 'unicity')) { $changes['glpi_contracts_suppliers'][] = "ADD UNIQUE `unicity` (`suppliers_id`, `contracts_id`)"; } if (!isIndex('glpi_displaypreferences', 'unicity')) { $changes['glpi_displaypreferences'][] = "ADD UNIQUE `unicity` (`users_id`, `itemtype`, `num`)"; } if (!isIndex('glpi_bookmarks_users', 'unicity')) { $changes['glpi_bookmarks_users'][] = "ADD UNIQUE `unicity` (`users_id`, `itemtype`)"; } if (!isIndex('glpi_documents_items', 'unicity')) { $changes['glpi_documents_items'][] = "ADD UNIQUE `unicity` (`documents_id`, `itemtype`,\n `items_id`)"; } if (!isIndex('glpi_documents_items', 'item')) { $changes['glpi_documents_items'][] = "ADD INDEX `item` (`itemtype`, `items_id`)"; } if (!isIndex('glpi_knowbaseitemcategories', 'unicity')) { $changes['glpi_knowbaseitemcategories'][] = "ADD UNIQUE `unicity` (`knowbaseitemcategories_id`,\n `name`)"; } if (!isIndex('glpi_locations', 'unicity')) { $changes['glpi_locations'][] = "ADD UNIQUE `unicity` (`entities_id`, `locations_id`, `name`)"; } if (isIndex('glpi_locations', 'name')) { $changes['glpi_locations'][] = "DROP INDEX `name` "; } if (!isIndex('glpi_netpoints', 'complete')) { $changes['glpi_netpoints'][] = "ADD INDEX `complete` (`entities_id`, `locations_id`, `name`)"; } if (!isIndex('glpi_netpoints', 'location_name')) { $changes['glpi_netpoints'][] = "ADD INDEX `location_name` (`locations_id`, `name`)"; } if (!isIndex('glpi_entities', 'unicity')) { $changes['glpi_entities'][] = "ADD UNIQUE `unicity` (`entities_id`, `name`)"; } if (!isIndex('glpi_entitydatas', 'unicity')) { $changes['glpi_entitydatas'][] = "ADD UNIQUE `unicity` (`entities_id`)"; } if (!isIndex('glpi_events', 'item')) { $changes['glpi_events'][] = "ADD INDEX `item` (`type`, `items_id`)"; } if (!isIndex('glpi_infocoms', 'unicity')) { $changes['glpi_infocoms'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`)"; } if (!isIndex('glpi_knowbaseitems', 'date_mod')) { $changes['glpi_knowbaseitems'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_networkequipments', 'date_mod')) { $changes['glpi_networkequipments'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_links_itemtypes', 'unicity')) { $changes['glpi_links_itemtypes'][] = "ADD UNIQUE `unicity` (`itemtype`, `links_id`)"; } if (!isIndex('glpi_mailingsettings', 'unicity')) { $changes['glpi_mailingsettings'][] = "ADD UNIQUE `unicity` (`type`, `items_id`, `mailingtype`)"; } if (!isIndex('glpi_networkports', 'item')) { $changes['glpi_networkports'][] = "ADD INDEX `item` (`itemtype`, `items_id`)"; } if (!isIndex('glpi_networkports_vlans', 'unicity')) { $changes['glpi_networkports_vlans'][] = "ADD UNIQUE `unicity` (`networkports_id`, `vlans_id`)"; } if (!isIndex('glpi_networkports_networkports', 'unicity')) { $changes['glpi_networkports_networkports'][] = "ADD UNIQUE `unicity` (`networkports_id_1`,\n `networkports_id_2`)"; } if (!isIndex('glpi_ocslinks', 'unicity')) { $changes['glpi_ocslinks'][] = "ADD UNIQUE `unicity` (`ocsservers_id`, `ocsid`)"; } if (!isIndex('glpi_peripherals', 'date_mod')) { $changes['glpi_peripherals'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_phones', 'date_mod')) { $changes['glpi_phones'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_plugins', 'unicity')) { $changes['glpi_plugins'][] = "ADD UNIQUE `unicity` (`directory`)"; } if (!isIndex('glpi_printers', 'date_mod')) { $changes['glpi_printers'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_reminders', 'date_mod')) { $changes['glpi_reminders'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_reservationitems', 'item')) { $changes['glpi_reservationitems'][] = "ADD INDEX `item` (`itemtype`, `items_id`)"; } if (!isIndex('glpi_tickets', 'item')) { $changes['glpi_tickets'][] = "ADD INDEX `item` (`itemtype`, `items_id`)"; } if (!isIndex('glpi_documenttypes', 'date_mod')) { $changes['glpi_documenttypes'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_documenttypes', 'unicity')) { $changes['glpi_documenttypes'][] = "ADD UNIQUE `unicity` (`ext`)"; } if (!isIndex('glpi_users', 'unicity')) { $changes['glpi_users'][] = "ADD UNIQUE `unicity` (`name`)"; } if (!isIndex('glpi_users', 'date_mod')) { $changes['glpi_users'][] = "ADD INDEX `date_mod` (`date_mod`)"; } if (!isIndex('glpi_users', 'authitem')) { $changes['glpi_users'][] = "ADD INDEX `authitem` (`authtype`, `auths_id`)"; } if (!isIndex('glpi_groups_users', 'unicity')) { $changes['glpi_groups_users'][] = "ADD UNIQUE `unicity` (`users_id`, `groups_id`)"; } $indextodrop = array('glpi_alerts' => array('alert', 'FK_device'), 'glpi_cartridges_printermodels' => array('FK_glpi_type_printer'), 'glpi_computers_items' => array('connect', 'type', 'end1', 'end1_2'), 'glpi_consumables' => array('FK_glpi_cartridges_type'), 'glpi_contacts_suppliers' => array('FK_enterprise'), 'glpi_contracts_items' => array('FK_contract_device', 'device_type'), 'glpi_contracts_suppliers' => array('FK_enterprise'), 'glpi_displaypreferences' => array('display', 'FK_users'), 'glpi_bookmarks_users' => array('FK_users'), 'glpi_documents_items' => array('FK_doc_device', 'device_type', 'FK_device'), 'glpi_knowbaseitemcategories' => array('parentID_2', 'parentID'), 'glpi_locations' => array('FK_entities'), 'glpi_netpoints' => array('FK_entities', 'location'), 'glpi_entities' => array('name'), 'glpi_entitydatas' => array('FK_entities'), 'glpi_events' => array('comp', 'itemtype'), 'glpi_infocoms' => array('FK_device'), 'glpi_computers_softwareversions' => array('sID'), 'glpi_links_itemtypes' => array('link'), 'glpi_mailingsettings' => array('mailings', 'FK_item'), 'glpi_networkports' => array('device_type'), 'glpi_networkports_vlans' => array('portvlan'), 'glpi_networkports_networkports' => array('netwire', 'end1', 'end1_2'), 'glpi_ocslinks' => array('ocs_server_id'), 'glpi_plugins' => array('name'), 'glpi_reservationitems' => array('reservationitem'), 'glpi_tickets' => array('computer', 'device_type'), 'glpi_documenttypes' => array('extension'), 'glpi_users' => array('name'), 'glpi_groups_users' => array('usergroup')); foreach ($indextodrop as $table => $tab) { foreach ($tab as $indexname) { if (isIndex($table, $indexname)) { $changes[$table][] = "DROP INDEX `{$indexname}`"; } } } foreach ($changes as $table => $tab) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $table)); $query = "ALTER TABLE `{$table}`\n " . implode($tab, " ,\n") . ";"; $DB->queryOrDie($query, "0.78 multiple alter in {$table}"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Update itemtype fields')); // Convert itemtype to Class names $typetoname = array(GENERAL_TYPE => "", COMPUTER_TYPE => "Computer", NETWORKING_TYPE => "NetworkEquipment", PRINTER_TYPE => "Printer", MONITOR_TYPE => "Monitor", PERIPHERAL_TYPE => "Peripheral", SOFTWARE_TYPE => "Software", CONTACT_TYPE => "Contact", ENTERPRISE_TYPE => "Supplier", INFOCOM_TYPE => "Infocom", CONTRACT_TYPE => "Contract", CARTRIDGEITEM_TYPE => "CartridgeItem", TYPEDOC_TYPE => "DocumentType", DOCUMENT_TYPE => "Document", KNOWBASE_TYPE => "KnowbaseItem", USER_TYPE => "User", TRACKING_TYPE => "Ticket", CONSUMABLEITEM_TYPE => "ConsumableItem", CONSUMABLE_TYPE => "Consumable", CARTRIDGE_TYPE => "Cartridge", SOFTWARELICENSE_TYPE => "SoftwareLicense", LINK_TYPE => "Link", STATE_TYPE => "States", PHONE_TYPE => "Phone", DEVICE_TYPE => "Device", REMINDER_TYPE => "Reminder", STAT_TYPE => "Stat", GROUP_TYPE => "Group", ENTITY_TYPE => "Entity", RESERVATION_TYPE => "ReservationItem", AUTHMAIL_TYPE => "AuthMail", AUTHLDAP_TYPE => "AuthLDAP", OCSNG_TYPE => "OcsServer", REGISTRY_TYPE => "RegistryKey", PROFILE_TYPE => "Profile", MAILGATE_TYPE => "MailCollector", RULE_TYPE => "Rule", TRANSFER_TYPE => "Transfer", BOOKMARK_TYPE => "Bookmark", SOFTWAREVERSION_TYPE => "SoftwareVersion", PLUGIN_TYPE => "Plugin", COMPUTERDISK_TYPE => "ComputerDisk", NETWORKING_PORT_TYPE => "NetworkPort", FOLLOWUP_TYPE => "TicketFollowup", BUDGET_TYPE => "Budget"); // End is not used in 0.72.x $devtypetoname = array(MOBOARD_DEVICE => 'DeviceMotherboard', PROCESSOR_DEVICE => 'DeviceProcessor', RAM_DEVICE => 'DeviceMemory', HDD_DEVICE => 'DeviceHardDrive', NETWORK_DEVICE => 'DeviceNetworkCard', DRIVE_DEVICE => 'DeviceDrive', CONTROL_DEVICE => 'DeviceControl', GFX_DEVICE => 'DeviceGraphicCard', SND_DEVICE => 'DeviceSoundCard', PCI_DEVICE => 'DevicePci', CASE_DEVICE => 'DeviceCase', POWER_DEVICE => 'DevicePowerSupply'); $itemtype_tables = array("glpi_alerts", "glpi_bookmarks", "glpi_bookmarks_users", "glpi_computers_items", "glpi_contracts_items", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_links_itemtypes", "glpi_networkports", "glpi_reservationitems", "glpi_tickets"); foreach ($itemtype_tables as $table) { $migration->displayMessage(sprintf(__('Data migration - %s'), "{$table}")); // Updating data // Alter itemtype field $query = "ALTER TABLE `{$table}`\n CHANGE `itemtype` `itemtype` VARCHAR( 100 ) NOT NULL"; $DB->queryOrDie($query, "0.78 alter itemtype of table {$table}"); // Update values foreach ($typetoname as $key => $val) { $query = "UPDATE `{$table}`\n SET `itemtype` = '{$val}'\n WHERE `itemtype` = '{$key}'"; $DB->queryOrDie($query, "0.78 update itemtype of table {$table} for {$val}"); } } if (FieldExists('glpi_logs', 'device_type', false)) { // History migration, handled separatly for optimization $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_logs - 1')); $query = "ALTER TABLE `glpi_logs`\n CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT,\n ADD `itemtype` VARCHAR(100) NOT NULL DEFAULT '' AFTER `device_type`,\n ADD `items_id` INT( 11 ) NOT NULL DEFAULT '0' AFTER `itemtype`,\n ADD `itemtype_link` VARCHAR(100) NOT NULL DEFAULT '' AFTER `device_internal_type`,\n CHANGE `linked_action` `linked_action` INT( 11 ) NOT NULL DEFAULT '0'\n COMMENT 'see define.php HISTORY_* constant'"; $DB->queryOrDie($query, "0.78 add item* fields to table glpi_logs"); // Update values $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_logs')); // Copy data $query = "UPDATE `glpi_logs`\n SET `itemtype` = `device_type`,\n `items_id` = `FK_glpi_device`,\n `itemtype_link` = `device_internal_type`"; $DB->queryOrDie($query, "0.78 update glpi_logs default values"); foreach ($typetoname as $key => $val) { $query = "UPDATE `glpi_logs`\n SET `itemtype` = '{$val}'\n WHERE `device_type` = '{$key}'"; $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}"); $query = "UPDATE `glpi_logs`\n SET `itemtype_link` = '{$val}'\n WHERE `device_internal_type` = '{$key}'\n AND `linked_action` IN (" . Log::HISTORY_ADD_RELATION . ",\n " . Log::HISTORY_DEL_RELATION . ",\n " . Log::HISTORY_DISCONNECT_DEVICE . ",\n " . Log::HISTORY_CONNECT_DEVICE . ")"; $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}"); } foreach ($devtypetoname as $key => $val) { $query = "UPDATE `glpi_logs`\n SET `itemtype_link` = '{$val}'\n WHERE `device_internal_type` = '{$key}'\n AND `linked_action` IN (" . Log::HISTORY_ADD_DEVICE . ",\n " . Log::HISTORY_UPDATE_DEVICE . ",\n " . Log::HISTORY_DELETE_DEVICE . ")"; $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}"); } // Clean link $query = "UPDATE `glpi_logs`\n SET `itemtype_link` = ''\n WHERE `itemtype_link` = '0'"; $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_logs - 2')); $query = "ALTER TABLE `glpi_logs`\n DROP `device_type`,\n DROP `FK_glpi_device`,\n DROP `device_internal_type`,\n ADD INDEX `itemtype_link` (`itemtype_link`),\n ADD INDEX `item` (`itemtype`,`items_id`)"; $DB->queryOrDie($query, "0.78 drop device* fields to table glpi_logs"); } // Update glpi_profiles item_type $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: post actions after renaming')); if (!isIndex('glpi_locations', 'name')) { $query = " ALTER TABLE `glpi_locations`\n ADD INDEX `name` (`name`)"; $DB->queryOrDie($query, "0.78 add name index in glpi_locations"); } // Update values of mailcollectors $query = "SELECT `default_mailcollector_filesize_max`\n FROM `glpi_configs`\n WHERE `id` = 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $query = "UPDATE `glpi_mailcollectors`\n SET `filesize_max` = '" . $DB->result($result, 0, 0) . "';"; $DB->query($query); } } // For compatiblity with updates from past versions regenerateTreeCompleteName("glpi_locations"); regenerateTreeCompleteName("glpi_knowbaseitemcategories"); regenerateTreeCompleteName("glpi_ticketcategories"); // Update timezone values if (FieldExists('glpi_configs', 'time_offset', false)) { $query = "UPDATE `glpi_configs`\n SET `time_offset` = `time_offset`*3600"; $DB->queryOrDie($query, "0.78 update time_offset value in glpi_configs"); } if (FieldExists('glpi_authldaps', 'time_offset', false)) { $query = "UPDATE `glpi_authldaps`\n SET `time_offset` = `time_offset`*3600"; $DB->queryOrDie($query, "0.78 update time_offset value in glpi_authldaps"); } // Change defaults store values : if (FieldExists('glpi_softwares', 'sofwtares_id', false)) { $query = "UPDATE `glpi_softwares`\n SET `sofwtares_id` = 0\n WHERE `sofwtares_id` < 0"; $DB->queryOrDie($query, "0.78 update default value of sofwtares_id in glpi_softwares"); } if (FieldExists('glpi_users', 'authtype', false)) { $query = "UPDATE `glpi_users`\n SET `authtype` = 0\n WHERE `authtype` < 0"; $DB->queryOrDie($query, "0.78 update default value of authtype in glpi_users"); } if (FieldExists('glpi_users', 'auths_id', false)) { $query = "UPDATE `glpi_users`\n SET `auths_id` = 0\n WHERE `auths_id` < 0"; $DB->queryOrDie($query, "0.78 update default value of auths_id in glpi_users"); } // Update glpi_ocsadmininfoslinks table for new field name if (FieldExists('glpi_ocsadmininfoslinks', 'glpi_column', false)) { $query = "UPDATE `glpi_ocsadmininfoslinks`\n SET `glpi_column` = 'locations_id'\n WHERE `glpi_column` = 'location'"; $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks"); $query = "UPDATE `glpi_ocsadmininfoslinks`\n SET `glpi_column` = 'networks_id'\n WHERE `glpi_column` = 'network'"; $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks"); $query = "UPDATE `glpi_ocsadmininfoslinks`\n SET `glpi_column` = 'groups_id'\n WHERE `glpi_column` = 'FK_groups'"; $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks"); } // Update bookmarks for new columns fields if (FieldExists('glpi_bookmarks', 'is_private', false)) { $query = "UPDATE `glpi_bookmarks`\n SET `entities_id` = -1\n WHERE `is_private` = 1"; $DB->queryOrDie($query, "0.78 update value of entities_id in glpi_bookmarks"); } if (FieldExists('glpi_reminders', 'is_private', false)) { $query = "UPDATE `glpi_reminders`\n SET `entities_id` = -1\n WHERE `is_private` = 1"; $DB->queryOrDie($query, "0.78 update value of entities_id in glpi_reminders"); } // Update bookmarks for new columns fields if (FieldExists('glpi_bookmarks', 'query', false)) { // All search $olds = array("deleted"); $news = array("is_deleted"); foreach ($olds as $key => $val) { $olds[$key] = "/&{$val}=/"; } foreach ($news as $key => $val) { $news[$key] = "/&{$val}=/"; } // Manage meta search foreach ($typetoname as $key => $val) { $olds[$key] = "/&type2\\[(\\d+)\\]={$key}/"; $news[$key] = "&itemtype2[\\1]={$val}"; } $query = "SELECT `id`, `query`\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)) { $query2 = "UPDATE `glpi_bookmarks`\n SET `query` = '" . addslashes(preg_replace($olds, $news, $data['query'])) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->queryOrDie($query2, "0.78 update all bookmarks"); } } } // Update bookmarks due to FHS change $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/documenttype.php'\n WHERE `path` = 'front/typedoc.php'"; $DB->queryOrDie($query2, "0.78 update typedoc bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/consumableitem.php'\n WHERE `path` = 'front/consumable.php'"; $DB->queryOrDie($query2, "0.78 update consumable bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/cartridgeitem.php'\n WHERE `path` = 'front/cartridge.php'"; $DB->queryOrDie($query2, "0.78 update cartridge bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/ticket.php'\n WHERE `path` = 'front/tracking.php'"; $DB->queryOrDie($query2, "0.78 update ticket bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/mailcollector.php'\n WHERE `path` = 'front/mailgate.php'"; $DB->queryOrDie($query2, "0.78 update mailcollector bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/ocsserver.php'\n WHERE `path` = 'front/setup.ocsng.php'"; $DB->queryOrDie($query2, "0.78 update ocsserver bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/supplier.php'\n WHERE `path` = 'front/enterprise.php'"; $DB->queryOrDie($query2, "0.78 update supplier bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/networkequipment.php'\n WHERE `path` = 'front/networking.php'"; $DB->queryOrDie($query2, "0.78 update networkequipment bookmarks"); $query2 = "UPDATE `glpi_bookmarks`\n SET `path` = 'front/states.php'\n WHERE `path` = 'front/state.php'"; $DB->queryOrDie($query2, "0.78 update states bookmarks"); } //// Upgrade rules datas $changes = array(); // For Rule::RULE_AFFECT_RIGHTS $changes[1] = array('FK_entities' => 'entities_id', 'FK_profiles' => 'profiles_id', 'recursive' => 'is_recursive', 'active' => 'is_active'); // For Rule::RULE_DICTIONNARY_SOFTWARE $changes[4] = array('helpdesk_visible ' => 'is_helpdesk_visible'); // For Rule::RULE_OCS_AFFECT_COMPUTER $changes[0] = array('FK_entities' => 'entities_id'); // For Rule::RULE_SOFTWARE_CATEGORY $changes[3] = array('category' => 'softwarecategories_id', 'comment' => 'comment'); // For Rule::RULE_TRACKING_AUTO_ACTION $changes[2] = array('category' => 'ticketcategories_id', 'author' => 'users_id', 'author_location' => 'users_locations', 'FK_group' => 'groups_id', 'assign' => 'users_id_assign', 'assign_group' => 'groups_id_assign', 'device_type' => 'itemtype', 'FK_entities' => 'entities_id', 'contents' => 'content', 'request_type' => 'requesttypes_id'); $DB->query("SET SESSION group_concat_max_len = 9999999;"); 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.78 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.78 update datas for rules criterias"); } } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_rulecachesoftwares')); $query = "ALTER TABLE `glpi_rules`\n CHANGE `sub_type` `sub_type` VARCHAR( 255 ) NOT NULL DEFAULT ''"; $DB->queryOrDie($query, "0.78 change subtype from INT(11) to VARCHAR(255) in glpi_rules"); $subtypes = array(0 => 'RuleOcs', 1 => 'RuleRight', 2 => 'RuleTicket', 3 => 'RuleSoftwareCategory', 4 => 'RuleDictionnarySoftware', 5 => 'RuleDictionnaryManufacturer', 6 => 'RuleDictionnaryComputerModel', 7 => 'RuleDictionnaryComputerType', 8 => 'RuleDictionnaryMonitorModel', 9 => 'RuleDictionnaryMonitorType', 10 => 'RuleDictionnaryPrinterModel', 11 => 'RuleDictionnaryPrinterType', 12 => 'RuleDictionnaryPhoneModel', 13 => 'RuleDictionnaryPhoneType', 14 => 'RuleDictionnaryPeripheralModel', 15 => 'RuleDictionnaryPeripheralType', 16 => 'RuleDictionnaryNetworkEquipmentModel', 17 => 'RuleDictionnaryNetworkEquipmentType', 18 => 'RuleDictionnaryOperatingSystem', 19 => 'RuleDictionnaryOperatingSystemServicePack', 20 => 'RuleDictionnaryOperatingSystemVersion', 21 => 'RuleMailCollector'); foreach ($subtypes as $old_subtype => $new_subtype) { $query = "UPDATE `glpi_rules`\n SET `sub_type` = '{$new_subtype}'\n WHERE `sub_type` = '{$old_subtype}'"; $DB->queryOrDie($query, "0.78 change sub_type {$old_subtype} in {$new_subtype} in glpi_rules"); } $DB->queryOrDie($query, "0.78 update itemtypes in business rules"); //Update business rules itemtypes foreach ($typetoname as $key => $val) { if ($key != GENERAL_TYPE) { $query = "UPDATE `glpi_rulecriterias`\n SET `pattern` = '{$val}'\n WHERE `pattern` = '{$key}'\n AND `criteria` = 'itemtype'"; $DB->queryOrDie($query, "0.78 update itemtype for business rules for {$val}"); } } if (FieldExists("glpi_rulecachesoftwares", "ignore_ocs_import", false)) { $query = "ALTER TABLE `glpi_rulecachesoftwares`\n CHANGE `ignore_ocs_import` `ignore_ocs_import` CHAR( 1 ) NULL DEFAULT NULL "; $DB->queryOrDie($query, "0.78 alter table glpi_rulecachesoftwares"); } if (!FieldExists("glpi_rulecachesoftwares", "is_helpdesk_visible", false)) { $query = "ALTER TABLE `glpi_rulecachesoftwares`\n ADD `is_helpdesk_visible` CHAR( 1 ) NULL "; $DB->queryOrDie($query, "0.78 add is_helpdesk_visible in glpi_rulecachesoftwares"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_entities')); if (!FieldExists("glpi_entities", "sons_cache", false)) { $query = "ALTER TABLE `glpi_entities`\n ADD `sons_cache` LONGTEXT NULL ; "; $DB->queryOrDie($query, "0.78 add sons_cache field in glpi_entities"); } if (!FieldExists("glpi_entities", "ancestors_cache", false)) { $query = "ALTER TABLE `glpi_entities`\n ADD `ancestors_cache` LONGTEXT NULL ; "; $DB->queryOrDie($query, "0.78 add ancestors_cache field in glpi_entities"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_configs')); if (!FieldExists("glpi_configs", "default_graphtype", false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `default_graphtype` char( 3 ) NOT NULL DEFAULT 'svg'"; $DB->queryOrDie($query, "0.78 add default_graphtype in glpi_configs"); } if (FieldExists('glpi_configs', 'license_deglobalisation', false)) { $query = "ALTER TABLE `glpi_configs`\n DROP `license_deglobalisation`;"; $DB->queryOrDie($query, "0.78 alter clean glpi_configs table"); } if (FieldExists("glpi_configs", "use_cache", false)) { $query = "ALTER TABLE `glpi_configs`\n DROP `use_cache`;"; $DB->queryOrDie($query, "0.78 drop use_cache in glpi_configs"); } if (FieldExists("glpi_configs", "cache_max_size", false)) { $query = "ALTER TABLE `glpi_configs`\n DROP `cache_max_size`;"; $DB->queryOrDie($query, "0.78 drop cache_max_size in glpi_configs"); } if (!FieldExists("glpi_configs", "default_request_type", false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `default_request_type` INT( 11 ) NOT NULL DEFAULT 1"; $DB->queryOrDie($query, "0.78 add default_request_type in glpi_configs"); } if (!FieldExists("glpi_users", "default_request_type", false)) { $query = "ALTER TABLE `glpi_users`\n ADD `default_request_type` INT( 11 ) NULL"; $DB->queryOrDie($query, "0.78 add default_request_type in glpi_users"); } if (!FieldExists("glpi_configs", "use_noright_users_add", false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `use_noright_users_add` tinyint( 1 ) NOT NULL DEFAULT '1'"; $DB->queryOrDie($query, "0.78 add use_noright_users_add in glpi_configs"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_budgets')); if (!FieldExists("glpi_profiles", "budget", false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `budget` CHAR( 1 ) NULL "; $DB->queryOrDie($query, "0.78 add budget in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `budget` = `infocom`"; $DB->queryOrDie($query, "0.78 update default budget rights"); } if (!FieldExists("glpi_budgets", "is_recursive", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `is_recursive` tinyint(1) NOT NULL DEFAULT '0' AFTER `name`,\n ADD INDEX `is_recursive` (`is_recursive`)"; $DB->queryOrDie($query, "0.78 add is_recursive field in glpi_budgets"); // budgets in 0.72 were global $query = "UPDATE `glpi_budgets`\n SET `is_recursive` = '1';"; $DB->queryOrDie($query, "0.78 set is_recursive to true in glpi_budgets"); } if (!FieldExists("glpi_budgets", "entities_id", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `entities_id` int(11) NOT NULL default '0' AFTER `name`,\n ADD INDEX `entities_id` (`entities_id`);"; $DB->queryOrDie($query, "0.78 add entities_id field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "is_deleted", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n ADD INDEX `is_deleted` (`is_deleted`)"; $DB->queryOrDie($query, "0.78 add is_deleted field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "begin_date", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `begin_date` DATE NULL,\n ADD INDEX `begin_date` (`begin_date`)"; $DB->queryOrDie($query, "0.78 add begin_date field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "end_date", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `end_date` DATE NULL,\n ADD INDEX `end_date` (`begin_date`)"; $DB->queryOrDie($query, "0.78 add end_date field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "value", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `value` DECIMAL( 20, 4 ) NOT NULL default '0.0000'"; $DB->queryOrDie($query, "0.78 add value field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "is_template", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `is_template` tinyint(1) NOT NULL default '0',\n ADD INDEX `is_template` (`is_template`);"; $DB->queryOrDie($query, "0.78 add is_template field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "template_name", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `template_name` varchar(255) default NULL"; $DB->queryOrDie($query, "0.78 add template_name field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "date_mod", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod field in glpi_budgets"); } if (!FieldExists("glpi_budgets", "notepad", false)) { $query = "ALTER TABLE `glpi_budgets`\n ADD `notepad` LONGTEXT NULL collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add notepad field in glpi_budgets"); } // Change budget search pref : date_mod $ADDTODISPLAYPREF['Budget'] = array(2, 3, 4, 19); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), __('Automatic action'))); if (!TableExists('glpi_crontasks')) { $query = "CREATE TABLE `glpi_crontasks` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n `name` varchar(150) COLLATE utf8_unicode_ci NOT NULL COMMENT 'task name',\n `frequency` int(11) NOT NULL COMMENT 'second between launch',\n `param` int(11) DEFAULT NULL COMMENT 'task specify parameter',\n `state` int(11) NOT NULL DEFAULT '1' COMMENT '0:disabled, 1:waiting, 2:running',\n `mode` int(11) NOT NULL DEFAULT '1' COMMENT '1:internal, 2:external',\n `allowmode` int(11) NOT NULL DEFAULT '3' COMMENT '1:internal, 2:external, 3:both',\n `hourmin` int(11) NOT NULL DEFAULT '0',\n `hourmax` int(11) NOT NULL DEFAULT '24',\n `logs_lifetime` int(11) NOT NULL DEFAULT '30' COMMENT 'number of days',\n `lastrun` datetime DEFAULT NULL COMMENT 'last run date',\n `lastcode` int(11) DEFAULT NULL COMMENT 'last run return code',\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`itemtype`,`name`),\n KEY `mode` (`mode`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\n COMMENT='Task run by internal / external cron.';"; $DB->queryOrDie($query, "0.78 create glpi_crontasks"); $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('OcsServer', 'ocsng', 300, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('CartridgeItem', 'cartridge', 86400, 10, 0, 1, 3, 0, 24, 30, NULL, NULL,\n NULL),\n ('ConsumableItem', 'consumable', 86400, 10, 0, 1, 3, 0, 24, 30, NULL, NULL,\n NULL),\n ('SoftwareLicense', 'software', 86400, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL,\n NULL),\n ('Contract', 'contract', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('InfoCom', 'infocom', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('CronTask', 'logs', 86400, 10, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('CronTask', 'optimize', 604800, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('MailCollector', 'mailgate', 600, 10, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('DBconnection', 'checkdbreplicate', 300, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('CronTask', 'checkupdate', 604800, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('CronTask', 'session', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('CronTask', 'graph', 3600, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n ('ReservationItem', 'reservation', 3600, NULL, 1, 1, 3, 0, 24, 30, NULL,\n NULL, NULL),\n ('Ticket', 'closeticket', '43200', NULL, '1', '1', '3', '0', '24', '30',\n NULL, NULL, NULL),\n ('Ticket', 'alertnotclosed', '43200', NULL, '1', '1', '3', '0', '24', '30',\n NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.78 populate glpi_crontasks"); } $ADDTODISPLAYPREF['Crontask'] = array(8, 3, 4, 7); if (!TableExists('glpi_crontasklogs')) { $query = "CREATE TABLE `glpi_crontasklogs` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `crontasks_id` int(11) NOT NULL,\n `crontasklogs_id` int(11) NOT NULL COMMENT 'id of ''start'' event',\n `date` datetime NOT NULL,\n `state` int(11) NOT NULL COMMENT '0:start, 1:run, 2:stop',\n `elapsed` float NOT NULL COMMENT 'time elapsed since start',\n `volume` int(11) NOT NULL COMMENT 'for statistics',\n `content` varchar(255) COLLATE utf8_unicode_ci NULL COMMENT 'message',\n PRIMARY KEY (`id`),\n KEY `date` (`date`),\n KEY `crontasks_id` (`crontasks_id`),\n KEY `crontasklogs_id_state` (`crontasklogs_id`,`state`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;"; $DB->queryOrDie($query, "0.78 create glpi_crontasklogs"); } // Retrieve core task lastrun date $tasks = array('ocsng', 'cartridge', 'consumable', 'software', 'contract', 'infocom', 'logs', 'optimize', 'mailgate', 'DBConnection', 'check_update', 'session'); foreach ($tasks as $task) { $lock = GLPI_CRON_DIR . '/' . $task . '.lock'; if (is_readable($lock) && ($stat = stat($lock))) { $DB->query("UPDATE `glpi_crontasks`\n SET `lastrun` = '" . date('Y-m-d H:i:s', $stat['mtime']) . "'\n WHERE `name` = '{$task}'"); unlink($lock); } } // Clean plugin lock foreach (glob(GLPI_CRON_DIR . '/*.lock') as $lock) { unlink($lock); } // disable ocsng cron if not activate if (FieldExists('glpi_configs', 'use_ocs_mode', false)) { $query = "SELECT `use_ocs_mode`\n FROM `glpi_configs`\n WHERE `id` = 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $value = $DB->result($result, 0, 0); if ($value == 0) { $query = "UPDATE `glpi_crontasks`\n SET `state`='0'\n WHERE `name` = 'ocsng'"; $DB->query($query); } } } } // Move glpi_config.expire_events to glpi_crontasks.param if (FieldExists('glpi_configs', 'expire_events', false)) { $query = "SELECT `expire_events`\n FROM `glpi_configs`\n WHERE `id` = 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $value = $DB->result($result, 0, 0); if ($value > 0) { $query = "UPDATE `glpi_crontasks`\n SET `state` = '1',\n `param` = '{$value}'\n WHERE `name` = 'logs'"; } else { $query = "UPDATE `glpi_crontasks`\n SET `state` = '0'\n WHERE `name` = 'logs'"; } $DB->query($query); } } $query = "ALTER TABLE `glpi_configs`\n DROP `expire_events`"; $DB->queryOrDie($query, "0.78 drop expire_events in glpi_configs"); } // Move glpi_config.auto_update_check to glpi_crontasks.state if (FieldExists('glpi_configs', 'auto_update_check', false)) { $query = "SELECT `auto_update_check`\n FROM `glpi_configs`\n WHERE `id` = 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $value = $DB->result($result, 0, 0); if ($value > 0) { $value *= DAY_TIMESTAMP; $query = "UPDATE `glpi_crontasks`\n SET `state` = '1',\n `frequency` = '{$value}'\n WHERE `name` = 'check_update'"; } else { $query = "UPDATE `glpi_crontasks`\n SET `state` = '0'\n WHERE `name` = 'logs'"; } $DB->query($query); } } $query = "ALTER TABLE `glpi_configs`\n DROP `auto_update_check`"; $DB->queryOrDie($query, "0.78 drop auto_update_check in check_update"); } if (FieldExists('glpi_configs', 'dbreplicate_maxdelay', false)) { $query = "SELECT `dbreplicate_maxdelay`\n FROM `glpi_configs`\n WHERE `id` = 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $value = $DB->result($result, 0, 0); $value = intval($value / 60); $query = "UPDATE `glpi_crontasks`\n SET `state` = '1',\n `frequency` = '{$value}'\n WHERE `name` = 'check_dbreplicate'"; $DB->query($query); } } $query = "ALTER TABLE `glpi_configs`\n DROP `dbreplicate_maxdelay`"; $DB->queryOrDie($query, "0.78 drop dbreplicate_maxdelay in check_update"); } if (FieldExists('glpi_configs', 'dbreplicate_notify_desynchronization', false)) { $query = "ALTER TABLE `glpi_configs`\n DROP `dbreplicate_notify_desynchronization`"; $DB->queryOrDie($query, "0.78 drop dbreplicate_notify_desynchronization in check_update"); } if (!FieldExists('glpi_configs', 'cron_limit', false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `cron_limit` TINYINT NOT NULL DEFAULT '1'\n COMMENT 'Number of tasks execute by external cron'"; $DB->queryOrDie($query, "0.78 add cron_limit in glpi_configs"); } if (!FieldExists('glpi_documents', 'sha1sum', false)) { $query = "ALTER TABLE `glpi_documents`\n ADD `sha1sum` CHAR(40) NULL DEFAULT NULL ,\n ADD INDEX `sha1sum` (`sha1sum`)"; $DB->queryOrDie($query, "0.78 add sha1sum in glpi_documents"); } if (FieldExists('glpi_documents', 'filename', false)) { $query = "ALTER TABLE `glpi_documents`\n CHANGE `filename` `filename` VARCHAR( 255 ) NULL DEFAULT NULL\n COMMENT 'for display and transfert'"; $DB->queryOrDie($query, "0.78 alter filename in glpi_documents"); } if (!FieldExists('glpi_documents', 'filepath', false)) { $query = "ALTER TABLE `glpi_documents`\n ADD `filepath` VARCHAR( 255 ) NULL\n COMMENT 'file storage path' AFTER `filename`"; $DB->queryOrDie($query, "0.78 add filepath in glpi_documents"); $query = "UPDATE `glpi_documents`\n SET `filepath` = `filename`"; $DB->queryOrDie($query, "0.78 set value of filepath in glpi_documents"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Category of tickets')); if (!FieldExists('glpi_tickets', 'solvedate', false)) { $query = "ALTER TABLE `glpi_tickets`\n ADD `solvedate` datetime default NULL AFTER `closedate`,\n ADD INDEX `solvedate` (`solvedate`)"; $DB->queryOrDie($query, "0.78 add solvedate to glpi_tickets"); $query = "UPDATE `glpi_tickets`\n SET `solvedate` = `closedate`"; $DB->queryOrDie($query, "0.78 update solvedate values in glpi_tickets"); } if (!FieldExists('glpi_ticketcategories', 'entities_id', false)) { $query = "ALTER TABLE `glpi_ticketcategories`\n ADD `entities_id` INT NOT NULL DEFAULT '0' AFTER `id`,\n ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `entities_id`,\n ADD INDEX `entities_id` (`entities_id`),\n ADD INDEX `is_recursive` (`is_recursive`)"; $DB->queryOrDie($query, "0.78 add entities_id,is_recursive in glpi_ticketcategories "); // Set existing categories recursive global $query = "UPDATE `glpi_ticketcategories`\n SET `is_recursive` = '1'"; $DB->queryOrDie($query, "0.78 set value of is_recursive in glpi_ticketcategories"); } if (!FieldExists('glpi_ticketcategories', 'knowbaseitemcategories_id', false)) { $query = "ALTER TABLE `glpi_ticketcategories`\n ADD `knowbaseitemcategories_id` INT NOT NULL DEFAULT '0',\n ADD INDEX `knowbaseitemcategories_id` ( `knowbaseitemcategories_id` )"; $DB->queryOrDie($query, "0.78 add knowbaseitemcategories_id in glpi_ticketcategories"); } if (!FieldExists('glpi_ticketcategories', 'users_id', false)) { $query = "ALTER TABLE `glpi_ticketcategories`\n ADD `users_id` INT NOT NULL DEFAULT '0',\n ADD INDEX `users_id` ( `users_id` ) "; $DB->queryOrDie($query, "0.78 add users_id in glpi_ticketcategories"); } if (!FieldExists('glpi_ticketcategories', 'groups_id', false)) { $query = "ALTER TABLE `glpi_ticketcategories`\n ADD `groups_id` INT NOT NULL DEFAULT '0',\n ADD INDEX `groups_id` ( `groups_id` ) "; $DB->queryOrDie($query, "0.78 add groups_id in glpi_ticketcategories"); } if (!FieldExists('glpi_ticketcategories', 'ancestors_cache', false)) { $query = "ALTER TABLE `glpi_ticketcategories`\n ADD `ancestors_cache` LONGTEXT NULL,\n ADD `sons_cache` LONGTEXT NULL"; $DB->queryOrDie($query, "0.78 add cache in glpi_ticketcategories"); } if (!FieldExists('glpi_ticketcategories', 'is_helpdeskvisible', false)) { $query = "ALTER TABLE `glpi_ticketcategories`\n ADD `is_helpdeskvisible` TINYINT( 1 ) NOT NULL DEFAULT '1',\n ADD INDEX `is_helpdeskvisible` (`is_helpdeskvisible`)"; $DB->queryOrDie($query, "0.78 add cache in glpi_ticketcategories"); } // change item type management for helpdesk if (FieldExists('glpi_profiles', 'helpdesk_hardware_type', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `helpdesk_item_type` TEXT NULL DEFAULT NULL AFTER `helpdesk_hardware_type`"; $DB->queryOrDie($query, "0.78 add helpdesk_item_type in glpi_profiles"); $query = "SELECT `id`, `helpdesk_hardware_type`\n FROM `glpi_profiles`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $types = $data['helpdesk_hardware_type']; $CFG_GLPI["ticket_types"] = array(COMPUTER_TYPE, NETWORKING_TYPE, PRINTER_TYPE, MONITOR_TYPE, PERIPHERAL_TYPE, SOFTWARE_TYPE, PHONE_TYPE); $tostore = array(); foreach ($CFG_GLPI["ticket_types"] as $itemtype) { if (pow(2, $itemtype) & $types) { $tostore[] = $typetoname[$itemtype]; } } $query = "UPDATE `glpi_profiles`\n SET `helpdesk_item_type` = '" . exportArrayToDB($tostore) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query, "0.78 populate helpdesk_item_type"); } } } $query = "ALTER TABLE `glpi_profiles`\n DROP `helpdesk_hardware_type`;"; $DB->queryOrDie($query, "0.78 drop helpdesk_hardware_type in glpi_profiles"); } if (!FieldExists('glpi_profiles', 'helpdesk_status', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `helpdesk_status` TEXT NULL\n COMMENT 'json encoded array of from/dest allowed status change'\n AFTER `helpdesk_item_type`"; $DB->queryOrDie($query, "0.78 add helpdesk_status in glpi_profiles"); } if (!FieldExists('glpi_profiles', 'update_priority', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `update_priority` CHAR( 1 ) NULL DEFAULT NULL AFTER `update_ticket`"; $DB->queryOrDie($query, "0.78 add update_priority in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `update_priority` = `update_ticket`"; $DB->queryOrDie($query, "0.78 set update_priority in glpi_profiles"); } if (FieldExists('glpi_profiles', 'comment_ticket', false)) { $query = "ALTER TABLE `glpi_profiles`\n CHANGE `comment_ticket` `add_followups` CHAR(1) NULL DEFAULT NULL"; $DB->queryOrDie($query, "0.78 add add_followups in glpi_profiles"); } if (FieldExists('glpi_profiles', 'comment_all_ticket', false)) { $query = "ALTER TABLE `glpi_profiles`\n CHANGE `comment_all_ticket` `global_add_followups` CHAR(1) NULL DEFAULT NULL"; $DB->queryOrDie($query, "0.78 add add_followups in glpi_profiles"); } if (!FieldExists('glpi_profiles', 'update_tasks', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `global_add_tasks` CHAR( 1 ) NULL AFTER `global_add_followups`,\n ADD `update_tasks` CHAR( 1 ) NULL AFTER `update_followups`"; $DB->queryOrDie($query, "0.78 add global_add_tasks, update_tasks in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `update_tasks` = `update_followups`,\n `global_add_tasks` = `global_add_followups`"; $DB->queryOrDie($query, "0.78 set update_tasks, global_add_tasks in glpi_profiles"); } if (!TableExists('glpi_taskcategories')) { $query = "CREATE TABLE `glpi_taskcategories` (\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 `taskcategories_id` int(11) NOT NULL default '0',\n `name` varchar(255) default NULL,\n `completename` text,\n `comment` text,\n `level` int(11) NOT NULL default '0',\n `ancestors_cache` longtext,\n `sons_cache` longtext,\n `is_helpdeskvisible` tinyint(1) NOT NULL default '1',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `taskcategories_id` (`taskcategories_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `is_helpdeskvisible` (`is_helpdeskvisible`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 create glpi_taskcategories"); } if (!TableExists('glpi_ticketsolutiontypes')) { $query = "CREATE TABLE `glpi_ticketsolutiontypes` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) default NULL,\n `comment` text,\n PRIMARY KEY (`id`),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 create glpi_ticketsolutiontypes"); // Populate only required for migration of ticket status $query = "INSERT INTO `glpi_ticketsolutiontypes`\n (`id` ,`name` ,`comment`)\n VALUES ('1', 'Closed (solved)', NULL),\n ('2', 'Closed (not solved)', NULL)"; $DB->queryOrDie($query, "0.78 populate glpi_ticketsolutiontypes"); } if (!FieldExists('glpi_tickets', 'solution', false)) { $query = "ALTER TABLE `glpi_tickets`\n ADD `ticketsolutiontypes_id` INT( 11 ) NOT NULL DEFAULT '0',\n ADD `solution` TEXT NULL"; $DB->queryOrDie($query, "0.78 create glpi_ticketsolutions"); $query = "ALTER TABLE `glpi_tickets`\n ADD INDEX `ticketsolutiontypes_id` ( `ticketsolutiontypes_id` ) "; $DB->queryOrDie($query, "0.78 add key for glpi_ticketsolutions"); // Move old status "old_done"", "old_notdone" as solution // and change to new "solved" / "closed" status $query = "UPDATE `glpi_tickets`\n SET `ticketsolutiontypes_id` = '2',\n `status` = 'closed'\n WHERE `status` = 'old_done'"; $DB->queryOrDie($query, "0.78 migration of glpi_tickets status"); $query = "UPDATE `glpi_tickets`\n SET `ticketsolutiontypes_id` = '1',\n `status` = 'closed'\n WHERE `status` = 'old_notdone'"; $DB->queryOrDie($query, "0.78 migration of glpi_tickets status"); } if (!FieldExists('glpi_documenttypes', 'comment', false)) { $query = "ALTER TABLE `glpi_documenttypes`\n ADD `comment` TEXT NULL "; $DB->queryOrDie($query, "0.78 add comment in glpi_documenttypes"); } if (!FieldExists('glpi_locations', 'is_recursive', false)) { $query = "ALTER TABLE `glpi_locations`\n ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `entities_id`,\n ADD `ancestors_cache` LONGTEXT NULL,\n ADD `sons_cache` LONGTEXT NULL,\n ADD INDEX `is_recursive` (`is_recursive`)"; $DB->queryOrDie($query, "0.78 add recursive, cache in glpi_locations"); } if (!FieldExists('glpi_locations', 'building', false)) { $query = "ALTER TABLE `glpi_locations`\n ADD `building` VARCHAR( 255 ) NULL ,\n ADD `room` VARCHAR( 255 ) NULL "; $DB->queryOrDie($query, "0.78 add building, room in glpi_locations"); } if (!TableExists('glpi_requesttypes')) { $query = "CREATE TABLE `glpi_requesttypes` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `is_helpdesk_default` tinyint(1) NOT NULL DEFAULT '0',\n `is_mail_default` tinyint(1) NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `is_helpdesk_default` (`is_helpdesk_default`),\n KEY `is_mail_default` (`is_mail_default`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 create glpi_requesttypes"); $DB->query("INSERT INTO `glpi_requesttypes`\n VALUES(1, '" . addslashes(__('Simplified interface')) . "', 1, 0, NULL)"); $DB->query("INSERT INTO `glpi_requesttypes`\n VALUES(2, '" . addslashes(__('Email')) . "', 0, 1, NULL)"); $DB->query("INSERT INTO `glpi_requesttypes`\n VALUES(3, '" . addslashes(__('Phone')) . "', 0, 0, NULL)"); $DB->query("INSERT INTO `glpi_requesttypes`\n VALUES(4, '" . addslashes(__('Direct')) . "', 0, 0, NULL)"); $DB->query("INSERT INTO `glpi_requesttypes`\n VALUES(5, '" . addslashes(__('Written')) . "', 0, 0, NULL)"); $DB->query("INSERT INTO `glpi_requesttypes`\n VALUES(6, '" . addslashes(__('Other')) . "', 0, 0, NULL)"); } // Add default display $ADDTODISPLAYPREF['RequestType'] = array(14, 15); if (FieldExists('glpi_tickets', 'request_type', false)) { $query = "ALTER TABLE `glpi_tickets`\n CHANGE `request_type` `requesttypes_id` INT( 11 ) NOT NULL DEFAULT '0'"; $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_tickets"); } if (FieldExists('glpi_configs', 'default_request_type', false)) { $query = "ALTER TABLE `glpi_configs`\n CHANGE `default_request_type` `default_requesttypes_id` INT( 11 ) NOT NULL\n DEFAULT '1'"; $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_configs"); } if (FieldExists('glpi_users', 'default_request_type', false)) { $query = "ALTER TABLE `glpi_users`\n CHANGE `default_request_type` `default_requesttypes_id` INT( 11 ) NULL DEFAULT NULL"; $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_users"); } if (!FieldExists('glpi_groups', 'date_mod', false)) { $query = "ALTER TABLE `glpi_groups`\n ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_groups"); } if (!FieldExists("glpi_configs", "priority_matrix", false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `priority_matrix` VARCHAR( 255 ) NULL\n COMMENT 'json encoded array for Urgence / Impact to Protority'"; $DB->queryOrDie($query, "0.78 add priority_matrix in glpi_configs"); $matrix = array(1 => array(1 => 1, 2 => 1, 3 => 2, 4 => 2, 4 => 2, 5 => 2), 2 => array(1 => 1, 2 => 2, 3 => 2, 4 => 3, 4 => 3, 5 => 3), 3 => array(1 => 2, 2 => 2, 3 => 3, 4 => 4, 4 => 4, 5 => 4), 4 => array(1 => 2, 2 => 3, 3 => 4, 4 => 4, 4 => 4, 5 => 5), 5 => array(1 => 2, 2 => 3, 3 => 4, 4 => 5, 4 => 5, 5 => 5)); $matrix = exportArrayToDB($matrix); $query = "UPDATE `glpi_configs`\n SET `priority_matrix` = '{$matrix}'\n WHERE `id` = '1'"; $DB->queryOrDie($query, "0.78 set default priority_matrix in glpi_configs"); } if (!FieldExists("glpi_configs", "urgency_mask", false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `urgency_mask` INT( 11 ) NOT NULL DEFAULT '62',\n ADD `impact_mask` INT( 11 ) NOT NULL DEFAULT '62'"; $DB->queryOrDie($query, "0.78 add urgency/impact_mask in glpi_configs"); } if (!FieldExists("glpi_users", "priority_6", false)) { $query = "ALTER TABLE `glpi_users`\n ADD `priority_6` CHAR( 20 ) NULL DEFAULT NULL AFTER `priority_5`"; $DB->queryOrDie($query, "0.78 add priority_6 in glpi_users"); } if (!FieldExists("glpi_configs", "priority_6", false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `priority_6` CHAR( 20 ) NOT NULL DEFAULT '#ff5555' AFTER `priority_5`"; $DB->queryOrDie($query, "0.78 add priority_6 in glpi_configs"); } if (!FieldExists('glpi_tickets', 'urgency', false)) { $query = "ALTER TABLE `glpi_tickets`\n ADD `urgency` INT NOT NULL DEFAULT '1' AFTER `content`,\n ADD `impact` INT NOT NULL DEFAULT '1' AFTER `urgency`,\n ADD INDEX `urgency` (`urgency`),\n ADD INDEX `impact` (`impact`)"; $DB->queryOrDie($query, "0.78 add urgency, impact to glpi_tickets"); // set default trivial values for Impact and Urgence $query = "UPDATE `glpi_tickets`\n SET `urgency` = `priority`,\n `impact` = `priority`"; $DB->queryOrDie($query, "0.78 set urgency, impact in glpi_tickets"); // Replace 'priority' (user choice un 0.72) by 'urgency' as criteria // Don't change "action" which is the result of user+tech evaluation. $query = "UPDATE `glpi_rulecriterias`\n SET `criteria`='urgency'\n WHERE `criteria`='priority'\n AND `rules_id` IN (SELECT `id`\n FROM `glpi_rules`\n WHERE `sub_type` = 'RuleTicket')"; $DB->queryOrDie($query, "0.78 fix priority/urgency in business rules"); } if (!TableExists('glpi_tickettasks')) { $query = "CREATE TABLE `glpi_tickettasks` (\n `id` int(11) NOT NULL auto_increment,\n `tickets_id` int(11) NOT NULL default '0',\n `taskcategories_id` int(11) NOT NULL default '0',\n `date` datetime default NULL,\n `users_id` int(11) NOT NULL default '0',\n `content` longtext collate utf8_unicode_ci,\n `is_private` tinyint(1) NOT NULL default '0',\n `realtime` float NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `date` (`date`),\n KEY `users_id` (`users_id`),\n KEY `tickets_id` (`tickets_id`),\n KEY `is_private` (`is_private`),\n KEY `taskcategories_id` (`taskcategories_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 create glpi_tickettasks"); // Required for migration from ticketfollowups to tickettasks - planned followups $query = "INSERT INTO `glpi_tickettasks`\n (`id`, `tickets_id`, `date`, `users_id`, `content`, `is_private`, `realtime`)\n SELECT `glpi_ticketfollowups`.`id`,\n `glpi_ticketfollowups`.`tickets_id`,\n `glpi_ticketfollowups`.`date`,\n `glpi_ticketfollowups`.`users_id`,\n `glpi_ticketfollowups`.`content`,\n `glpi_ticketfollowups`.`is_private`,\n `glpi_ticketfollowups`.`realtime`\n FROM `glpi_ticketfollowups`\n INNER JOIN `glpi_ticketplannings`\n ON (`glpi_ticketplannings`.`ticketfollowups_id` = `glpi_ticketfollowups`.`id`)"; $DB->queryOrDie($query, "0.78 populate glpi_tickettasks"); // delete from ticketfollowups - planned followups, previously copied $query = "DELETE FROM `glpi_ticketfollowups`\n WHERE `glpi_ticketfollowups`.`id`\n IN (SELECT `glpi_ticketplannings`.`ticketfollowups_id`\n FROM `glpi_ticketplannings`)"; $DB->queryOrDie($query, "0.78 delete from glpi_ticketfollowups"); // Required for migration from ticketfollowups to tickettasks - followups with a duration $query = "INSERT INTO `glpi_tickettasks`\n (`id`, `tickets_id`, `date`, `users_id`, `content`, `is_private`, `realtime`)\n SELECT `glpi_ticketfollowups`.`id`,\n `glpi_ticketfollowups`.`tickets_id`,\n `glpi_ticketfollowups`.`date`,\n `glpi_ticketfollowups`.`users_id`,\n `glpi_ticketfollowups`.`content`,\n `glpi_ticketfollowups`.`is_private`,\n `glpi_ticketfollowups`.`realtime`\n FROM `glpi_ticketfollowups`\n WHERE `realtime`>0"; $DB->queryOrDie($query, "0.78 populate glpi_tickettasks"); // delete from ticketfollowups - followups with duration, previously copied $query = "DELETE FROM `glpi_ticketfollowups`\n WHERE `realtime` > 0"; $DB->queryOrDie($query, "0.78 delete from glpi_ticketfollowups"); // ticketplannings is for tickettasks $query = "ALTER TABLE `glpi_ticketplannings`\n CHANGE `ticketfollowups_id` `tickettasks_id` int(11) NOT NULL default '0'"; $DB->queryOrDie($query, "0.78 alter glpi_ticketplannings"); // add requesttype for glpi_ticketfollowups $query = "ALTER TABLE `glpi_ticketfollowups`\n DROP `realtime`,\n ADD `requesttypes_id` int(11) NOT NULL default '0',\n ADD INDEX `requesttypes_id` (`requesttypes_id`)"; $DB->queryOrDie($query, "0.78 alter glpi_ticketplannings"); } // Migrate devices if (TableExists('glpi_computer_device')) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), _n('Component', 'Components', 2))); foreach ($devtypetoname as $key => $itemtype) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $itemtype)); $linktype = "Computer_{$itemtype}"; $linktable = getTableForItemType($linktype); $itemtable = getTableForItemType($itemtype); $fkname = getForeignKeyFieldForTable($itemtable); $withspecifity = array(MOBOARD_DEVICE => false, PROCESSOR_DEVICE => 'int', RAM_DEVICE => 'int', HDD_DEVICE => 'int', NETWORK_DEVICE => 'varchar', DRIVE_DEVICE => false, CONTROL_DEVICE => false, GFX_DEVICE => 'int', SND_DEVICE => false, PCI_DEVICE => false, CASE_DEVICE => false, POWER_DEVICE => false); if (FieldExists($itemtable, 'specif_default', false)) { // Convert default specifity if ($withspecifity[$key]) { // Convert data to int if ($withspecifity[$key] == 'int') { // clean non integer values $query = "UPDATE `{$itemtable}`\n SET `specif_default` = 0\n WHERE `specif_default` NOT REGEXP '^[0-9]*\$'\n OR `specif_default` = ''\n OR `specif_default` IS NULL"; $DB->queryOrDie($query, "0.78 update specif_default in {$itemtable}"); $query = "ALTER TABLE `{$itemtable}`\n CHANGE `specif_default` `specif_default` INT(11) NOT NULL"; $DB->queryOrDie($query, "0.78 alter specif_default in {$itemtable}"); } } else { // Drop default specificity $query = "ALTER TABLE `{$itemtable}`\n DROP `specif_default`"; $DB->queryOrDie($query, "0.78 drop specif_default in {$itemtable}"); } } if (!TableExists($linktable)) { // create table $query = "CREATE TABLE `{$linktable}` (\n `id` int(11) NOT NULL auto_increment,\n `computers_id` int(11) NOT NULL default '0',\n `{$fkname}` int(11) NOT NULL default '0',"; if ($withspecifity[$key]) { if ($withspecifity[$key] == 'int') { $query .= "`specificity` int(11) NOT NULL,"; } else { $query .= "`specificity` varchar(255) collate utf8_unicode_ci default NULL,"; } } $query .= "PRIMARY KEY (`id`),\n KEY `computers_id` (`computers_id`),\n KEY `{$fkname}` (`{$fkname}`)"; if ($withspecifity[$key]) { $query .= ",KEY `specificity` (`specificity`)"; } $query .= ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->queryOrDie($query, "0.78 create {$linktable}"); // Update data before copy if ($withspecifity[$key]) { // Convert data to int if ($withspecifity[$key] == 'int') { // clean non integer values $query = "UPDATE `glpi_computer_device`\n SET `specificity` = 0\n WHERE device_type = {$key}\n AND `specificity` NOT REGEXP '^[0-9]*\$'\n OR `specificity` = ''"; $DB->queryOrDie($query, "0.78 update specificity in glpi_computer_device for {$itemtype}"); } } // copy datas to new table : keep id for ocs sync $query = "INSERT INTO `{$linktable}` (`id`, `computers_id`, `{$fkname}`\n " . ($withspecifity[$key] ? ", `specificity`" : '') . ")\n SELECT `ID`, `FK_computers`, `FK_device`\n " . ($withspecifity[$key] ? ", specificity" : '') . "\n FROM `glpi_computer_device`\n WHERE `device_type` = {$key}"; $DB->queryOrDie($query, "0.78 populate {$linktable}"); } } // Drop computer_device_table $query = "DROP TABLE `glpi_computer_device`"; $DB->queryOrDie($query, "0.78 drop glpi_computer_device"); } if (!FieldExists('glpi_users', 'task_private', false)) { $query = "ALTER TABLE `glpi_users`\n ADD `task_private` TINYINT(1) DEFAULT NULL AFTER `followup_private`"; $DB->queryOrDie($query, "0.78 add task_private to glpi_users"); } if (!FieldExists('glpi_configs', 'task_private', false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `task_private` TINYINT(1) NOT NULL DEFAULT '0' AFTER `followup_private`"; $DB->queryOrDie($query, "0.78 add task_private to glpi_users"); } if (!FieldExists('glpi_rules', 'date_mod', false)) { $query = "ALTER TABLE `glpi_rules`\n ADD `date_mod` DATETIME NULL,\n ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_rules"); } if (!FieldExists('glpi_authldaps', 'entity_field', false)) { $query = "ALTER TABLE `glpi_authldaps`\n ADD `entity_field` VARCHAR( 255 ) DEFAULT NULL"; $DB->queryOrDie($query, "0.78 add entity_field to glpi_authldaps"); } if (!FieldExists('glpi_authldaps', 'entity_condition', false)) { $query = "ALTER TABLE `glpi_authldaps`\n ADD `entity_condition` TEXT NULL collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add entity_condition to glpi_authldaps"); } if (!FieldExists('glpi_entitydatas', 'ldapservers_id', false)) { $query = "ALTER TABLE `glpi_entitydatas`\n ADD `ldapservers_id` INT( 11 ) NOT NULL DEFAULT '0'"; $DB->queryOrDie($query, "0.78 add ldapservers_id to glpi_entitydatas"); } if (!FieldExists('glpi_entitydatas', 'mail_domain', false)) { $query = "ALTER TABLE `glpi_entitydatas`\n ADD `mail_domain` VARCHAR( 255 ) DEFAULT NULL"; $DB->queryOrDie($query, "0.78 add mail_domain to glpi_entitydatas"); } if (!FieldExists('glpi_entitydatas', 'entity_ldapfilter', false)) { $query = "ALTER TABLE `glpi_entitydatas`\n ADD `entity_ldapfilter` TEXT NULL collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add entity_ldapfilter to glpi_entitydatas"); } if (!FieldExists('glpi_profiles', 'import_externalauth_users', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `import_externalauth_users` CHAR( 1 ) NULL"; $DB->queryOrDie($query, "0.78 add import_externalauth_users in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `import_externalauth_users` = 'w'\n WHERE `user` ='w'"; $DB->queryOrDie($query, "0.78 add import_externalauth_users right users which are able to write users"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Notifications')); $templates = array(); if (!TableExists('glpi_notificationtemplates')) { $query = "CREATE TABLE `glpi_notificationtemplates` (\n `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n `name` VARCHAR( 255 ) default NULL ,\n `itemtype` VARCHAR( 100 ) NOT NULL,\n `date_mod` DATETIME DEFAULT NULL ,\n `comment` text collate utf8_unicode_ci,\n PRIMARY KEY ( `ID` ),\n KEY `itemtype` (`itemtype`),\n KEY `date_mod` (`date_mod`),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 create glpi_notificationtemplates"); $queries['DBConnection'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'MySQL Synchronization', 'DBConnection', NOW(),'');"; $queries['Reservation'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Reservations', 'Reservation', NOW(),'');"; $queries['Reservation2'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Alert Reservation', 'Reservation', NOW(),'');"; $queries['Ticket'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Tickets', 'Ticket', NOW(),'');"; $queries['Ticket2'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Tickets (Simple)', 'Ticket', NOW(),'');"; $queries['Ticket3'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Alert Tickets not closed', 'Ticket', NOW(),'');"; $queries['TicketValidation'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Tickets Validation', 'Ticket', NOW(),'');"; $queries['Cartridge'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Cartridges', 'Cartridge', NOW(),'');"; $queries['Consumable'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Consumables', 'Consumable', NOW(),'');"; $queries['Infocom'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Infocoms', 'Infocom', NOW(),'');"; $queries['SoftwareLicense'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Licenses', 'SoftwareLicense', NOW(),'');"; $queries['Contract'] = "INSERT INTO `glpi_notificationtemplates`\n VALUES(NULL, 'Contracts', 'Contract', NOW(),'');"; foreach ($queries as $itemtype => $query) { $DB->queryOrDie($query, "0.78 insert notification template for {$itemtype}"); $templates[$itemtype] = $DB->insert_id(); } $ADDTODISPLAYPREF['NotificationTemplate'] = array(4, 16); //There was a problem with GLPI < 0.78 : smtp_port field wans'nt used : migrate it $query = "SELECT `smtp_host`\n FROM `glpi_configs`\n WHERE `id` = '1'"; $result = $DB->query($query); $host = $DB->result($result, 0, 'smtp_host'); $results = array(); preg_match("/(.*):([0-9]*)/", $host, $results); if (!empty($results)) { $query = "UPDATE `glpi_configs`\n SET `smtp_host` = '" . $results[1] . "' ,\n `smtp_port` = '" . $results[2] . "'\n WHERE `id` = '1'"; $DB->query($query); } } if (!TableExists('glpi_notificationtemplatetranslations')) { $query = "CREATE TABLE `glpi_notificationtemplatetranslations` (\n `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n `notificationtemplates_id` INT( 11 ) NOT NULL DEFAULT '0',\n `language` CHAR ( 5 ) NOT NULL DEFAULT '',\n `subject` VARCHAR( 255 ) NOT NULL ,\n `content_text` TEXT NULL ,\n `content_html` TEXT NULL ,\n PRIMARY KEY ( `id` ),\n KEY `notificationtemplates_id` (`notificationtemplates_id`)\n )ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 create glpi_notificationtemplatetranslations"); $queries = array(); $queries['DBConnection'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['DBConnection'] . ", '','##lang.dbconnection.title##',\n '##lang.dbconnection.delay## : ##dbconnection.delay##\r\n',\n '<p>##lang.dbconnection.delay## : ##dbconnection.delay##</p>');"; $content_text_reservation = "======================================================================\r\n" . "##lang.reservation.user##: ##reservation.user##\r\n" . "##lang.reservation.item.name##: ##reservation.itemtype## - ##reservation.item.name##\r\n" . "##IFreservation.tech## ##lang.reservation.tech## ##reservation.tech## ##ENDIFreservation.tech##\r\n" . "##lang.reservation.begin##: ##reservation.begin##\r\n" . "##lang.reservation.end##: ##reservation.end##\r\n" . "##lang.reservation.comment##: ##reservation.comment##\r\n" . "======================================================================\r\n"; $content_html_reservation = "<!-- description{ color: inherit; background: #ebebeb;" . "border-style: solid;border-color: #8d8d8d; border-width: 0px 1px 1px 0px; }" . " -->\r\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">" . "##lang.reservation.user##:</span>##reservation.user##" . "<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">" . "##lang.reservation.item.name##:</span>" . "##reservation.itemtype## - ##reservation.item.name##<br />" . "##IFreservation.tech## ##lang.reservation.tech## ##reservation.tech##" . "##ENDIFreservation.tech##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">" . "##lang.reservation.begin##:</span> ##reservation.begin##" . "<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">" . "##lang.reservation.end##:</span>" . "##reservation.end##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">" . "##lang.reservation.comment##:</span> ##reservation.comment##" . "</p>"; $queries['Reservation'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Reservation'] . ", '',\n '##reservation.action##', '{$content_text_reservation}',\n '{$content_html_reservation}')"; $queries['Reservation2'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Reservation2'] . ", '',\n '##reservation.action## ##reservation.entity##',\n '##lang.reservation.entity## : ##reservation.entity## \r\n\n \r\n##FOREACHreservations## \r\n##lang.reservation.itemtype## : ##reservation.itemtype##\r\n\n ##lang.reservation.item## : ##reservation.item##\r\n \r\n ##reservation.url## \r\n\n ##ENDFOREACHreservations##',\n '<p>##lang.reservation.entity## : ##reservation.entity## <br /> <br />\n##FOREACHreservations## <br />##lang.reservation.itemtype## : ##reservation.itemtype##<br />\n ##lang.reservation.item## : ##reservation.item##<br /> <br />\n <a href=\"##reservation.url##\"> ##reservation.url##</a><br />\n ##ENDFOREACHreservations##</p>');"; $queries['Ticket'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, '" . $templates['Ticket'] . "', '',\n '##ticket.action## ##ticket.title##',\n' ##IFticket.storestatus=solved##\n ##lang.ticket.url## : ##ticket.urlapprove##\n ##lang.ticket.autoclosewarning##\n ##lang.ticket.solvedate## : ##ticket.solvedate##\n ##lang.ticket.solution.type## : ##ticket.solution.type##\n ##lang.ticket.solution.description## : ##ticket.solution.description## ##ENDIFticket.storestatus##\n ##ELSEticket.storestatus## ##lang.ticket.url## : ##ticket.url## ##ENDELSEticket.storestatus##\n\n ##lang.ticket.description##\n\n ##lang.ticket.title## : ##ticket.title##\n ##lang.ticket.author.name## : ##IFticket.author.name## ##ticket.author.name## ##ENDIFticket.author.name## ##ELSEticket.author.name##--##ENDELSEticket.author.name##\n ##lang.ticket.creationdate## : ##ticket.creationdate##\n ##lang.ticket.closedate## : ##ticket.closedate##\n ##lang.ticket.requesttype## : ##ticket.requesttype##\n ##IFticket.itemtype## ##lang.ticket.item.name## : ##ticket.itemtype## - ##ticket.item.name## ##IFticket.item.model## - ##ticket.item.model## ##ENDIFticket.item.model## ##IFticket.item.serial## - ##ticket.item.serial## ##ENDIFticket.item.serial## ##IFticket.item.otherserial## -##ticket.item.otherserial## ##ENDIFticket.item.otherserial## ##ENDIFticket.itemtype##\n##IFticket.assigntouser## ##lang.ticket.assigntouser## : ##ticket.assigntouser## ##ENDIFticket.assigntouser##\n ##lang.ticket.status## : ##ticket.status##\n##IFticket.assigntogroup## ##lang.ticket.assigntogroup## : ##ticket.assigntogroup## ##ENDIFticket.assigntogroup##\n ##lang.ticket.urgency## : ##ticket.urgency##\n ##lang.ticket.impact## : ##ticket.impact##\n ##lang.ticket.priority## : ##ticket.priority##\n##IFticket.user.email## ##lang.ticket.user.email## : ##ticket.user.email ##ENDIFticket.user.email##\n##IFticket.category## ##lang.ticket.category## : ##ticket.category## ##ENDIFticket.category## ##ELSEticket.category## ##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n ##lang.ticket.content## : ##ticket.content##\n\n ##IFticket.storestatus=closed##\n\n ##lang.ticket.solvedate## : ##ticket.solvedate##\n ##lang.ticket.solution.type## : ##ticket.solution.type##\n ##lang.ticket.solution.description## : ##ticket.solution.description##\n ##ENDIFticket.storestatus##\n ##lang.ticket.numberoffollowups## : ##ticket.numberoffollowups##\n\n##FOREACHfollowups##\n\n [##followup.date##] ##lang.followup.isprivate## : ##followup.isprivate##\n ##lang.followup.author## ##followup.author##\n ##lang.followup.description## ##followup.description##\n ##lang.followup.date## ##followup.date##\n ##lang.followup.requesttype## ##followup.requesttype##\n\n##ENDFOREACHfollowups##\n ##lang.ticket.numberoftasks## : ##ticket.numberoftasks##\n\n##FOREACHtasks##\n\n [##task.date##] ##lang.task.isprivate## : ##task.isprivate##\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'<!-- description{ color: inherit; background: #ebebeb; border-style: solid;border-color: #8d8d8d; border-width: 0px 1px 1px 0px; } -->\n<div>##IFticket.storestatus=solved##</div>\n<div>##lang.ticket.url## : <a href=\"##ticket.urlapprove##\">##ticket.urlapprove##</a> <span class=\"b\"> </span></div>\n<div><span class=\"b\">##lang.ticket.autoclosewarning##</span> </div>\n<div><span style=\"color: #888888;\"><span class=\"b\"><span style=\"text-decoration: underline;\">##lang.ticket.solvedate##</span></span></span> : ##ticket.solvedate##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.type##</span></span> : ##ticket.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.description##</span></span> : ##ticket.solution.description## ##ENDIFticket.storestatus##</div>\n<div>##ELSEticket.storestatus## ##lang.ticket.url## : <a href=\"##ticket.url##\">##ticket.url##</a> ##ENDELSEticket.storestatus##</div>\n<div class=\"description b\"><span class=\"b\">##lang.ticket.description##</span></div>\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.title##</span> :##ticket.title## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.author.name##</span> :##IFticket.author.name## ##ticket.author.name## ##ENDIFticket.author.name## ##ELSEticket.author.name##--##ENDELSEticket.author.name## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.creationdate##</span> :##ticket.creationdate## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.closedate##</span> :##ticket.closedate## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.requesttype##</span> :##ticket.requesttype##<br /> ##IFticket.itemtype## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.item.name##</span> : ##ticket.itemtype## - ##ticket.item.name## ##IFticket.item.model## - ##ticket.item.model## ##ENDIFticket.item.model## ##IFticket.item.serial## -##ticket.item.serial## ##ENDIFticket.item.serial##  ##IFticket.item.otherserial## -##ticket.item.otherserial## ##ENDIFticket.item.otherserial## ##ENDIFticket.itemtype## <br /> ##IFticket.assigntouser## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.assigntouser##</span> : ##ticket.assigntouser## ##ENDIFticket.assigntouser##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.ticket.status## </span> : ##ticket.status##<br /> ##IFticket.assigntogroup## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.assigntogroup##</span> : ##ticket.assigntogroup## ##ENDIFticket.assigntogroup##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.urgency##</span> : ##ticket.urgency##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.impact##</span> : ##ticket.impact##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.priority##</span> : ##ticket.priority## <br /> ##IFticket.user.email##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.user.email##</span> : ##ticket.user.email ##ENDIFticket.user.email## <br /> ##IFticket.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.ticket.category## </span> :##ticket.category## ##ENDIFticket.category## ##ELSEticket.category## ##lang.ticket.nocategoryassigned## ##ENDELSEticket.category## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.content##</span> : ##ticket.content##</p>\n<br />##IFticket.storestatus=closed##<br /><span style=\"text-decoration: underline;\"><span class=\"b\"><span style=\"color: #888888;\">##lang.ticket.solvedate##</span></span></span> : ##ticket.solvedate##<br /><span style=\"color: #888888;\"><span class=\"b\"><span style=\"text-decoration: underline;\">##lang.ticket.solution.type##</span></span></span> : ##ticket.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.description##</span></span> : ##ticket.solution.description##<br />##ENDIFticket.storestatus##</p>\n<div class=\"description b\">##lang.ticket.numberoffollowups## : ##ticket.numberoffollowups##</div>\n<p>##FOREACHfollowups##</p>\n<div class=\"description b\"><br /> <span class=\"b\"> [##followup.date##] <em>##lang.followup.isprivate## : ##followup.isprivate## </em></span><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.author## </span> ##followup.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.description## </span> ##followup.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.date## </span> ##followup.date##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.requesttype## </span> ##followup.requesttype##</div>\n<p>##ENDFOREACHfollowups##</p>\n<div class=\"description b\">##lang.ticket.numberoftasks## : ##ticket.numberoftasks##</div>\n<p>##FOREACHtasks##</p>\n<div class=\"description b\"><br /> <span class=\"b\"> [##task.date##] <em>##lang.task.isprivate## : ##task.isprivate## </em></span><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>');"; $queries['Contract'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Contract'] . ", '',\n '##contract.action## ##contract.entity##',\n '##lang.contract.entity## : ##contract.entity##\r\n" . "\r\n##FOREACHcontracts##\r\n" . "##lang.contract.name## : ##contract.name##\r\n" . "##lang.contract.number## : ##contract.number##\r\n" . "##lang.contract.time## : ##contract.time##\r\n" . "##IFcontract.type####lang.contract.type## : ##contract.type##" . "##ENDIFcontract.type##\r\n" . "##contract.url##\r\n" . "##ENDFOREACHcontracts##',\n'<p>##lang.contract.entity## : ##contract.entity##<br />\n<br />##FOREACHcontracts##<br />##lang.contract.name## :\n##contract.name##<br />\n##lang.contract.number## : ##contract.number##<br />\n##lang.contract.time## : ##contract.time##<br />\n##IFcontract.type####lang.contract.type## : ##contract.type##\n##ENDIFcontract.type##<br />\n<a href=\"##contract.url##\">\n##contract.url##</a><br />\n##ENDFOREACHcontracts##</p>');"; $queries['Ticket2'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Ticket2'] . ", '',\n '##ticket.action## ##ticket.title##',\n'##lang.ticket.url## : ##ticket.url## \r\n\n##lang.ticket.description## \r\n\n\n##lang.ticket.title##  :##ticket.title## \n\n##lang.ticket.author.name##  :##IFticket.author.name##\n##ticket.author.name## ##ENDIFticket.author.name##\n##ELSEticket.author.name##--##ENDELSEticket.author.name##   \n\n##IFticket.category## ##lang.ticket.category##  :##ticket.category##\n##ENDIFticket.category## ##ELSEticket.category##\n##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n\n##lang.ticket.content##  : ##ticket.content##\n##IFticket.itemtype##\n##lang.ticket.item.name##  : ##ticket.itemtype## - ##ticket.item.name##\n##ENDIFticket.itemtype##',\n'<div>##lang.ticket.url## : <a href=\"##ticket.url##\">\n##ticket.url##</a></div>\r\n<div class=\"description b\">\n##lang.ticket.description##</div>\r\n<p><span\nstyle=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">\n##lang.ticket.title##</span> :##ticket.title##\n<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">\n##lang.ticket.author.name##</span>\n##IFticket.author.name## ##ticket.author.name##\n##ENDIFticket.author.name##\n##ELSEticket.author.name##--##ENDELSEticket.author.name##\n<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> \n;</span><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> </span>\n##IFticket.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">\n##lang.ticket.category## </span> :##ticket.category##\n##ENDIFticket.category## ##ELSEticket.category##\n##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">\n##lang.ticket.content##</span> :\n##ticket.content##<br />##IFticket.itemtype##\n<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">\n##lang.ticket.item.name##</span> :\n##ticket.itemtype## - ##ticket.item.name##\n##ENDIFticket.itemtype##</p>');"; $queries['TicketValidation'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['TicketValidation'] . ", '',\n '##ticket.action## ##ticket.title##',\n'##FOREACHvalidations##\n\n##IFvalidation.storestatus=waiting##\n##validation.submission.title##\n##lang.validation.commentsubmission## : ##validation.commentsubmission##\n##ENDIFvalidation.storestatus##\n##ELSEvalidation.storestatus## ##validation.answer.title## ##ENDELSEvalidation.storestatus##\n\n##lang.ticket.url## : ##ticket.urlvalidation##\n\n##IFvalidation.status## ##lang.validation.validationstatus## ##ENDIFvalidation.status##\n##IFvalidation.commentvalidation##\n##lang.validation.commentvalidation## : ##validation.commentvalidation##\n##ENDIFvalidation.commentvalidation##\n##ENDFOREACHvalidations##',\n'<div>##FOREACHvalidations##</div>\n<p>##IFvalidation.storestatus=waiting##</p>\n<div>##validation.submission.title##</div>\n<div>##lang.validation.commentsubmission## : ##validation.commentsubmission##</div>\n<div>##ENDIFvalidation.storestatus##</div>\n<div>##ELSEvalidation.storestatus## ##validation.answer.title## ##ENDELSEvalidation.storestatus##</div>\n<div></div>\n<div>\n<div>##lang.ticket.url## : <a href=\"##ticket.urlvalidation##\"> ##ticket.urlvalidation## </a></div>\n</div>\n<p>##IFvalidation.status## ##lang.validation.validationstatus## ##ENDIFvalidation.status##\n<br /> ##IFvalidation.commentvalidation##<br /> ##lang.validation.commentvalidation## :\n  ##validation.commentvalidation##<br /> ##ENDIFvalidation.commentvalidation##\n<br />##ENDFOREACHvalidations##</p>');"; $queries['Ticket3'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Ticket3'] . ", '',\n '##ticket.action## ##ticket.entity##',\n'##lang.ticket.entity## : ##ticket.entity##\n \n##FOREACHtickets##\n\n##lang.ticket.title## : ##ticket.title##\n ##lang.ticket.status## : ##ticket.status##\n\n ##ticket.url## \n ##ENDFOREACHtickets##',\n'<table class=\"tab_cadre\" border=\"1\" cellspacing=\"2\" cellpadding=\"3\">\n<tbody>\n<tr>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.author.name##</span></td>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.title##</span></td>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.priority##</span></td>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.status##</span></td>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.attribution##</span></td>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.creationdate##</span></td>\n<td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"><span style=\"font-size: 11px; text-align: left;\">##lang.ticket.content##</span></td>\n</tr>\n##FOREACHtickets##\n<tr>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\">##ticket.author.name##</span></td>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\"><a href=\"##ticket.url##\">##ticket.title##</a></span></td>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\">##ticket.priority##</span></td>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\">##ticket.status##</span></td>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\">##IFticket.assigntouser####ticket.assigntouser##<br />##ENDIFticket.assigntouser####IFticket.assigntogroup##<br />##ticket.assigntogroup## ##ENDIFticket.assigntogroup####IFticket.assigntosupplier##<br />##ticket.assigntosupplier## ##ENDIFticket.assigntosupplier##</span></td>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\">##ticket.creationdate##</span></td>\n<td width=\"auto\"><span style=\"font-size: 11px; text-align: left;\">##ticket.content##</span></td>\n</tr>\n##ENDFOREACHtickets##\n</tbody>\n</table>');"; $queries['Consumable'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Consumable'] . ", '',\n '##consumable.action## ##consumable.entity##',\n'##lang.consumable.entity## : ##consumable.entity##\n \n\n##FOREACHconsumables##\n##lang.consumable.item## : ##consumable.item##\n \n\n##lang.consumable.reference## : ##consumable.reference##\n\n##lang.consumable.remaining## : ##consumable.remaining##\n\n##consumable.url## \n\n##ENDFOREACHconsumables##', '<p>\n##lang.consumable.entity## : ##consumable.entity##\n<br /> <br />##FOREACHconsumables##\n<br />##lang.consumable.item## : ##consumable.item##<br />\n<br />##lang.consumable.reference## : ##consumable.reference##<br />\n##lang.consumable.remaining## : ##consumable.remaining##<br />\n<a href=\"##consumable.url##\"> ##consumable.url##</a><br />\n ##ENDFOREACHconsumables##</p>');"; $queries['Cartridge'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Cartridge'] . ", '',\n '##cartridge.action## ##cartridge.entity##',\n'##lang.cartridge.entity## : ##cartridge.entity##\n \n\n##FOREACHcartridges##\n##lang.cartridge.item## : ##cartridge.item##\n \n\n##lang.cartridge.reference## : ##cartridge.reference##\n\n##lang.cartridge.remaining## : ##cartridge.remaining##\n\n##cartridge.url## \n ##ENDFOREACHcartridges##',\n'<p>##lang.cartridge.entity## :##cartridge.entity##\n<br /> <br />##FOREACHcartridges##\n<br />##lang.cartridge.item## :\n##cartridge.item##<br /> <br />\n##lang.cartridge.reference## :\n##cartridge.reference##<br />\n##lang.cartridge.remaining## :\n##cartridge.remaining##<br />\n<a href=\"##cartridge.url##\">\n##cartridge.url##</a><br />\n##ENDFOREACHcartridges##</p>');"; $queries['Infocom'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['Infocom'] . ", '',\n '##infocom.action## ##infocom.entity##',\n'##lang.infocom.entity## : ##infocom.entity## \n \n\n##FOREACHinfocoms## \n\n##lang.infocom.itemtype## : ##infocom.itemtype##\n\n##lang.infocom.item## : ##infocom.item##\n \n\n##lang.infocom.expirationdate## : ##infocom.expirationdate##\n\n##infocom.url## \n ##ENDFOREACHinfocoms##',\n'<p>##lang.infocom.entity## : ##infocom.entity##\n<br /> <br />##FOREACHinfocoms##\n<br />##lang.infocom.itemtype## : ##infocom.itemtype##<br />\n##lang.infocom.item## : ##infocom.item##<br /> <br />\n##lang.infocom.expirationdate## : ##infocom.expirationdate##\n<br /> <a href=\"##infocom.url##\">\n##infocom.url##</a><br />\n##ENDFOREACHinfocoms##</p>');"; $queries['SoftwareLicense'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES(NULL, " . $templates['SoftwareLicense'] . ", '',\n '##license.action## ##license.entity##',\n'##lang.license.entity## : ##license.entity##\r\n\n##FOREACHlicenses## \r\n\n##lang.license.item## : ##license.item##\r\n\n##lang.license.serial## : ##license.serial##\r\n\n##lang.license.expirationdate## : ##license.expirationdate##\r\n\n##license.url## \r\n ##ENDFOREACHlicenses##', '<p>\n##lang.license.entity## : ##license.entity##<br />\n##FOREACHlicenses##\n<br />##lang.license.item## : ##license.item##<br />\n##lang.license.serial## : ##license.serial##<br />\n##lang.license.expirationdate## : ##license.expirationdate##\n<br /> <a href=\"##license.url##\"> ##license.url##\n</a><br /> ##ENDFOREACHlicenses##</p>');"; foreach ($queries as $itemtype => $query) { $DB->queryOrDie($query, "0.78 insert notification template default translation for {$itemtype}"); } unset($queries); } $notifications = array(); if (!TableExists('glpi_notifications')) { $query = "CREATE TABLE `glpi_notifications` (\n `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n `name` VARCHAR( 255 ) DEFAULT NULL ,\n `entities_id` INT( 11 ) NOT NULL DEFAULT '0',\n `itemtype` VARCHAR( 100 ) NOT NULL ,\n `event` VARCHAR( 255 ) NOT NULL ,\n `mode` VARCHAR( 255 ) NOT NULL ,\n `notificationtemplates_id` INT( 11 ) NOT NULL DEFAULT '0',\n `comment` TEXT DEFAULT NULL ,\n `is_recursive` 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 `itemtype` (`itemtype`),\n KEY `entities_id` (`entities_id`),\n KEY `is_active` (`is_active`),\n KEY `date_mod` (`date_mod`),\n KEY `is_recursive` (`is_recursive`),\n KEY `notificationtemplates_id` (`notificationtemplates_id`)\n ) ENGINE = MYISAM CHARSET utf8 COLLATE utf8_unicode_ci;"; $DB->queryOrDie($query, "0.78 create glpi_notifications"); $queries = array(); $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Alert Tickets not closed', 0, 'Ticket', 'alertnotclosed',\n 'mail'," . $templates['Ticket3'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'New Ticket', 0, 'Ticket', 'new', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Update Ticket', 0, 'Ticket', 'update', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Close Ticket', 0, 'Ticket', 'closed', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Add Followup', 0, 'Ticket', 'add_followup', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Add Task', 0, 'Ticket', 'add_task', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Update Followup', 0, 'Ticket', 'update_followup', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Update Task', 0, 'Ticket', 'update_task', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Delete Followup', 0, 'Ticket', 'delete_followup', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Delete Task', 0, 'Ticket', 'delete_task', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Resolve ticket', 0, 'Ticket', 'solved', 'mail',\n " . $templates['Ticket'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Ticket Validation', 0, 'Ticket', 'validation', 'mail',\n " . $templates['TicketValidation'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'New Reservation', 0, 'Reservation', 'new', 'mail',\n " . $templates['Reservation'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Update Reservation', 0, 'Reservation', 'update', 'mail',\n " . $templates['Reservation'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Delete Reservation', 0, 'Reservation', 'delete', 'mail',\n " . $templates['Reservation'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Alert Reservation', 0, 'Reservation', 'alert', 'mail',\n " . $templates['Reservation2'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Contract Notice', 0, 'Contract', 'notice', 'mail',\n " . $templates['Contract'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Contract End', 0, 'Contract', 'end', 'mail',\n " . $templates['Contract'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'MySQL Synchronization', 0, 'DBConnection', 'desynchronization',\n 'mail'," . $templates['DBConnection'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Cartridges', 0, 'Cartridge', 'alert', 'mail',\n " . $templates['Cartridge'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Consumables', 0, 'Consumable', 'alert', 'mail',\n " . $templates['Consumable'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Infocoms', 0, 'Infocom', 'alert', 'mail',\n " . $templates['Infocom'] . ", '', 1, 1, NOW())"; $queries[] = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Software Licenses', 0, 'SoftwareLicense', 'alert', 'mail',\n " . $templates['SoftwareLicense'] . ", '', 1, 1, NOW())"; foreach ($queries as $query) { $DB->queryOrDie($query, "0.78 insert notification"); } $ADDTODISPLAYPREF['Notification'] = array(5, 6, 2, 4, 80, 86); unset($queries); } if (!TableExists('glpi_notificationtargets') && TableExists('glpi_mailingsettings')) { $query = "RENAME TABLE `glpi_mailingsettings` TO `glpi_notificationtargets`;"; $DB->queryOrDie($query, "0.78 rename table glpi_mailingsettings in glpi_notificationtargets"); $query = "ALTER TABLE `glpi_notificationtargets`\n ADD `notifications_id` INT( 11 ) NOT NULL DEFAULT '0',\n ADD INDEX `notifications_id` (`notifications_id`)"; $DB->queryOrDie($query, "0.78 add field notifications_id to glpi_notificationtargets"); $query = "ALTER TABLE `glpi_notificationtargets`\n CHANGE `type` `oldtype` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci\n NULL DEFAULT NULL"; $DB->queryOrDie($query, "0.78 change field type in oldtype"); $query = "ALTER TABLE `glpi_notificationtargets`\n CHANGE `mailingtype` `type` INT( 11 ) NOT NULL DEFAULT '0'"; $DB->queryOrDie($query, "0.78 change field mailingtype in type"); $fields = array('new' => array('itemtype' => 'Ticket', 'newaction' => 'new'), 'update' => array('itemtype' => 'Ticket', 'newaction' => 'update'), 'finish' => array('itemtype' => 'Ticket', 'newaction' => 'closed'), 'resa' => array('itemtype' => 'Reservation', 'newaction' => 'new'), 'followup' => array('itemtype' => 'Ticket', 'newaction' => 'add_followup'), 'alertconsumable' => array('itemtype' => 'Consumable', 'newaction' => 'alert'), 'alertcartridge' => array('itemtype' => 'Cartridge', 'newaction' => 'alert'), 'alertlicense' => array('itemtype' => 'SoftwareLicense', 'newaction' => 'alert'), 'alertinfocom' => array('itemtype' => 'Infocom', 'newaction' => 'alert'), 'alertcontract' => array('itemtype' => 'Contract', 'newaction' => 'end')); $query = "SELECT `oldtype`\n FROM `glpi_notificationtargets`\n GROUP BY `oldtype`"; foreach ($DB->request($query) as $data) { $infos = $fields[$data['oldtype']]; $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype`='" . $infos['itemtype'] . "'\n AND `event`='" . $infos['newaction'] . "'"; $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id"); if ($DB->numrows($result)) { $id = $DB->result($result, 0, 'id'); $query_update = "UPDATE `glpi_notificationtargets`\n SET `notifications_id` = '{$id}'\n WHERE `oldtype` = '" . $data['oldtype'] . "'"; $DB->queryOrDie($query_update, "0.78 set notificationtargets_id"); } } $query = "ALTER TABLE `glpi_notificationtargets`\n DROP INDEX `unicity` "; $DB->queryOrDie($query, "0.78 drop index unicity from glpi_notificationtargets"); $query = "ALTER TABLE `glpi_notificationtargets`\n DROP `oldtype`"; $DB->queryOrDie($query, "0.78 drop field oldtype in glpi_notificationtargets"); //Add administrator as target for MySQL Synchronization notification $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype` = 'DBConnection'"; $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id"); if ($DB->numrows($result)) { $id = $DB->result($result, 0, 'id'); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, " . $id . ", 1, 1)"; $DB->queryOrDie($query, "0.78 add target for dbsynchronization"); } //Add validator as target for Ticket Validation $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Ticket'\n AND `event` = 'validation'"; $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id"); if ($DB->numrows($result)) { $id = $DB->result($result, 0, 'id'); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, " . $id . ", 1, 14);"; $DB->queryOrDie($query, "0.78 add target for Ticket Validation"); } //Manage Reservation update & delete $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Reservation'\n AND `event` IN ('update', 'delete')"; foreach ($DB->request($query_type) as $data_resa) { $query_targets = "SELECT `glpi_notificationtargets` . *\n FROM `glpi_notifications` ,\n `glpi_notificationtargets`\n WHERE `glpi_notifications`.`itemtype` = 'Reservation'\n AND `glpi_notifications`.`event` = 'new'\n AND `glpi_notificationtargets`.notifications_id\n = `glpi_notifications`.id"; foreach ($DB->request($query_targets) as $data_targets) { $query_insert = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, " . $data_resa['id'] . ", " . $data_targets['type'] . ",\n " . $data_targets['items_id'] . ");"; $DB->queryOrDie($query_insert, "0.78 add target for reservations"); } } //Manage contract notice $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Contract'\n AND `event` = 'notice'"; foreach ($DB->request($query_type) as $data_contract) { $query_targets = "SELECT `glpi_notificationtargets`.*\n FROM `glpi_notifications` , `glpi_notificationtargets`\n WHERE `glpi_notifications`.`itemtype` = 'Contract'\n AND `glpi_notifications`.`event` = 'end'\n AND `glpi_notificationtargets`.notifications_id\n = `glpi_notifications`.id"; foreach ($DB->request($query_targets) as $data_targets) { $query_insert = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, " . $data_contract['id'] . ", " . $data_targets['type'] . ",\n " . $data_targets['items_id'] . ")"; $DB->queryOrDie($query_insert, "0.78 add target for contract"); } } //Manage ticket tasks & followups $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype`='Ticket'\n AND `event` IN ('add_task', 'update_task', 'update_followup',\n 'delete_task', 'delete_followup')"; foreach ($DB->request($query_type) as $data_ticket) { $query_targets = "SELECT `glpi_notificationtargets`.*\n FROM `glpi_notifications` ,\n `glpi_notificationtargets`\n WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n AND `glpi_notifications`.`event` = 'add_followup'\n AND `glpi_notificationtargets`.notifications_id\n = `glpi_notifications`.id"; foreach ($DB->request($query_targets) as $data_targets) { $query_insert = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, " . $data_ticket['id'] . ", " . $data_targets['type'] . ",\n " . $data_targets['items_id'] . ");"; $DB->queryOrDie($query_insert, "0.78 add target for tickets"); } } //Manage ticket solved $query_type = "SELECT `id`\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Ticket'\n AND `event` = 'solved'"; foreach ($DB->request($query_type) as $data_ticket) { $query_targets = "SELECT `glpi_notificationtargets`.*\n FROM `glpi_notifications` ,\n `glpi_notificationtargets`\n WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n AND `glpi_notifications`.`event` = 'closed'\n AND `glpi_notificationtargets`.notifications_id\n = `glpi_notifications`.id"; foreach ($DB->request($query_targets) as $data_targets) { $query_insert = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, " . $data_ticket['id'] . ", " . $data_targets['type'] . ",\n " . $data_targets['items_id'] . ")"; $DB->queryOrDie($query_insert, "0.78 add target for tickets action solved"); } } } if (!FieldExists('glpi_profiles', 'notification', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `notification` CHAR( 1 ) NULL"; $DB->queryOrDie($query, "0.78 add notification in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `notification` = 'w'\n WHERE `config` ='w'"; $DB->queryOrDie($query, "0.78 add notification write right user which have config right"); } if (!FieldExists('glpi_entitydatas', 'mailing_signature', false)) { $query = "ALTER TABLE `glpi_entitydatas` ADD `mailing_signature` TEXT DEFAULT NULL ,\n ADD `cartridges_alert_repeat` INT( 11 ) NOT NULL DEFAULT '-1',\n ADD `consumables_alert_repeat` INT( 11 ) NOT NULL DEFAULT '-1',\n ADD `use_licenses_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n ADD `use_contracts_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n ADD `use_infocoms_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n ADD `use_reservations_alert` INT( 11 ) NOT NULL DEFAULT '-1',\n ADD `autoclose_delay` INT( 11 ) NOT NULL DEFAULT '-1',\n ADD `notclosed_delay` INT( 11 ) NOT NULL DEFAULT '-1'"; $DB->queryOrDie($query, "0.78 add notifications fields in glpi_entitydatas"); } if (!FieldExists('glpi_configs', 'use_reservations_alert', false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `use_infocoms_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n ADD `use_contracts_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n ADD `use_reservations_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n ADD `autoclose_delay` INT( 11 ) NOT NULL DEFAULT '0',\n ADD `notclosed_delay` INT( 11 ) NOT NULL DEFAULT '0'"; $DB->queryOrDie($query, "0.78 add notifications fields in glpi_configs"); } if (TableExists('glpi_mailingsettings')) { $query = "DROP TABLE `glpi_mailingsettings`;"; $DB->queryOrDie($query, "0.78 drop table glpi_mailingsettings"); } $tables = array('glpi_infocoms' => __('Financial and administrative information'), 'glpi_reservationitems' => _n('Reservation', 'Reservations', 2), 'glpi_networkports' => _n('Network port', 'Network ports', 2)); foreach ($tables as $table => $label) { // Migrate infocoms entity information if (!FieldExists($table, 'entities_id', false)) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $label)); $query = "ALTER TABLE `{$table}`\n ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `itemtype`,\n ADD `is_recursive` tinyint(1) NOT NULL DEFAULT 0 AFTER `entities_id`,\n ADD INDEX `entities_id` ( `entities_id` ),\n ADD INDEX `is_recursive` (`is_recursive`)"; $DB->queryOrDie($query, "0.78 add entities_id and is_recursive in {$table}"); $entities = getAllDatasFromTable('glpi_entities'); $entities[0] = "Root"; $query = "SELECT DISTINCT `itemtype`\n FROM `{$table}`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), sprintf(__('%1$s - %2$s'), $label, $data['itemtype']))); $itemtable = getTableForItemType($data['itemtype']); // ajout d'un contrôle pour voir si la table existe ( cas migration plugin non fait) if (!TableExists($itemtable)) { $migration->displayWarning("*** Skip : no table {$itemtable} ***", true); continue; } $do_recursive = false; if (FieldExists($itemtable, 'is_recursive', false)) { $do_recursive = true; } // This is duplicated in Plugin::migrateItemType() for plugin object foreach ($entities as $entID => $val) { if ($do_recursive) { // Non recursive ones $query3 = "UPDATE `{$table}`\n SET `entities_id` = {$entID},\n `is_recursive` = 0\n WHERE `itemtype` = '" . $data['itemtype'] . "'\n AND `items_id` IN (SELECT `id`\n FROM `{$itemtable}`\n WHERE `entities_id` = {$entID}\n AND `is_recursive` = 0)"; $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=0 in {$table} for " . $data['itemtype']); // Recursive ones $query3 = "UPDATE `{$table}`\n SET `entities_id` = {$entID},\n `is_recursive` = 1\n WHERE `itemtype` = '" . $data['itemtype'] . "'\n AND `items_id` IN (SELECT `id`\n FROM `{$itemtable}`\n WHERE `entities_id` = {$entID}\n AND `is_recursive` = 1)"; $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=1 in {$table} for " . $data['itemtype']); } else { $query3 = "UPDATE `{$table}`\n SET `entities_id` = {$entID}\n WHERE `itemtype` = '" . $data['itemtype'] . "'\n AND `items_id` IN (SELECT `id`\n FROM `{$itemtable}`\n WHERE `entities_id` = {$entID})"; $DB->queryOrDie($query3, "0.78 update entities_id in {$table} for " . $data['itemtype']); } } } } } } } // Migrate consumable and cartridge and computerdisks entity information $items = array('glpi_cartridges' => 'glpi_cartridgeitems', 'glpi_consumables' => 'glpi_consumableitems', 'glpi_computerdisks' => 'glpi_computers'); foreach ($items as $linkitem => $sourceitem) { if (!FieldExists($linkitem, 'entities_id', false)) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $linkitem)); $query = "ALTER TABLE `{$linkitem}`\n ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `id`,\n ADD INDEX `entities_id` ( `entities_id` )"; $DB->queryOrDie($query, "0.78 add entities_id in {$linkitem}"); $entities = getAllDatasFromTable('glpi_entities'); $entities[0] = "Root"; foreach ($entities as $entID => $val) { $query3 = "UPDATE `{$linkitem}`\n SET `entities_id` = '{$entID}'\n WHERE " . getForeignKeyFieldForTable($sourceitem) . "\n IN (SELECT `id`\n FROM `{$sourceitem}`\n WHERE `entities_id` = '{$entID}' )"; $DB->queryOrDie($query3, "0.78 update entities_id in {$linkitem}"); } } } // Migrate softwareversions entity information if (!FieldExists('glpi_softwareversions', 'entities_id', false)) { $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_softwareversions')); $query = "ALTER TABLE `glpi_softwareversions`\n ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `id`,\n ADD INDEX `entities_id` ( `entities_id` ),\n ADD `is_recursive` tinyint(1) NOT NULL DEFAULT 0 AFTER `entities_id`,\n ADD INDEX `is_recursive` ( `is_recursive` )"; $DB->queryOrDie($query, "0.78 add entities_id in glpi_softwareversion"); $entities = getAllDatasFromTable('glpi_entities'); $entities[0] = "Root"; foreach ($entities as $entID => $val) { // Non recursive ones $query3 = "UPDATE `glpi_softwareversions`\n SET `entities_id` = {$entID},\n `is_recursive` = 0\n WHERE `softwares_id` IN (SELECT `id`\n FROM `glpi_softwares`\n WHERE `entities_id` = {$entID}\n AND `is_recursive` = 0)"; $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=0 in glpi_softwareversions"); // Recursive ones $query3 = "UPDATE `glpi_softwareversions`\n SET `entities_id` = {$entID},\n `is_recursive` = 1\n WHERE `softwares_id` IN (SELECT `id`\n FROM `glpi_softwares`\n WHERE `entities_id` = {$entID}\n AND `is_recursive` = 1)"; $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=1 in glpi_softwareversions"); } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_mailcollectors')); if (!FieldExists("glpi_mailcollectors", "is_active", false)) { $query = "ALTER TABLE `glpi_mailcollectors`\n ADD `is_active` tinyint( 1 ) NOT NULL DEFAULT '1',\n ADD INDEX `is_active` (`is_active`) "; $DB->queryOrDie($query, "0.78 add is_active in glpi_mailcollectors"); } if (!FieldExists('glpi_mailcollectors', 'date_mod', false)) { $query = "ALTER TABLE `glpi_mailcollectors`\n ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_mailcollectors"); } if (!FieldExists('glpi_mailcollectors', 'comment', false)) { $query = "ALTER TABLE `glpi_mailcollectors`\n ADD `comment` text collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add comment to glpi_mailcollectors"); } if (!FieldExists('glpi_profiles', 'rule_mailcollector', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `rule_mailcollector` CHAR( 1 ) NULL "; $DB->queryOrDie($query, "0.78 add rule_mailcollector to glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `rule_mailcollector` = `rule_ticket`"; $DB->queryOrDie($query, "0.78 set default rule_mailcollector same as rule_ticket"); } // Change search pref : add active / date_mod $ADDTODISPLAYPREF['MailCollector'] = array(2, 19); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_authldaps')); if (!FieldExists('glpi_authldaps', 'date_mod', false)) { $query = "ALTER TABLE `glpi_authldaps`\n ADD `date_mod` DATETIME NULL,\n ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_authldaps"); } if (!FieldExists('glpi_authldaps', 'comment', false)) { $query = "ALTER TABLE `glpi_authldaps`\n ADD `comment` text collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add comment to glpi_authldaps"); } // Change search pref : host, date_mod $ADDTODISPLAYPREF['AuthLDAP'] = array(3, 19); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_authldaps')); if (!FieldExists('glpi_authmails', 'date_mod', false)) { $query = "ALTER TABLE `glpi_authmails`\n ADD `date_mod` DATETIME NULL,\n ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_authmails"); } if (!FieldExists('glpi_authmails', 'comment', false)) { $query = "ALTER TABLE `glpi_authmails`\n ADD `comment` text collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add comment to glpi_authmails"); } // Change search pref : host, date_mod $ADDTODISPLAYPREF['AuthMail'] = array(3, 19); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_ocsservers')); if (!FieldExists('glpi_ocsservers', 'date_mod', false)) { $query = "ALTER TABLE `glpi_ocsservers`\n ADD `date_mod` DATETIME NULL,\n ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_ocsservers"); } if (!FieldExists('glpi_ocsservers', 'comment', false)) { $query = "ALTER TABLE `glpi_ocsservers`\n ADD `comment` text collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add comment to glpi_ocsservers"); } // Change search pref : date_mod / host $ADDTODISPLAYPREF['OcsServer'] = array(3, 19); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_profiles')); if (!FieldExists('glpi_profiles', 'date_mod', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `date_mod` DATETIME NULL,\n ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_profiles"); } if (!FieldExists('glpi_profiles', 'comment', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `comment` text collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add comment to glpi_profiles"); } // Change search pref : date_mod / host $ADDTODISPLAYPREF['Profile'] = array(2, 3, 19); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_printers')); if (!FieldExists('glpi_printers', 'have_ethernet', false)) { $query = "ALTER TABLE `glpi_printers`\n ADD `have_ethernet` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `have_usb`"; $DB->queryOrDie($query, "0.78 add have_ethernet to glpi_printers"); } if (!FieldExists('glpi_printers', 'have_wifi', false)) { $query = "ALTER TABLE `glpi_printers`\n ADD `have_wifi` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `have_usb`"; $DB->queryOrDie($query, "0.78 add have_wifi to glpi_printers"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_profiles')); if (!FieldExists('glpi_transfers', 'date_mod', false)) { $query = "ALTER TABLE `glpi_transfers`\n ADD `date_mod` DATETIME NULL,\n ADD INDEX `date_mod` (`date_mod`)"; $DB->queryOrDie($query, "0.78 add date_mod to glpi_transfers"); } if (!FieldExists('glpi_transfers', 'comment', false)) { $query = "ALTER TABLE `glpi_transfers`\n ADD `comment` text collate utf8_unicode_ci"; $DB->queryOrDie($query, "0.78 add comment to glpi_transfers"); } // Change search pref : date_mod $ADDTODISPLAYPREF['Transfer'] = array(19); // Convert events $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_events')); $convert_types = array('tracking' => 'ticket', 'networking' => 'networkequipment', 'knowbase' => 'knowbaseitem', 'typedocs' => 'documenttype', 'mailgate' => 'mailcollector'); foreach ($convert_types as $from => $to) { $query2 = "UPDATE `glpi_events`\n SET `type` = '{$to}'\n WHERE `type` = '{$from}'"; $DB->queryOrDie($query2, "0.78 update events data"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticket bookmarks')); $query = "SELECT *\n FROM `glpi_bookmarks`\n WHERE `itemtype` = 'Ticket'\n AND `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); $newoptions = array(); foreach ($options as $key => $val) { switch ($key) { case "status": $newoptions['field'][$num] = 12; $newoptions['searchtype'][$num] = 'equals'; $newoptions['link'][$num] = 'AND'; if ($val == 'old_done' || $val == 'old_notdone') { $newoptions['contains'][$num] = 'closed'; } else { $newoptions['contains'][$num] = $val; } $num++; break; case "priority": if ($val != 0) { $newoptions['field'][$num] = 3; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "category": if ($val > 0) { $newoptions['field'][$num] = 7; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "request_type": if ($val > 0) { $newoptions['field'][$num] = 9; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "type": if ($val > 0 && isset($data['item']) && $data['item'] > 0) { $newoptions['itemtype2'][$num2] = $typetoname[$val]; $newoptions['field2'][$num2] = 1; $newoptions['searchtype2'][$num2] = 'equals'; $newoptions['contains2'][$num2] = $data['item']; $newoptions['link2'][$num2] = 'AND'; $num2++; } break; case "author": if ($val > 0) { $newoptions['field'][$num] = 4; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "group": if ($val > 0) { $newoptions['field'][$num] = 71; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "assign": if ($val > 0) { $newoptions['field'][$num] = 5; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "assign_group": if ($val > 0) { $newoptions['field'][$num] = 8; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "assign_ent": if ($val > 0) { $newoptions['field'][$num] = 6; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "recipient": if ($val > 0) { $newoptions['field'][$num] = 22; $newoptions['searchtype'][$num] = 'equals'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "date1": // begin from if (strlen($val) > 0 && $val != 'NULL') { $newoptions['field'][$num] = 15; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = '>=' . $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "date2": // begin to if (strlen($val) > 0 && $val != 'NULL') { $newoptions['field'][$num] = 15; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = '<=' . $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "enddate1": // end from if (strlen($val) > 0 && $val != 'NULL') { $newoptions['field'][$num] = 16; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = '>=' . $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "enddate2": // end to if (strlen($val) > 0 && $val != 'NULL') { $newoptions['field'][$num] = 16; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = '<=' . $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "datemod1": // mod from if (strlen($val) > 0 && $val != 'NULL') { $newoptions['field'][$num] = 19; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = '>=' . $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "datemod2": // mod to if (strlen($val) > 0 && $val != 'NULL') { $newoptions['field'][$num] = 19; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = '<=' . $val; $newoptions['link'][$num] = 'AND'; $num++; } break; case "tosearch": if (isset($data['search'])) { $search = trim($data['search']); if (strlen($search) > 0) { $first = false; if (strstr($data['search'], 'name')) { $newoptions['field'][$num] = 1; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = $first ? 'AND' : 'OR'; $first = false; $num++; } if (strstr($data['search'], 'contents')) { $newoptions['field'][$num] = 21; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = $first ? 'AND' : 'OR'; $first = false; $num++; } if (strstr($data['search'], 'followup')) { $newoptions['field'][$num] = 25; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = $first ? 'AND' : 'OR'; $first = false; $num++; } if (strstr($data['search'], 'ID')) { $newoptions['field'][$num] = 2; $newoptions['searchtype'][$num] = 'contains'; $newoptions['contains'][$num] = $val; $newoptions['link'][$num] = 'AND'; $first = false; $num++; } } } break; } } if ($num > 0 || $num2 > 0) { $newoptions['glpisearchcount'] = $num; $newoptions['glpisearchcount2'] = $num2; $newoptions['itemtype'] = 'Ticket'; $query2 = "UPDATE `glpi_bookmarks`\n SET `query` = '" . addslashes(Toolbox::append_params($newoptions)) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query2, "0.78 update ticket bookmarks"); } else { $query2 = "DELETE\n FROM `glpi_bookmarks`\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query2, "0.78 delete ticket bookmarks : cannot convert"); } // Lost paramaters //only_computers=1&contains=dddd&field=moboard.designation& } } } if (!TableExists('glpi_ticketvalidations')) { $query = "CREATE TABLE `glpi_ticketvalidations` (\n `id` int(11) NOT NULL auto_increment,\n `entities_id` int(11) NOT NULL default '0',\n `users_id` int(11) NOT NULL default '0',\n `tickets_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` varchar(255) collate utf8_unicode_ci default 'waiting',\n `submission_date` datetime default NULL,\n `validation_date` datetime default NULL,\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `users_id` (`users_id`),\n KEY `users_id_validate` (`users_id_validate`),\n KEY `tickets_id` (`tickets_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.78 create glpi_ticketvalidations"); $ADDTODISPLAYPREF['TicketValidation'] = array(3, 2, 8, 4, 9, 7); } if (!FieldExists('glpi_tickets', 'global_validation', false)) { $query = "ALTER TABLE `glpi_tickets`\n ADD `global_validation` varchar(255) collate utf8_unicode_ci default 'accepted',\n ADD INDEX `global_validation` (`global_validation`)"; $DB->queryOrDie($query, "0.78 add global_validation to glpi_tickets"); } if (!FieldExists('glpi_profiles', 'validate_ticket', false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `validate_ticket` char(1) collate utf8_unicode_ci default NULL"; $DB->queryOrDie($query, "0.78 add validate_ticket to glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `validate_ticket` = '1'\n WHERE `interface` = 'central' "; $DB->queryOrDie($query, "0.78 add validate_ticket write right to super-admin and admin profiles"); $query = "ALTER TABLE `glpi_profiles`\n ADD `create_validation` char(1) collate utf8_unicode_ci default NULL"; $DB->queryOrDie($query, "0.78 add create_validation to glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `create_validation` = `own_ticket`"; $DB->queryOrDie($query, "0.78 add create_validation right if can own ticket"); } if (FieldExists('glpi_mailcollectors', 'entities_id', false)) { $ranking = 1; // No mailcollector : set a default rule if (countElementsInTable('glpi_mailcollectors') == 0) { $query = "INSERT INTO `glpi_rules`\n VALUES (NULL, -1, 'RuleMailCollector', {$ranking}, 'Root', '', 'OR', 1, NULL,\n NULL)"; $DB->queryOrDie($query, "0.78 error inserting new default maigate rule"); if ($newID = $DB->insert_id()) { $query = "INSERT INTO `glpi_rulecriterias`\n VALUES (NULL, {$newID}, 'subject', 6, '/.*/')"; $DB->queryOrDie($query, "0.78 error getting new criteria for rule"); $query = "INSERT INTO `glpi_ruleactions`\n VALUES (NULL, {$newID}, 'assign', 'entities_id', '0')"; $DB->queryOrDie($query, "0.78 error getting new action for rule"); } } else { foreach (getAllDatasFromTable('glpi_mailcollectors') as $collector) { $query = "INSERT INTO `glpi_rules`\n VALUES (NULL, -1, 'RuleMailCollector', {$ranking}, '" . $collector['name'] . "', '',\n 'AND', 1, NULL, NULL)"; $DB->queryOrDie($query, "0.78 error inserting new maigate rule " . $collector['name']); if ($newID = $DB->insert_id()) { $query = "INSERT INTO `glpi_rulecriterias`\n VALUES (NULL, {$newID}, 'mailcollector', 0, '" . $collector['id'] . "')"; $DB->queryOrDie($query, "0.78 error getting new criteria for rule " . $collector['name']); $query = "INSERT INTO `glpi_ruleactions`\n VALUES (NULL, {$newID}, 'assign', 'entities_id',\n '" . $collector['entities_id'] . "')"; $DB->queryOrDie($query, "0.78 error getting new action for rule " . $collector['name']); } $ranking++; } } $query = "ALTER TABLE `glpi_mailcollectors`\n DROP INDEX `entities_id` "; $DB->queryOrDie($query, "0.78 drop index entities_id from glpi_mailcollectors"); $query = "ALTER TABLE `glpi_mailcollectors`\n DROP `entities_id` "; $DB->queryOrDie($query, "0.78 drop entities_id from glpi_mailcollectors"); $query = "DELETE\n FROM `glpi_displaypreferences`\n WHERE `itemtype` = 'MailCollector'\n AND `num` = '80'"; $DB->queryOrDie($query, "0.78 drop entities_id from collectors display preferences"); } if (!TableExists('glpi_notimportedemails')) { $query = "CREATE TABLE `glpi_notimportedemails` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `from` varchar(255) NOT NULL,\n `to` varchar(255) NOT NULL,\n `mailcollectors_id` int(11) NOT NULL DEFAULT '0',\n `date` datetime NOT NULL,\n `subject` text,\n `messageid` varchar(255) NOT NULL,\n `reason` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `users_id` (`users_id`),\n KEY `mailcollectors_id` (`mailcollectors_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=latin1;"; $DB->queryOrDie($query, "0.78 add table glpi_notimportedemails"); $ADDTODISPLAYPREF['NotImportedEmail'] = array(2, 5, 4, 6, 16, 19); } if (!FieldExists("glpi_profiles", "entity_rule_ticket", false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `entity_rule_ticket` CHAR( 1 ) NULL AFTER `rule_ticket`"; $DB->queryOrDie($query, "0.78 add entity_rule_ldap in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `entity_rule_ticket` = `rule_ticket`"; $DB->queryOrDie($query, "0.78 update default entity_rule_ticket rights"); $query = "UPDATE `glpi_profiles`\n SET `rule_ticket` = 'r'\n WHERE `rule_ticket` = 'w'"; $DB->queryOrDie($query, "0.78 update rule_ticket rights"); } if (!FieldExists('glpi_authldaps', 'is_default', false)) { $query = "ALTER TABLE `glpi_authldaps`\n ADD `is_default` TINYINT( 1 ) NOT NULL DEFAULT '0',\n ADD INDEX `is_default` (`is_default`)"; $DB->queryOrDie($query, "0.78 add is_default to glpi_authldaps"); $query = "SELECT COUNT(*) AS cpt\n FROM `glpi_authldaps`"; $result = $DB->query($query); $number_servers = $DB->result($result, 0, 'cpt'); if ($number_servers >= 1) { //If only one server defined if ($number_servers == 1) { $query = "SELECT `id`\n FROM `glpi_authldaps`"; $result = $DB->query($query); $ldapservers_id = $DB->result($result, 0, 'id'); } else { $query = "SELECT `auths_id`, COUNT(`auths_id`) AS cpt\n FROM `glpi_users`\n WHERE `authtype` = '3'\n GROUP BY `auths_id`\n ORDER BY `cpt` DESC"; $result = $DB->query($query); $ldapservers_id = $DB->result($result, 0, 'auths_id'); } $query = "UPDATE `glpi_authldaps`\n SET `is_default` = '1'\n WHERE `id` = '" . $ldapservers_id . "'"; $DB->queryOrDie($query, "0.78 set default directory"); } } if (TableExists('glpi_rulerightparameters')) { $query = "ALTER TABLE `glpi_rulerightparameters`\n ADD `comment` TEXT NOT NULL "; $DB->queryOrDie($query, "0.78 add comment to glpi_rulerightparameters"); $ADDTODISPLAYPREF['RuleRightParameter'] = array(11); } if (!FieldExists('glpi_rules', 'is_recursive', false)) { $query = "ALTER TABLE `glpi_rules`\n ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n ADD INDEX `is_recursive` (`is_recursive`)"; $DB->queryOrDie($query, "0.78 add is_recursive to glpi_rules"); $query = "UPDATE `glpi_rules`\n SET `entities_id` = '0'\n WHERE `entities_id` = '-1'"; $DB->queryOrDie($query, "0.78 set entities_id to 0 where value is -1 in glpi_rules"); $query = "UPDATE `glpi_rules`\n SET `is_recursive`='1'\n WHERE `sub_type` = 'RuleTicket'"; $DB->queryOrDie($query, "0.78 set is_recursive to 1 for RuleTicket in glpi_rules"); } if (!FieldExists('glpi_configs', 'user_deleted_ldap', false)) { $query = "ALTER TABLE `glpi_configs`\n ADD `user_deleted_ldap` TINYINT( 1 ) NOT NULL DEFAULT '0'"; $DB->queryOrDie($query, "0.78 add user_deleted_ldap to glpi_configs"); } if (!FieldExists("glpi_profiles", "group_add_followup", false)) { $query = "ALTER TABLE `glpi_profiles`\n ADD `group_add_followups` CHAR(1) NULL AFTER `add_followups`"; $DB->queryOrDie($query, "0.78 add budget in glpi_profiles"); $query = "UPDATE `glpi_profiles`\n SET `group_add_followups`=`global_add_followups`"; $DB->queryOrDie($query, "0.78 update default budget rights"); } if (!FieldExists("glpi_groups_users", "is_dynamic", false)) { $query = "ALTER TABLE `glpi_groups_users`\n ADD `is_dynamic` TINYINT( 1 ) NOT NULL DEFAULT '0'"; $DB->queryOrDie($query, "0.78 add is_dynamic in glpi_groups_users"); //If group comes from an LDAP directory, then update users belonging to it //by setting is_dynamic to 1 $query = "UPDATE `glpi_groups_users` SET `is_dynamic`='1'\n WHERE groups_id IN (SELECT `id`\n FROM `glpi_groups`\n WHERE (`ldap_group_dn` IS NOT NULL AND `ldap_group_dn` <> '')\n OR ((`ldap_field` IS NOT NULL AND `ldap_field` <> '')\n AND (`ldap_value` IS NOT NULL AND `ldap_value` <> '')))"; $DB->queryOrDie($query, "0.78 update is_dynamic in glpi_groups_users"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences')); // Add search values for tickets $ADDTODISPLAYPREF['Ticket'] = array(12, 19, 15, 3, 4, 5, 7); 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++ . "', '" . $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 (only for end message) $migration->executeMigration(); return $updateresult; }
/** * Replay collection rules on an existing DB for model dropdowns * * @param $offset offset used to begin (default 0) * @param $maxtime maximum time of process (reload at the end) (default 0) * * @return -1 on completion else current offset **/ function replayRulesOnExistingDBForModel($offset = 0, $maxtime = 0) { global $DB; if (isCommandLine()) { printf(__('Replay rules on existing database started on %s') . "\n", date("r")); } // Model check : need to check using manufacturer extra data if (strpos($this->item_table, 'models') === false) { _e('Error replaying rules'); return false; } $model_table = getPlural(str_replace('models', '', $this->item_table)); $model_field = getForeignKeyFieldForTable($this->item_table); // Need to give manufacturer from item table $Sql = "SELECT DISTINCT `glpi_manufacturers`.`id` AS idmanu,\n `glpi_manufacturers`.`name` AS manufacturer,\n `" . $this->item_table . "`.`id`,\n `" . $this->item_table . "`.`name` AS name,\n `" . $this->item_table . "`.`comment`\n FROM `" . $this->item_table . "`,\n `{$model_table}`\n LEFT JOIN `glpi_manufacturers`\n ON (`{$model_table}`.`manufacturers_id` = `glpi_manufacturers`.`id`)\n WHERE `{$model_table}`.`{$model_field}` = `" . $this->item_table . "`.`id`"; if ($offset) { $Sql .= " LIMIT " . intval($offset) . ",999999999"; } $result = $DB->query($Sql); $nb = $DB->numrows($result) + $offset; $i = $offset; if ($result && $nb > $offset) { // Step to refresh progressbar $step = $nb > 20 ? floor($nb / 20) : 1; $tocheck = array(); while ($data = $DB->fetch_assoc($result)) { if (!($i % $step)) { if (isCommandLine()) { printf(__('Replay rules on existing database: %1$s/%2$s') . "\r", $i, $nb); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } } // Model case if (isset($data["manufacturer"])) { $data["manufacturer"] = Manufacturer::processName(addslashes($data["manufacturer"])); } //Replay Type dictionnary $ID = Dropdown::importExternal(getItemTypeForTable($this->item_table), addslashes($data["name"]), -1, $data, addslashes($data["comment"])); if ($data['id'] != $ID) { $tocheck[$data["id"]][] = $ID; $sql = "UPDATE `{$model_table}`\n SET `{$model_field}` = '{$ID}'\n WHERE `{$model_field}` = '" . $data['id'] . "'"; if (empty($data['idmanu'])) { $sql .= " AND (`manufacturers_id` IS NULL\n OR `manufacturers_id` = '0')"; } else { $sql .= " AND `manufacturers_id` = '" . $data['idmanu'] . "'"; } $DB->query($sql); } $i++; if ($maxtime) { $crt = explode(" ", microtime()); if ($crt[0] + $crt[1] > $maxtime) { break; } } } foreach ($tocheck as $ID => $tab) { $sql = "SELECT COUNT(*)\n FROM `{$model_table}`\n WHERE `{$model_field}` = '{$ID}'"; $result = $DB->query($sql); $deletecartmodel = false; // No item left : delete old item if ($result && $DB->result($result, 0, 0) == 0) { $Sql = "DELETE\n FROM `" . $this->item_table . "`\n WHERE `id` = '{$ID}'"; $resdel = $DB->query($Sql); $deletecartmodel = true; } // Manage cartridge assoc Update items if ($this->getRuleClassName() == 'RuleDictionnaryPrinterModel') { $sql = "SELECT *\n FROM `glpi_cartridgeitems_printermodels`\n WHERE `printermodels_id` = '{$ID}'"; if ($result = $DB->query($sql)) { if ($DB->numrows($result)) { // Get compatible cartridge type $carttype = array(); while ($data = $DB->fetch_assoc($result)) { $carttype[] = $data['cartridgeitems_id']; } // Delete cartrodges_assoc if ($deletecartmodel) { $sql = "DELETE\n FROM `glpi_cartridgeitems_printermodels`\n WHERE `printermodels_id` = 'id'"; $DB->query($sql); } // Add new assoc $ct = new CartridgeItem(); foreach ($carttype as $cartID) { foreach ($tab as $model) { $ct->addCompatibleType($cartID, $model); } } } } } } // each tocheck } if (isCommandLine()) { printf(__('Replay rules on existing database ended on %s') . "\n", date("r")); } else { Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}"); } return $i == $nb ? -1 : $i; }
/** * Clean Rule with Action or Criteria linked to an item * * @param $item Object * @param $field string name (default is FK to item) * @param $ruleitem object (instance of Rules of SlaLevel) * @param $table string (glpi_ruleactions, glpi_rulescriterias or glpi_slalevelcriterias) * @param $valfield string (value or pattern) * @param $fieldfield string (criteria of field) **/ private static function cleanForItemActionOrCriteria($item, $field, $ruleitem, $table, $valfield, $fieldfield) { global $DB; $fieldid = getForeignKeyFieldForTable($ruleitem->getTable()); if (empty($field)) { $field = getForeignKeyFieldForTable($item->getTable()); } if (isset($item->input['_replace_by']) && $item->input['_replace_by'] > 0) { $query = "UPDATE `{$table}`\n SET `{$valfield}` = '" . $item->input['_replace_by'] . "'\n WHERE `{$valfield}` = '" . $item->getField('id') . "'\n AND `{$fieldfield}` LIKE '{$field}'"; $DB->query($query); } else { $query = "SELECT `{$fieldid}`\n FROM `{$table}`\n WHERE `{$valfield}` = '" . $item->getField('id') . "'\n AND `{$fieldfield}` LIKE '{$field}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $input['is_active'] = 0; while ($data = $DB->fetch_assoc($result)) { $input['id'] = $data[$fieldid]; $ruleitem->update($input); } Session::addMessageAfterRedirect(__('Rules using the object have been disabled.'), true); } } } }
/** * Can I change recusvive flag to false * check if there is "linked" object in another entity * * May be overloaded if needed * * @return booleen **/ function canUnrecurs() { global $DB, $CFG_GLPI; $ID = $this->fields['id']; if ($ID < 0 || !$this->fields['is_recursive']) { return true; } $entities = "('" . $this->fields['entities_id'] . "'"; foreach (getAncestorsOf("glpi_entities", $this->fields['entities_id']) as $papa) { $entities .= ",'{$papa}'"; } $entities .= ")"; $RELATION = getDbRelations(); if ($this instanceof CommonTreeDropdown) { $f = getForeignKeyFieldForTable($this->getTable()); if (countElementsInTable($this->getTable(), "`{$f}`='{$ID}' AND entities_id NOT IN {$entities}") > 0) { return false; } } if (isset($RELATION[$this->getTable()])) { foreach ($RELATION[$this->getTable()] as $tablename => $field) { $itemtype = getItemTypeForTable($tablename); $item = new $itemtype(); if ($item->isEntityAssign()) { // 1->N Relation if (is_array($field)) { foreach ($field as $f) { if (countElementsInTable($tablename, "`{$f}`='{$ID}' AND entities_id NOT IN {$entities}") > 0) { return false; } } } else { if (countElementsInTable($tablename, "`{$field}`='{$ID}' AND entities_id NOT IN {$entities}") > 0) { return false; } } } else { foreach ($RELATION as $othertable => $rel) { // Search for a N->N Relation with devices if ($othertable == "_virtual_device" && isset($rel[$tablename])) { $devfield = $rel[$tablename][0]; // items_id... $typefield = $rel[$tablename][1]; // itemtype... $sql = "SELECT DISTINCT `{$typefield}` AS itemtype\n FROM `{$tablename}`\n WHERE `{$field}`='{$ID}'"; $res = $DB->query($sql); // Search linked device of each type if ($res) { while ($data = $DB->fetch_assoc($res)) { $itemtype = $data["itemtype"]; $itemtable = getTableForItemType($itemtype); $item = new $itemtype(); if ($item->isEntityAssign()) { if (countElementsInTable(array($tablename, $itemtable), "`{$tablename}`.`{$field}`='{$ID}'\n AND `{$tablename}`.`{$typefield}`='{$itemtype}'\n AND `{$tablename}`.`{$devfield}`=`{$itemtable}`.id\n AND `{$itemtable}`.`entities_id`\n NOT IN {$entities}") > '0') { return false; } } } } // Search for another N->N Relation } else { if ($othertable != $this->getTable() && isset($rel[$tablename])) { $itemtype = getItemTypeForTable($othertable); $item = new $itemtype(); if ($item->isEntityAssign()) { if (is_array($rel[$tablename])) { foreach ($rel[$tablename] as $otherfield) { if (countElementsInTable(array($tablename, $othertable), "`{$tablename}`.`{$field}`='{$ID}'\n AND `{$tablename}`.`{$otherfield}`\n =`{$othertable}`.id\n AND `{$othertable}`.`entities_id`\n NOT IN {$entities}") > '0') { return false; } } } else { $otherfield = $rel[$tablename]; if (countElementsInTable(array($tablename, $othertable), "`{$tablename}`.`{$field}`={$ID}\n AND `{$tablename}`.`{$otherfield}`=`{$othertable}`.id\n AND `{$othertable}`.`entities_id`\n NOT IN {$entities}") > '0') { return false; } } } } } } } } } // Doc links to this item if ($this->getType() > 0 && countElementsInTable(array('glpi_documents_items', 'glpi_documents'), "`glpi_documents_items`.`items_id`='{$ID}'\n AND `glpi_documents_items`.`itemtype`=" . $this->getType() . "\n AND `glpi_documents_items`.`documents_id`=`glpi_documents`.`id`\n AND `glpi_documents`.`entities_id` NOT IN {$entities}") > '0') { return false; } // TODO : do we need to check all relations in $RELATION["_virtual_device"] for this item return true; }
function generatePdf($itemtype, $data, $saveas) { global $CFG_GLPI, $PDF, $DB; $ID = $data["id"]; //name if (!empty($data["name"])) { $name_item = Toolbox::decodeFromUtf8($data["name"]); } else { $name_item = ""; } //user if (!empty($data["users_id"])) { $user_item = Toolbox::decodeFromUtf8(Html::clean(getUserName($data["users_id"]))); } else { if (!empty($data["groups_id"])) { $user_item = Toolbox::decodeFromUtf8(Dropdown::getDropdownName("glpi_groups", $data["groups_id"])); } else { $user_item = ""; } } //fabricant if (!empty($data["manufacturers_id"])) { $fabricant_item = Toolbox::decodeFromUtf8(Dropdown::getDropdownName("glpi_manufacturers", $data["manufacturers_id"])); } else { $fabricant_item = ""; } //serial if (!empty($data["serial"])) { $serial_item = Toolbox::decodeFromUtf8($data["serial"]); } else { $serial_item = ""; } $class = $itemtype . "Type"; $item = new $class(); $typefield = getForeignKeyFieldForTable(getTableForItemType($itemtype . "Type")); $item->getFromDB($data[$typefield]); if (!empty($typefield) && !empty($item->fields["name"])) { $type_item = Toolbox::decodeFromUtf8($item->fields["name"]); } else { $type_item = ""; } //infocoms $ic = new Infocom(); if ($ic->getfromDBforDevice($itemtype, $ID)) { //immobilizationsheets_item if (!empty($ic->fields["immo_number"])) { $immobilizationsheets_item = Toolbox::decodeFromUtf8($ic->fields["immo_number"]); } else { $immobilizationsheets_item = ""; } //buy_date if (!empty($ic->fields["buy_date"])) { $buy_date_item = Toolbox::decodeFromUtf8(Html::convdate($ic->fields["buy_date"])); } else { $buy_date_item = ""; } //use_date if (!empty($ic->fields["use_date"])) { $use_date_item = Toolbox::decodeFromUtf8(Html::convdate($ic->fields["use_date"])); } else { $use_date_item = ""; } //order_number if (!empty($ic->fields["order_number"])) { $order_number_item = Toolbox::decodeFromUtf8($ic->fields["order_number"]); } else { $order_number_item = ""; } //value_item if (!empty($ic->fields["value"])) { $value_item = Toolbox::decodeFromUtf8(Html::clean(Html::formatNumber($ic->fields["value"]))); } else { $value_item = ""; } //sink_time if (!empty($ic->fields["sink_time"])) { $sink_time_item = Toolbox::decodeFromUtf8(sprintf(_n('%d year', '%d years', $ic->fields["sink_time"]), $ic->fields["sink_time"])); } else { $sink_time_item = ""; } //sink_type if (!empty($ic->fields["sink_type"])) { $sink_type_item = Toolbox::decodeFromUtf8(Infocom::getAmortTypeName($ic->fields["sink_type"])); } else { $sink_type_item = ""; } } else { $immobilizationsheets_item = ""; $buy_date_item = ""; $use_date_item = ""; $order_number_item = ""; $value_item = ""; $sink_time_item = ""; $sink_type_item = ""; } //composants $devtypes = self::getDeviceTypes(); if ($itemtype == 'Computer') { $device2 = new $devtypes[2](); $query2 = "SELECT `deviceprocessors_id`\n FROM `" . getTableForItemType('items_' . $devtypes[2]) . "`\n WHERE `items_id` = '{$ID}'"; $result2 = $DB->query($query2); $number2 = $DB->numrows($result2); $device3 = new $devtypes[3](); $query3 = "SELECT SUM(`size`) AS total\n FROM `" . getTableForItemType('items_' . $devtypes[3]) . "`\n WHERE `items_id` = '{$ID}'"; $result3 = $DB->query($query3); $number3 = $DB->numrows($result3); $query3b = "SELECT `devicememories_id`\n FROM `" . getTableForItemType('items_' . $devtypes[3]) . "`\n WHERE `items_id` = '{$ID}'"; $result3b = $DB->query($query3b); $number3b = $DB->numrows($result3b); $device4 = new $devtypes[4](); $query4 = "SELECT `deviceharddrives_id`,`capacity`\n FROM `" . getTableForItemType('items_' . $devtypes[4]) . "`\n WHERE `items_id` = '{$ID}'"; $result4 = $DB->query($query4); $number4 = $DB->numrows($result4); $device5 = new $devtypes[6](); $query5 = "SELECT `devicedrives_id`\n FROM `" . getTableForItemType('items_' . $devtypes[6]) . "`\n WHERE `items_id` = '{$ID}'"; $result5 = $DB->query($query5); $number5 = $DB->numrows($result5); if ($number2 != 0) { while ($data2 = $DB->fetch_array($result2)) { //proc_item if (!empty($data2["deviceprocessors_id"])) { $query_proc = "SELECT `designation`\n FROM `glpi_deviceprocessors`\n WHERE `id` = '" . $data2["deviceprocessors_id"] . "'"; $result_proc = $DB->query($query_proc); $number_proc = $DB->numrows($result_proc); if ($number_proc != 0) { while ($data_proc = $DB->fetch_array($result_proc)) { $proc_item = Toolbox::decodeFromUtf8($data_proc["designation"]); } } } } } else { $proc_item = ""; } if ($number3 != 0) { while ($data3 = $DB->fetch_array($result3)) { //ram_item $ram_item = $data3["total"]; } } else { $ram_item = ""; } $ram_type_item = ""; if ($number3b != 0) { while ($data3b = $DB->fetch_array($result3b)) { //ram_type_item if (!empty($data3b["devicememories_id"])) { $query_ram = "SELECT `glpi_devicememorytypes`.`name`\n FROM `glpi_devicememories`,`glpi_devicememorytypes`\n WHERE `glpi_devicememories`.`id` = '" . $data3b["devicememories_id"] . "'\n AND `glpi_devicememorytypes`.`id` = `glpi_devicememories`.`devicememorytypes_id` "; $result_ram = $DB->query($query_ram); $number_ram = $DB->numrows($result_ram); if ($number_ram != 0) { while ($data_ram = $DB->fetch_array($result_ram)) { $ram_type_item = Toolbox::decodeFromUtf8($data_ram["name"]); } } else { $ram_type_item = ""; } } } } else { $ram_type_item = ""; } $hdd_item = ""; $hdd_designation_item = ""; $hdd_interface_item = ""; if ($number4 != 0) { while ($data4 = $DB->fetch_array($result4)) { //hdd_item $hdd_size_item = Toolbox::decodeFromUtf8($data4["capacity"]); if (!empty($data4["deviceharddrives_id"])) { $query_hdd = "SELECT `designation`\n FROM `glpi_deviceharddrives`\n WHERE `id` = '" . $data4["deviceharddrives_id"] . "'"; $result_hdd = $DB->query($query_hdd); $number_hdd = $DB->numrows($result_hdd); if ($number_hdd != 0) { while ($data_hdd = $DB->fetch_array($result_hdd)) { $hdd_designation_item = Toolbox::decodeFromUtf8($data_hdd["designation"]); } } else { $hdd_designation_item = ""; } $query_hdd1 = "SELECT `glpi_interfacetypes`.`name`\n FROM `glpi_deviceharddrives`,`glpi_interfacetypes`\n WHERE `glpi_deviceharddrives`.`id` = '" . $data4["deviceharddrives_id"] . "'\n AND `glpi_interfacetypes`.`id` = `glpi_deviceharddrives`.`interfacetypes_id` "; //replace interface by FK_interface 0.72.1 $result_hdd1 = $DB->query($query_hdd1); $number_hdd1 = $DB->numrows($result_hdd1); if ($number_hdd1 != 0) { while ($data_hdd1 = $DB->fetch_array($result_hdd1)) { $hdd_interface_item = Toolbox::decodeFromUtf8($data_hdd1["name"]); } } } else { $hdd_interface_item = ""; } $hdd_item .= $hdd_designation_item . " " . $hdd_interface_item . " (" . $hdd_size_item . " Mo)"; if ($number4 > 1) { $hdd_item .= " - "; } } } else { $hdd_item = ""; } $lecteur_item = ""; if ($number5 != 0) { while ($data5 = $DB->fetch_array($result5)) { //lecteur_item if (!empty($data5["items_id"])) { $query_lecteur = "SELECT `designation`\n FROM `glpi_devicedrives`\n WHERE `id` = '" . $data5["interfacetypes_id"] . "'"; $result_lecteur = $DB->query($query_lecteur); $number_lecteur = $DB->numrows($result_lecteur); if ($number_lecteur != 0) { while ($data_lecteur = $DB->fetch_array($result_lecteur)) { $lecteur_item .= Toolbox::decodeFromUtf8($data_lecteur["designation"]); if ($number5 > 1) { $lecteur_item .= " - "; } } } } } } else { $lecteur_item = ""; } //softwares $query6 = "SELECT `glpi_softwares`.`name`,`glpi_softwarelicenses`.`softwareversions_id_buy`,`glpi_softwarelicenses`.`serial`\n FROM `glpi_softwarelicenses`\n INNER JOIN `glpi_computers_softwarelicenses` ON (`glpi_softwarelicenses`.`id` = `glpi_computers_softwarelicenses`.`softwarelicenses_id` AND `glpi_computers_softwarelicenses`.`computers_id` = '{$ID}') \n INNER JOIN `glpi_softwares` ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`) "; $result6 = $DB->query($query6); $number6 = $DB->numrows($result6); } //Affichage //$PDF->addJpegFromFile('../pics/immobilizationsheets.jpg',285,785,32,32); //title $PDF->ezSetDy(-20); $title = array(array('' => Toolbox::decodeFromUtf8(__('IDENTIFICATION IMMOBILIZATION SHEET', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'center')); $PDF->ezTable($title, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 12, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $PDF->ezSetDy(-10); //partie 1 $PDF->ezSetDy(-20); $title1 = array(array('' => Toolbox::decodeFromUtf8(__('I - PART TO BE FILLED BY THE PERSON IN CHARGE FOR THE PURCHASES', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'left')); $PDF->ezTable($title1, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 10, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $title2 = array(array('' => Toolbox::decodeFromUtf8(__('(transfer the original to the administrator network so computer equipement, the assistant of management in the other cases)', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'left')); $PDF->ezTable($title2, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 8, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $PDF->ezSetDy(-10); //Date mise en service $PDF->ezText("<u>" . Toolbox::decodeFromUtf8(__('Startup date')) . "</u> : " . $buy_date_item, 8, array("justification" => "left")); $PDF->ezSetDy(-10); //ligne1 (entreprise / fournisseur) $data1 = array(array('0' => Toolbox::decodeFromUtf8(__('MY ENTERPRISE', 'immobilizationsheets')), '1' => Toolbox::decodeFromUtf8(strtoupper(__('Supplier'))))); $cols1 = array('0' => array('width' => 265, 'justification' => 'center'), '1' => array('width' => 265, 'justification' => 'center')); $PDF->ezTable($data1, '', __('COMPUTER IDENTIFICATION', 'immobilizationsheets'), array('showHeadings' => 0, 'cols' => $cols1)); //ligne2 (4 / 9) $data2 = array(array('0' => Toolbox::decodeFromUtf8(__('Assignment number (si non informatique)', 'immobilizationsheets')), '1' => '', '2' => Toolbox::decodeFromUtf8(__('Brand')), '3' => $fabricant_item)); $cols2 = array('0' => array('width' => 132.5, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 132.5, 'justification' => 'left'), '2' => array('width' => 132.5, 'justification' => 'left'), '3' => array('width' => 132.5, 'justification' => 'left')); $PDF->ezTable($data2, '', '', array('showHeadings' => 0, 'cols' => $cols2, 'fontSize' => 8)); //ligne3 (5 / 10) $data3 = array(array('0' => Toolbox::decodeFromUtf8(__('Invoice number')), '1' => $order_number_item, '2' => Toolbox::decodeFromUtf8(__('Type')), '3' => $type_item)); $cols3 = array('0' => array('width' => 132.5, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 132.5, 'justification' => 'left'), '2' => array('width' => 132.5, 'justification' => 'left'), '3' => array('width' => 132.5, 'justification' => 'left')); $PDF->ezTable($data3, '', '', array('showHeadings' => 0, 'cols' => $cols3, 'fontSize' => 8)); //ligne4 (6 / 11) $data4 = array(array('0' => Toolbox::decodeFromUtf8(__('Value')), '1' => $value_item, '2' => Toolbox::decodeFromUtf8(__('Serial Number')), '3' => $serial_item)); $cols4 = array('0' => array('width' => 132.5, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 132.5, 'justification' => 'left'), '2' => array('width' => 132.5, 'justification' => 'left'), '3' => array('width' => 132.5, 'justification' => 'left')); $PDF->ezTable($data4, '', '', array('showHeadings' => 0, 'cols' => $cols4, 'fontSize' => 8)); //ligne5 (7 / 12) $data5 = array(array('0' => Toolbox::decodeFromUtf8(__('Assignment (client / inv. …)', 'immobilizationsheets')), '1' => '', '2' => Toolbox::decodeFromUtf8(__('Permanent number', 'immobilizationsheets')), '3' => $immobilizationsheets_item)); $cols5 = array('0' => array('width' => 132.5, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 132.5, 'justification' => 'left'), '2' => array('width' => 132.5, 'justification' => 'left'), '3' => array('width' => 132.5, 'justification' => 'left')); $PDF->ezTable($data5, '', '', array('showHeadings' => 0, 'cols' => $cols5, 'fontSize' => 8)); $PDF->ezSetDy(-10); //trigramme $data6 = array(array('0' => Toolbox::decodeFromUtf8(__('Trigram and visa of the person in charge', 'immobilizationsheets')), '1' => '')); $cols6 = array('0' => array('width' => 430, 'fontSize' => 8, 'justification' => 'right'), '1' => array('width' => 100, 'justification' => 'left')); $PDF->ezTable($data6, '', '', array('showHeadings' => 0, 'cols' => $cols6, 'xPos' => 'center', 'xOreintation' => 'right', 'fontSize' => 8)); //partie 2 $PDF->ezSetDy(-20); $title1 = array(array('' => Toolbox::decodeFromUtf8(__('II - PART TO BE FILLED BY THE NETWORK ADMINISTRATOR', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'left')); $PDF->ezTable($title1, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 10, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $title2 = array(array('' => Toolbox::decodeFromUtf8(__('(transfer to the assistant of management)', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'left')); $PDF->ezTable($title2, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 8, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $PDF->ezSetDy(-10); //ligne1 (name / user) $data1 = array(array('0' => Toolbox::decodeFromUtf8(__('User name / sector', 'immobilizationsheets')), '1' => $user_item, '2' => Toolbox::decodeFromUtf8(__('Name')), '3' => $name_item)); $cols1 = array('0' => array('width' => 132.5, 'justification' => 'center'), '1' => array('width' => 132.5, 'justification' => 'center'), '2' => array('width' => 132.5, 'justification' => 'center'), '3' => array('width' => 132.5, 'justification' => 'center')); $PDF->ezTable($data1, '', __('PRINCIPAL ASSIGNMENT', 'immobilizationsheets'), array('fontSize' => 8, 'showHeadings' => 0, 'cols' => $cols1)); $PDF->ezSetDy(-10); if ($itemtype == 'Computer') { //title config mat?ielle $title = array(array('' => Toolbox::decodeFromUtf8(__('HARDWARE CONFIGURATION', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'center')); $PDF->ezTable($title, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 12, 'showLines' => 1)); $PDF->ezSetDy(-10); //ligne1 (processeur / ram quantit?/ ram type) $data1 = array(array('0' => Toolbox::decodeFromUtf8(__('Processor')), '1' => $proc_item, '2' => Toolbox::decodeFromUtf8(__('Memory')), '3' => Toolbox::decodeFromUtf8(__('Quantity', 'immobilizationsheets')), '4' => $ram_item, '5' => Toolbox::decodeFromUtf8(__('Type')), '6' => $ram_type_item)); $cols1 = array('0' => array('width' => 55, 'justification' => 'center'), '1' => array('width' => 200, 'justification' => 'left'), '2' => array('width' => 55, 'justification' => 'center'), '3' => array('width' => 55, 'justification' => 'center'), '4' => array('width' => 55, 'justification' => 'center'), '5' => array('width' => 55, 'justification' => 'center'), '6' => array('width' => 55, 'justification' => 'center')); $PDF->ezTable($data1, '', '', array('fontSize' => 8, 'showHeadings' => 0, 'cols' => $cols1)); //ligne2 (Disque dur / Lecteur) $data1 = array(array('0' => Toolbox::decodeFromUtf8(__('Hard drive')), '1' => $hdd_item, '2' => Toolbox::decodeFromUtf8(__('Drive')), '3' => $lecteur_item)); $cols1 = array('0' => array('width' => 55, 'justification' => 'center'), '1' => array('width' => 200, 'justification' => 'left'), '2' => array('width' => 55, 'justification' => 'center'), '3' => array('width' => 220, 'justification' => 'center')); $PDF->ezTable($data1, '', '', array('fontSize' => 8, 'showHeadings' => 0, 'cols' => $cols1)); $PDF->ezSetDy(-10); //titre suppl?ent $PDF->ezText("<u>" . Toolbox::decodeFromUtf8(__('Additional cards or peripherals', 'immobilizationsheets')) . "</u> : ", 8, array("justification" => "left")); $PDF->ezSetDy(-10); if ($number6 > 0) { //title config logicielle $title = array(array('' => Toolbox::decodeFromUtf8(__('SOFTWARE CONFIGURATION', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'center')); $PDF->ezTable($title, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 12, 'showLines' => 1)); $PDF->ezSetDy(-10); //titre logiciels $PDF->ezText("<u>" . Toolbox::decodeFromUtf8(__('Oem/Delivered software', 'immobilizationsheets')) . "</u> : ", 8, array("justification" => "left")); $PDF->ezSetDy(-10); //ligne1 (name / version / licence) $data0 = array(array('0' => Toolbox::decodeFromUtf8(__('Name')), '1' => Toolbox::decodeFromUtf8(__('Version')), '2' => Toolbox::decodeFromUtf8(__('License number')))); $cols1 = array('0' => array('width' => 240, 'justification' => 'left'), '1' => array('width' => 50, 'justification' => 'center'), '2' => array('width' => 240, 'justification' => 'center')); $PDF->ezTable($data0, '', '', array('fontSize' => 8, 'showHeadings' => 0, 'cols' => $cols1)); while ($data6 = $DB->fetch_array($result6)) { $soft_name_item = $data6["name"]; $soft_version_item = Dropdown::getDropdownName("glpi_softwareversions", $data6["softwareversions_id_buy"]); $soft_license_item = $data6["serial"]; $data1 = array(array('0' => $soft_name_item, '1' => $soft_version_item, '2' => $soft_license_item)); $cols1 = array('0' => array('width' => 240, 'justification' => 'left'), '1' => array('width' => 50, 'justification' => 'center'), '2' => array('width' => 240, 'justification' => 'center')); $PDF->ezTable($data1, '', '', array('fontSize' => 8, 'showHeadings' => 0, 'cols' => $cols1)); } $PDF->ezSetDy(-10); } } //trigramme $data6 = array(array('0' => Toolbox::decodeFromUtf8(__('Trigram and visa of the person in charge', 'immobilizationsheets')), '1' => '')); $cols6 = array('0' => array('width' => 430, 'fontSize' => 8, 'justification' => 'right'), '1' => array('width' => 100, 'justification' => 'left')); $PDF->ezTable($data6, '', '', array('showHeadings' => 0, 'cols' => $cols6, 'xPos' => 'center', 'xOreintation' => 'right', 'fontSize' => 8)); //partie 3 $PDF->ezSetDy(-20); $title1 = array(array('' => Toolbox::decodeFromUtf8(__('III - PART TO BE FILLED BY THE MANAGEMENT ASSISTANT', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'left')); $PDF->ezTable($title1, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 10, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $title2 = array(array('' => Toolbox::decodeFromUtf8(__('(for checking, visa and classification)', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'left')); $PDF->ezTable($title2, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 8, 'showLines' => 0, 'shaded' => 2, 'shadeCol' => array(0.8, 0.8, 0.8), 'shadeCol2' => array(0.8, 0.8, 0.8))); $PDF->ezSetDy(-20); //title $title = array(array('' => Toolbox::decodeFromUtf8(__('CALCULATION OF AMORTIZATION', 'immobilizationsheets')))); $cols = array('' => array('width' => 530, 'justification' => 'center')); $PDF->ezTable($title, '', '', array('cols' => $cols, 'showHeadings' => 0, 'fontSize' => 12, 'showLines' => 1)); $PDF->ezSetDy(-10); //Base d'amortissement $amort0 = array(array('0' => Toolbox::decodeFromUtf8(__('Base amortization', 'immobilizationsheets')), '1' => $sink_type_item)); $cols1 = array('0' => array('width' => 130, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 400, 'justification' => 'left')); $PDF->ezTable($amort0, '', '', array('showHeadings' => 0, 'cols' => $cols1, 'fontSize' => 8, 'showLines' => 0)); $PDF->ezSetDy(-10); //Duree d'amortissement $amort1 = array(array('0' => Toolbox::decodeFromUtf8(__('Amortization duration')), '1' => $sink_time_item)); $cols1 = array('0' => array('width' => 130, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 400, 'justification' => 'left')); $PDF->ezTable($amort1, '', '', array('showHeadings' => 0, 'cols' => $cols1, 'fontSize' => 8, 'showLines' => 0)); $PDF->ezSetDy(-10); //Date de debut d'amortissement $amort2 = array(array('0' => Toolbox::decodeFromUtf8(__('Date of beginning of amortization', 'immobilizationsheets')), '1' => $use_date_item)); $cols1 = array('0' => array('width' => 130, 'fontSize' => 8, 'justification' => 'left'), '1' => array('width' => 400, 'justification' => 'left')); $PDF->ezTable($amort2, '', '', array('showHeadings' => 0, 'cols' => $cols1, 'fontSize' => 8, 'showLines' => 0)); $PDF->ezSetDy(-10); //visa $amort1 = array(array('0' => Toolbox::decodeFromUtf8(__('VISA A.G.', 'immobilizationsheets')), '1' => "")); $cols6 = array('0' => array('width' => 430, 'fontSize' => 8, 'justification' => 'right'), '1' => array('width' => 100, 'justification' => 'left')); $PDF->ezTable($data6, '', '', array('showHeadings' => 0, 'cols' => $cols6, 'xPos' => 'center', 'xOreintation' => 'right', 'fontSize' => 8)); //end $PDF->addInfo('Author', Toolbox::decodeFromUtf8(Html::clean(getUserName(Session::getLoginUserID())))); $config = new PluginImmobilizationsheetsConfig(); if ($config->getFromDB(1)) { if ($saveas == 1) { if ($config->fields["use_backup"] == 1) { $path = GLPI_DOC_DIR . "/_uploads/"; $time_file = date("Y-m-d-H-i-s"); $filename = "immo_" . $time_file . "_" . $data["name"] . ".pdf"; $filepath = $path . $filename; $fp = fopen($filepath, 'wb'); fwrite($fp, $PDF->output()); fclose($fp); $doc = new document(); $input = array(); $input["entities_id"] = $data["entities_id"]; $input["name"] = addslashes(self::getTypeName(1) . " " . $data["name"] . " " . $time_file); $input["upload_file"] = $filename; $input["documentcategories_id"] = $config->fields["documentcategories_id"]; $input["type"] = "application/pdf"; $input["date_mod"] = date("Y-m-d H:i:s"); $input["users_id"] = Session::getLoginUserID(); $newdoc = $doc->add($input); $docitem = new Document_Item(); $docitem->add(array('documents_id' => $newdoc, 'itemtype' => $itemtype, 'items_id' => $ID, 'entities_id' => $input["entities_id"])); } } } }
/** * List value for a dropdown, with search criterias * for an authenticated user * * @param $params array of options (dropdown, id, parent, name) * @param $protocol the commonication protocol used * * @return array of hashtable **/ static function methodListDropdownValues($params, $protocol) { global $DB, $CFG_GLPI; if (isset($params['help'])) { return array('dropdown' => 'string,mandatory', 'id' => 'integer,optional', 'parent' => 'integer,optional', 'criteria' => 'string, optional', 'name' => 'string,optional', 'help' => 'bool,optional', 'start' => 'integer,optional', 'limit' => 'integer,optional'); } if (!Session::getLoginUserID()) { return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED); } if (!isset($params['dropdown'])) { return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER); } $resp = self::listSpecialDropdown($params['dropdown']); if (is_array($resp)) { return $resp; } if (class_exists($type = $params['dropdown'])) { $table = getTableForItemType($type); } else { if (TableExists($table = 'glpi_' . $params['dropdown'])) { $type = getItemTypeForTable($table); } } if (!($item = getItemForItemtype($type))) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', $params['dropdown']); } // Right check if (!$item instanceof CommonDropdown && !$item->canView()) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED); } $start = 0; $limit = $_SESSION['glpilist_limit']; if (isset($params['limit']) && is_numeric($params['limit'])) { $limit = $params['limit']; } if (isset($params['start']) && is_numeric($params['start'])) { $start = $params['start']; } // Minimal visible fields $fields = array('name', 'completename', 'comment', 'entities_id', 'is_recursive', 'is_incident', 'is_request', 'is_uploadable', 'ext'); $fields[] = getForeignKeyFieldForTable($table); $query = "SELECT `id`"; foreach ($fields as $field) { if ($item->isField($field)) { $query .= ", `{$field}`"; } } $query .= "\nFROM `{$table}`"; if (isset($params['id']) && is_numeric($params['id'])) { $query .= " WHERE `id` = '" . $params['id'] . "'"; } else { $query .= " WHERE 1"; } if ($item->isEntityAssign()) { $query .= getEntitiesRestrictRequest(" AND ", $table, '', '', $item->maybeRecursive()); } if (isset($params['parent']) && is_numeric($params['parent']) && $item instanceof CommonTreeDropdown) { $query .= " AND " . getForeignKeyFieldForTable($table) . "='" . $params['parent'] . "'"; } if (isset($params['helpdesk']) && $params['helpdesk'] && $item->isField('is_helpdeskvisible')) { $query .= " AND `is_helpdeskvisible` "; } if (isset($params['criteria']) && $params['criteria'] && $item->isField('is_' . $params['criteria'])) { $query .= " AND `is_" . $params['criteria'] . "` "; } if (isset($params['name'])) { if ($item instanceof CommonTreeDropdown) { $query .= " AND `completename` LIKE '" . addslashes($params['name']) . "'"; } else { $query .= " AND `name` LIKE '" . addslashes($params['name']) . "'"; } } $query .= " LIMIT {$start},{$limit}"; $resp = array(); foreach ($DB->request($query) as $data) { $resp[] = $data; } return $resp; }
/** 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']); } } }
/** * @see NotificationTargetCommonITILObject::getDatasForObject() **/ function getDatasForObject(CommonDBTM $item, array $options, $simple = false) { global $CFG_GLPI; // Common ITIL datas $datas = parent::getDatasForObject($item, $options, $simple); // Specific datas $datas['##change.urlvalidation##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $item->getField("id") . "_ChangeValidation\$1"); $datas['##change.globalvalidation##'] = ChangeValidation::getStatus($item->getField('global_validation')); // $datas["##problem.impacts##"] = $item->getField('impactcontent'); // $datas["##problem.causes##"] = $item->getField('causecontent'); // $datas["##problem.symptoms##"] = $item->getField('symptomcontent'); // Complex mode if (!$simple) { $restrict = "`changes_id`='" . $item->getField('id') . "'"; $tickets = getAllDatasFromTable('glpi_changes_tickets', $restrict); $datas['tickets'] = array(); if (count($tickets)) { $ticket = new Ticket(); foreach ($tickets as $data) { if ($ticket->getFromDB($data['tickets_id'])) { $tmp = array(); $tmp['##ticket.id##'] = $data['tickets_id']; $tmp['##ticket.date##'] = $ticket->getField('date'); $tmp['##ticket.title##'] = $ticket->getField('name'); $tmp['##ticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Ticket_" . $data['tickets_id']); $tmp['##ticket.content##'] = $ticket->getField('content'); $datas['tickets'][] = $tmp; } } } $datas['##change.numberoftickets##'] = count($datas['tickets']); $restrict = "`changes_id`='" . $item->getField('id') . "'"; $problems = getAllDatasFromTable('glpi_changes_problems', $restrict); $datas['problems'] = array(); if (count($problems)) { $problem = new Problem(); foreach ($problems as $data) { if ($problem->getFromDB($data['problems_id'])) { $tmp = array(); $tmp['##problem.id##'] = $data['problems_id']; $tmp['##problem.date##'] = $problem->getField('date'); $tmp['##problem.title##'] = $problem->getField('name'); $tmp['##problem.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Problem_" . $data['problems_id']); $tmp['##problem.content##'] = $problem->getField('content'); $datas['problems'][] = $tmp; } } } $datas['##change.numberofproblems##'] = count($datas['problems']); $restrict = "`changes_id` = '" . $item->getField('id') . "'"; $items = getAllDatasFromTable('glpi_changes_items', $restrict); $datas['items'] = array(); if (count($items)) { foreach ($items as $data) { if ($item2 = getItemForItemtype($data['itemtype'])) { if ($item2->getFromDB($data['items_id'])) { $tmp = array(); $tmp['##item.itemtype##'] = $item2->getTypeName(); $tmp['##item.name##'] = $item2->getField('name'); $tmp['##item.serial##'] = $item2->getField('serial'); $tmp['##item.otherserial##'] = $item2->getField('otherserial'); $tmp['##item.contact##'] = $item2->getField('contact'); $tmp['##item.contactnum##'] = $item2->getField('contactnum'); $tmp['##item.location##'] = ''; $tmp['##item.user##'] = ''; $tmp['##item.group##'] = ''; $tmp['##item.model##'] = ''; //Object location if ($item2->getField('locations_id') != NOT_AVAILABLE) { $tmp['##item.location##'] = Dropdown::getDropdownName('glpi_locations', $item2->getField('locations_id')); } //Object user if ($item2->getField('users_id')) { $user_tmp = new User(); if ($user_tmp->getFromDB($item2->getField('users_id'))) { $tmp['##item.user##'] = $user_tmp->getName(); } } //Object group if ($item2->getField('groups_id')) { $tmp['##item.group##'] = Dropdown::getDropdownName('glpi_groups', $item2->getField('groups_id')); } $modeltable = getSingular($item2->getTable()) . "models"; $modelfield = getForeignKeyFieldForTable($modeltable); if ($item2->isField($modelfield)) { $tmp['##item.model##'] = $item2->getField($modelfield); } $datas['items'][] = $tmp; } } } } $datas['##change.numberofitems##'] = count($datas['items']); //Validation infos $restrict = "`changes_id`='" . $item->getField('id') . "'"; if (isset($options['validation_id']) && $options['validation_id']) { $restrict .= " AND `glpi_changevalidations`.`id` = '" . $options['validation_id'] . "'"; } $restrict .= " ORDER BY `submission_date` DESC, `id` ASC"; $validations = getAllDatasFromTable('glpi_changevalidations', $restrict); $datas['validations'] = array(); foreach ($validations as $validation) { $tmp = array(); $tmp['##validation.submission.title##'] = sprintf(__('An approval request has been submitted by %s'), Html::clean(getUserName($validation['users_id']))); $tmp['##validation.answer.title##'] = sprintf(__('An answer to an an approval request was produced by %s'), Html::clean(getUserName($validation['users_id_validate']))); $tmp['##validation.author##'] = Html::clean(getUserName($validation['users_id'])); $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']); $tmp['##validation.storestatus##'] = $validation['status']; $tmp['##validation.submissiondate##'] = Html::convDateTime($validation['submission_date']); $tmp['##validation.commentsubmission##'] = $validation['comment_submission']; $tmp['##validation.validationdate##'] = Html::convDateTime($validation['validation_date']); $tmp['##validation.validator##'] = Html::clean(getUserName($validation['users_id_validate'])); $tmp['##validation.commentvalidation##'] = $validation['comment_validation']; $datas['validations'][] = $tmp; } } return $datas; }
public function dropdownAllItemsByType($name, $itemtype, $entity = 0, $types_id = 0, $models_id = 0) { switch ($itemtype) { case 'CartridgeItem': case 'ConsumableItem': case 'SoftwareLicense': $fk = getForeignkeyFieldForItemType($itemtype . "Type"); $condition = "`{$fk}` = '{$types_id}'"; $rand = Dropdown::show($itemtype, array('condition' => $condition, 'name' => $name, 'entity' => $entity, 'displaywith' => array('ref'))); break; default: $item = new $itemtype(); $and = ""; if (class_exists($itemtype . "Type", false)) { $and .= $types_id != 0 ? " AND `" . getForeignKeyFieldForTable(getTableForItemType($itemtype . "Type")) . "` = '{$types_id}' " : ""; } if (class_exists($itemtype . "Model", false)) { $and .= $models_id != 0 ? " AND `" . getForeignKeyFieldForTable(getTableForItemType($itemtype . "Model")) . "` ='{$models_id}' " : ""; } if ($item->maybeTemplate()) { $and .= " AND `is_template` = 0 "; } if ($item->maybeDeleted()) { $and .= " AND `is_deleted` = 0 "; } $table = getTableForItemType($itemtype); $condition = "1 {$and} AND `{$table}`.`id` NOT IN "; $condition .= "(SELECT `items_id` FROM `glpi_plugin_order_orders_items`\n WHERE `itemtype`='{$itemtype}' AND `items_id`!='0')"; $rand = Dropdown::show($itemtype, array('condition' => $condition, 'name' => $name, 'entity' => $entity, 'comments' => true, 'displaywith' => array('serial', 'otherserial'))); break; } return $rand; }
function showItemFromPlugin($instID, $face) { global $DB, $CFG_GLPI; if (!$this->canView()) { return false; } $rand = mt_rand(); $PluginRacksRack = new PluginRacksRack(); $PluginRacksConfig = new PluginRacksConfig(); if ($PluginRacksRack->getFromDB($instID)) { $canedit = $PluginRacksRack->can($instID, UPDATE); if ($canedit) { $this->AddItemToRack($PluginRacksRack, $instID, $face); } //LIST echo "<form method='post' name='racks_form{$rand}' id='racks_form{$rand}' \n action=\"" . PluginRacksRack::getFormURL(true) . "\">"; echo "<div class='center'><table class='tab_cadre_fixe'>"; echo "<tr><th colspan='12'>" . __('Rack enclosure arrangement', 'racks') . ":</th></tr><tr>"; if ($face == PluginRacksRack::FRONT_FACE) { $query = "SELECT `" . $this->getTable() . "`.*\n FROM `" . $this->getTable() . "`,`glpi_plugin_racks_itemspecifications`\n WHERE `" . $this->getTable() . "`.`plugin_racks_itemspecifications_id` = `glpi_plugin_racks_itemspecifications`.`id` \n AND `" . $this->getTable() . "`.`plugin_racks_racks_id` = '{$instID}'\n AND (`" . $this->getTable() . "`.`faces_id` = '" . PluginRacksRack::FRONT_FACE . "' \n OR (`" . $this->getTable() . "`.`faces_id` ='" . PluginRacksRack::BACK_FACE . "' \n AND `glpi_plugin_racks_itemspecifications`.`length` = 1 ))\n ORDER BY `" . $this->getTable() . "`.`position` ASC"; } else { $query = "SELECT `" . $this->getTable() . "`.*\n FROM `" . $this->getTable() . "`,`glpi_plugin_racks_itemspecifications`\n WHERE `" . $this->getTable() . "`.`plugin_racks_itemspecifications_id` = `glpi_plugin_racks_itemspecifications`.`id` \n AND `" . $this->getTable() . "`.`plugin_racks_racks_id` = '{$instID}'\n AND (`" . $this->getTable() . "`.`faces_id` = '" . PluginRacksRack::BACK_FACE . "' \n OR (`" . $this->getTable() . "`.`faces_id` ='" . PluginRacksRack::FRONT_FACE . "' \n AND `glpi_plugin_racks_itemspecifications`.`length` = 1 ))\n ORDER BY `" . $this->getTable() . "`.`position` ASC"; } $result = $DB->query($query); $number = $DB->numrows($result); $amps_tot = 0; $flow_rate_tot = 0; $dissip_tot = 0; $weight_tot = $PluginRacksRack->fields["weight"]; $nbcordons = 0; $nbcordons_tot = 0; $cordons_amps_tot = 0; $computer_tot = 0; $computer_size_tot = 0; $networking_tot = 0; $networking_size_tot = 0; $peripheral_tot = 0; $peripheral_size_tot = 0; $others_tot = 0; $others_size_tot = 0; $next = 0; $device_size = 0; echo "<th> </th>"; echo "<th>" . __('Position', 'racks') . "</th>"; echo "<th>" . __('Name') . "</th>"; // nom echo "<th>" . __('Type') . "</th>"; // type de materiel echo "<th>" . __('Model') . "</th>"; echo "<th>" . __('Power supply 1', 'racks') . "</th>"; //alim1 echo "<th>" . __('Power supply 2', 'racks') . "</th>"; //alim2 echo "<th>" . __('C13 Power Cord Quantity', 'racks') . "</th>"; // nb cordons echo "<th>" . __('Total Current', 'racks') . "<br>(" . __('amps', 'racks') . ")</th>"; // Courant consommé echo "<th>" . __('Calorific waste', 'racks') . "<br>"; // Dissipation calorifique echo " ("; $PluginRacksConfig->getUnit("dissipation"); echo ")</th>"; echo "<th>" . __('Flow Rate', 'racks') . "<br>"; // Débit d'air frais echo " ("; $PluginRacksConfig->getUnit("dissipation"); echo ")</th>"; echo "<th>" . __('Weight', 'racks') . "<br>"; // poids echo " ("; $PluginRacksConfig->getUnit("weight"); echo ")</th>"; echo "</tr>"; for ($i = $PluginRacksRack->fields['rack_size']; $i >= 1; $i--) { $alim1 = 0; $alim2 = 0; $j = $i; if ($i < 10) { $j = "0" . $i; } if ($face == PluginRacksRack::FRONT_FACE) { // recherche de l'equipement a la position courante $query = "SELECT `" . $this->getTable() . "`.*\n FROM `" . $this->getTable() . "`,`glpi_plugin_racks_itemspecifications`\n WHERE `" . $this->getTable() . "`.`plugin_racks_itemspecifications_id` = `glpi_plugin_racks_itemspecifications`.`id` \n AND `" . $this->getTable() . "`.`plugin_racks_racks_id` = '{$instID}'\n AND (`" . $this->getTable() . "`.`faces_id` = '" . PluginRacksRack::FRONT_FACE . "' \n OR (`" . $this->getTable() . "`.`faces_id` = '" . PluginRacksRack::BACK_FACE . "' \n AND `glpi_plugin_racks_itemspecifications`.`length` = 1)) AND `position` ='{$j}'\n ORDER BY `" . $this->getTable() . "`.`position` ASC"; } else { $query = "SELECT `" . $this->getTable() . "`.*\n FROM `" . $this->getTable() . "`,`glpi_plugin_racks_itemspecifications`\n WHERE `" . $this->getTable() . "`.`plugin_racks_itemspecifications_id` = `glpi_plugin_racks_itemspecifications`.`id` \n AND `" . $this->getTable() . "`.`plugin_racks_racks_id` = '{$instID}'\n AND (`" . $this->getTable() . "`.`faces_id` = '" . PluginRacksRack::BACK_FACE . "' \n OR (`" . $this->getTable() . "`.`faces_id` = '" . PluginRacksRack::FRONT_FACE . "' \n AND `glpi_plugin_racks_itemspecifications`.`length` = 1)) AND `position` ='{$j}'\n ORDER BY `" . $this->getTable() . "`.`position` ASC"; } $result = $DB->query($query); $number = $DB->numrows($result); // Si equipement if ($number != 0) { $data = $DB->fetch_array($result); $class = substr($data["itemtype"], 0, -5); $item = new $class(); $table = getTableForItemType($class); $r = $DB->query("SELECT * FROM `" . $table . "` WHERE `id` = '" . $data["items_id"] . "' "); $device = $DB->fetch_array($r); $modelclass = $data["itemtype"]; $model_table = getTableForItemType($modelclass); $modelfield = getForeignKeyFieldForTable(getTableForItemType($modelclass)); $query = "SELECT `" . $model_table . "`.`name` AS model,`" . $model_table . "`.`id` AS modelid, `glpi_plugin_racks_itemspecifications`.* \n FROM `glpi_plugin_racks_itemspecifications` " . " LEFT JOIN `" . $model_table . "` \n ON (`glpi_plugin_racks_itemspecifications`.`model_id` = `" . $model_table . "`.`id`)" . " LEFT JOIN `" . $table . "` \n ON (`glpi_plugin_racks_itemspecifications`.`model_id` = `" . $table . "`.`" . $modelfield . "` \n AND `glpi_plugin_racks_itemspecifications`.`itemtype` = '" . $modelclass . "')" . " WHERE `" . $table . "`.`id` = '" . $data["items_id"] . "' "; //Rack recursivity .getEntitiesRestrictRequest(" AND ",$table,'','',$item->maybeRecursive()) $res = $DB->query($query); $device_spec = $DB->fetch_array($res); $device_size = $device_spec["size"]; if ($data["first_powersupply"] > 0) { $nbcordons += 1; $nbcordons_tot += 1; } if ($data["second_powersupply"] > 0) { $nbcordons += 1; $nbcordons_tot += 1; } if ($data["itemtype"] == 'ComputerModel') { $computer_tot += 1; $computer_size_tot += $device_spec["size"]; } else { if ($data["itemtype"] == 'PeripheralModel') { $peripheral_tot += 1; $peripheral_size_tot += $device_spec["size"]; } else { if ($data["itemtype"] == 'NetworkEquipmentModel') { $networking_tot += 1; $networking_size_tot += $device_spec["size"]; } else { if ($data["itemtype"] == 'PluginRacksOtherModel') { $others_tot += 1; $others_size_tot += $device_spec["size"]; } } } } for ($t = 0; $t < $device_size; $t++) { if ($t == 0) { if ($data["itemtype"] == 'ComputerModel') { echo "<tr class='plugin_racks_device_computers_color'>"; } else { if ($data["itemtype"] == 'PeripheralModel') { echo "<tr class='plugin_racks_device_peripherals_color'>"; } else { if ($data["itemtype"] == 'NetworkEquipmentModel') { echo "<tr class='plugin_racks_device_networking_color'>"; } else { if ($data["itemtype"] == 'PluginRacksOtherModel') { echo "<tr class='plugin_racks_device_others_color'>"; } } } } echo "<td width='10' rowspan='" . $device_size . "'>"; $sel = ""; if (isset($_GET["select"]) && $_GET["select"] == "all") { $sel = "checked"; } echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1' {$sel}>"; echo "</td>"; echo "<td class='center'>U"; if ($canedit) { echo "<input type='text' size='3' name='position" . $data["id"] . "' value='{$j}'>"; echo " <input type='image' name='updateDevice[" . $data["id"] . "]' value=\"" . _sx('button', 'Save') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/actualiser.png' class='calendrier'>"; } else { echo $j; } echo "</td>"; $link = Toolbox::getItemTypeFormURL(substr($data["itemtype"], 0, -5)); if ($data["itemtype"] != 'PluginRacksOtherModel') { $name = "<a href=\"" . $link . "?id=" . $data["items_id"] . "\">" . $device["name"] . "</a>"; } else { $name = $device["name"]; } echo "<input type='hidden' name='plugin_racks_racks_id' value='" . $PluginRacksRack->fields['id'] . "'>"; echo "<input type='hidden' name='rack_size' value='" . $PluginRacksRack->fields['rack_size'] . "'>"; echo "<input type='hidden' name='type" . $data["id"] . "' value='" . $data["itemtype"] . "'>"; echo "<input type='hidden' name='items_id" . $data["id"] . "' value='" . $data["items_id"] . "'>"; echo "<input type='hidden' name='plugin_racks_itemspecifications_id" . $data["id"] . "' value='" . $data["plugin_racks_itemspecifications_id"] . "'>"; echo "<input type='hidden' name='update_server' value='1'>"; echo "<input type='hidden' name='faces_id' value='" . $face . "'>"; if ($data["itemtype"] != 'PluginRacksOtherModel') { echo "<td class='center' " . (isset($data['is_deleted']) && $data['is_deleted'] ? "class='tab_bg_2_2'" : "") . " >" . $name . "</td>"; } else { $PluginRacksOther = new PluginRacksOther(); $PluginRacksOther->GetfromDB($data["items_id"]); echo "<td class='center'><input type='text' name='name" . $data["id"] . "' value='" . $PluginRacksOther->fields["name"] . "' size='10'></td>"; } echo "<td class='center'>" . $item::getTypeName(2) . "</td>"; $linkmodel = Toolbox::getItemTypeFormURL($modelclass); echo "<td class='center'><a href=\"" . $linkmodel . "?id=" . $device_spec["modelid"] . "\">" . $device_spec["model"] . " (" . $device_spec["size"] . "U)</a></td>"; echo "<td class='center'>"; echo Dropdown::getDropdownName("glpi_plugin_racks_connections", $data["first_powersupply"]); echo "</td>"; echo "<td class='center'>"; echo Dropdown::getDropdownName("glpi_plugin_racks_connections", $data["second_powersupply"]); echo "</td>"; echo "<td class='center'>" . $nbcordons . "</td>"; if ($data["amps"] == '0.0000') { $amps = $device_spec["amps"]; } else { $amps = $data["amps"]; } $cordons_amps_tot += $amps * $nbcordons; echo "<td class='center'>" . Html::formatNumber($amps, true) . "</td>"; if ($data["dissipation"] == '0.0000') { $dissipation = $device_spec["dissipation"]; } else { $dissipation = $data["dissipation"]; } echo "<td class='center'>" . Html::formatNumber($dissipation, true) . "</td>"; if ($data["flow_rate"] == '0.0000') { $flow_rate = $device_spec["flow_rate"]; } else { $flow_rate = $data["flow_rate"]; } echo "<td class='center'>" . Html::formatNumber($flow_rate, true) . "</td>"; if ($data["weight"] == '0.0000') { $weight = $device_spec["weight"]; } else { $weight = $data["weight"]; } echo "<td class='center'>" . Html::formatNumber($weight, true) . "</td>"; echo "</tr>"; if ($data["amps"] == '0.0000') { $amps_tot += $device_spec["amps"]; } else { $amps_tot += $data["amps"]; } if ($data["flow_rate"] == '0.0000') { $flow_rate_tot += $device_spec["flow_rate"]; } else { $flow_rate_tot += $data["flow_rate"]; } if ($data["dissipation"] == '0.0000') { $dissip_tot += $device_spec["dissipation"]; } else { $dissip_tot += $data["dissipation"]; } if ($data["weight"] == '0.0000') { $weight_tot += $device_spec["weight"]; } else { $weight_tot += $data["weight"]; } } else { $name = $j - $t; if ($data["itemtype"] == 'ComputerModel') { echo "<tr class='plugin_racks_device_computers_color'>"; } else { if ($data["itemtype"] == 'PeripheralModel') { echo "<tr class='plugin_racks_device_peripherals_color'>"; } else { if ($data["itemtype"] == 'NetworkEquipmentModel') { echo "<tr class='plugin_racks_device_networking_color'>"; } else { if ($data["itemtype"] == 'PluginRacksOtherModel') { echo "<tr class='plugin_racks_device_others_color'>"; } } } } echo "<td class='center'>U{$name}</td><td colspan='10'></td></tr>"; } } if ($device_size > 1) { for ($d = 1; $d < $device_size; $d++) { $i--; } } } else { // Si pas d'equipement a la position courante echo "<tr class='tab_bg_1'><td></td><td class='center'>" . __('U', 'racks') . $j; echo "</td><td colspan='10'></td></tr>"; } $nbcordons = 0; } echo "<tr class='tab_bg_1'>"; echo "<td></td>"; echo "<td class='center'><b>" . __('Total') . "</b></td>"; echo "<td colspan='3' class='center'><b>"; if ($computer_tot != 0) { echo __('Total Servers', 'racks') . " : " . $computer_tot . " (" . $computer_size_tot . __('U', 'racks') . ")<br>"; } if ($networking_tot != 0) { echo __('Total Network equipements', 'racks') . " : " . $networking_tot . " (" . $networking_size_tot . __('U', 'racks') . ")<br>"; } if ($peripheral_tot != 0) { echo __('Total Peripherals', 'racks') . " : " . $peripheral_tot . " (" . $peripheral_size_tot . __('U', 'racks') . ")<br>"; } if ($others_tot != 0) { echo __('Total Others', 'racks') . " : " . $others_tot . " (" . $others_size_tot . __('U', 'racks') . ")<br>"; } //number of U availables $available = $PluginRacksRack->fields['rack_size'] - $computer_size_tot - $networking_size_tot - $peripheral_size_tot - $others_size_tot; if ($available > 0) { echo "<font color='green'>" . $available . " " . __('U availables', 'racks') . "</font>"; } else { echo "<font color='red'>" . $available . " " . __('U availables', 'racks') . "</font>"; } echo "</b></td>"; echo "<td colspan='3' class='center'><b>" . __('Total power Cords', 'racks') . " : " . $nbcordons_tot . "</b><br>"; echo "<b>" . __('Amperage on power Cords', 'racks') . " : " . $cordons_amps_tot . " " . __('amps', 'racks') . "</b></td>"; echo "<td class='center'><b>" . Html::formatNumber($amps_tot, true) . " " . __('amps', 'racks') . "</b></td>"; echo "<td class='center'><b>" . Html::formatNumber($dissip_tot, true) . " "; $PluginRacksConfig->getUnit("dissipation"); echo "</b></td>"; echo "<td class='center'><b>" . Html::formatNumber($flow_rate_tot, true) . " "; $PluginRacksConfig->getUnit("rate"); echo "</b></td>"; echo "<td class='center'><b>" . Html::formatNumber($weight_tot, true) . " "; $PluginRacksConfig->getUnit("weight"); echo "</b></td>"; echo "</tr>"; echo "</table></div>"; if ($canedit) { Html::openArrowMassives("racks_form{$rand}", true); Html::closeArrowMassives(array('deleteDevice' => _sx('button', 'Delete permanently'))); } else { echo "<input type='hidden' name='rack_size' value='" . $PluginRacksRack->fields['rack_size'] . "'>"; echo "</table></div>"; } Html::closeForm(); //////////////////////////////////////////////////// // Recherche des racks a gauche et a droite // Recuperation de la rangee $qPos = "SELECT `name`\n FROM `glpi_plugin_racks_roomlocations`\n WHERE `id` = '" . $PluginRacksRack->fields['plugin_racks_roomlocations_id'] . "' "; $rPos = $DB->query($qPos); $nbPos = $DB->numrows($rPos); $pos = ""; $next = ""; $prev = ""; if ($nbPos != 0) { $dataPos = $DB->fetch_array($rPos); $pos = $dataPos['name']; } // Incrementation & docrementation de la lettre de rang if (!empty($pos)) { // Z is the last letter... if ($pos[0] != "Z") { $next = chr(ord($pos[0]) + 1); for ($h = 1; $h < strlen($pos); $h++) { $next .= $pos[$h]; } } // A is the first letter.... if ($pos[0] != "A") { $prev = chr(ord($pos[0]) - 1); for ($h = 1; $h < strlen($pos); $h++) { $prev .= $pos[$h]; } } $qLeft = "SELECT `glpi_plugin_racks_racks`.`id`, `glpi_plugin_racks_roomlocations`.`name`\n FROM `glpi_plugin_racks_racks`\n LEFT JOIN `glpi_plugin_racks_roomlocations`\n ON (`glpi_plugin_racks_roomlocations`.`id` = `glpi_plugin_racks_racks`.`plugin_racks_roomlocations_id`)\n WHERE `glpi_plugin_racks_racks`.`is_deleted` = '0' AND `glpi_plugin_racks_roomlocations`.`name` = '" . $prev . "' " . getEntitiesRestrictRequest(" AND ", "glpi_plugin_racks_racks", '', '', $PluginRacksRack->maybeRecursive()); $rLeft = $DB->query($qLeft); $nb = $DB->numrows($rLeft); echo "<br><br>"; echo "<div align='center'><table border='0' width='950px'><tr><td class='left'>"; if ($nb != 0) { $left_racks = $DB->fetch_array($rLeft); echo "<a href =\"" . $CFG_GLPI["root_doc"] . "/plugins/racks/front/rack.form.php?id=" . $left_racks['id'] . "\">\n <img src=\"" . $CFG_GLPI["root_doc"] . "/pics/left.png\" alt=''> " . __('Left rack enclosure', 'racks') . " " . $left_racks['name'] . "</a>"; } else { echo __('No rack enclosure on the left', 'racks'); } echo "</td>"; echo "<td>"; echo "</td>"; echo "<td class='right'>"; $qRight = "SELECT `glpi_plugin_racks_racks`.`id`, `glpi_plugin_racks_roomlocations`.`name`\n FROM `glpi_plugin_racks_racks`\n LEFT JOIN `glpi_plugin_racks_roomlocations`\n ON (`glpi_plugin_racks_roomlocations`.`id` = `glpi_plugin_racks_racks`.`plugin_racks_roomlocations_id`)\n WHERE `glpi_plugin_racks_racks`.`is_deleted` = '0' AND `glpi_plugin_racks_roomlocations`.`name` = '" . $next . "' " . getEntitiesRestrictRequest(" AND ", "glpi_plugin_racks_racks", '', '', $PluginRacksRack->maybeRecursive()); $rRight = $DB->query($qRight); $nb = $DB->numrows($rRight); if ($nb != 0) { $right_racks = $DB->fetch_array($rRight); echo "<a href =\"" . $CFG_GLPI["root_doc"] . "/plugins/racks/front/rack.form.php?id=" . $right_racks['id'] . "\">" . __('Right rack enclosure', 'racks') . " " . $right_racks['name'] . " <img src=\"" . $CFG_GLPI["root_doc"] . "/pics/right.png\" alt=''></a>"; } else { echo __('No rack enclosure on the right', 'racks'); } echo "</td></tr></table></div>"; } } }
/** * 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"; }
function deleteItemSpecification($ID) { global $DB; $query_spec = "SELECT *\n FROM `" . $this->getTable() . "`\n WHERE `id` = '" . $ID . "' "; $result_spec = $DB->query($query_spec); while ($device = $DB->fetch_array($result_spec)) { $itemtype = $device['itemtype']; $modelfield = getForeignKeyFieldForTable(getTableForItemType($itemtype)); $table = getTableForItemType(substr($itemtype, 0, -5)); //delete items from racks $query_device = "SELECT `" . $table . "`.`id` FROM `" . $table . "`, `" . $this->getTable() . "` " . "WHERE `" . $this->getTable() . "`.`model_id` = `" . $table . "`.`" . $modelfield . "`\n AND `" . $this->getTable() . "`.`id` = '" . $ID . "'"; $result_device = $DB->query($query_device); while ($model = $DB->fetch_array($result_device)) { $query = "DELETE\n FROM `glpi_plugin_racks_racks_items`\n WHERE `itemtype` = '" . $itemtype . "'\n AND `items_id` ='" . $model['id'] . "';"; $result = $DB->query($query); } } $this->delete(array("id" => $ID)); }
/** * @see NotificationTargetCommonITILObject::getDatasForObject() **/ function getDatasForObject(CommonDBTM $item, array $options, $simple = false) { global $CFG_GLPI; // Common ITIL datas $datas = parent::getDatasForObject($item, $options, $simple); $datas['##ticket.description##'] = Html::clean($datas['##ticket.description##']); $datas['##ticket.description##'] = $item->convertContentForNotification($datas['##ticket.description##'], $item); $datas['##ticket.content##'] = $datas['##ticket.description##']; // Specific datas $datas['##ticket.urlvalidation##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . "_TicketValidation\$1"); $datas['##ticket.globalvalidation##'] = TicketValidation::getStatus($item->getField('global_validation')); $datas['##ticket.type##'] = Ticket::getTicketTypeName($item->getField('type')); $datas['##ticket.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $item->getField('requesttypes_id')); $autoclose_value = Entity::getUsedConfig('autoclose_delay', $this->getEntity(), '', Entity::CONFIG_NEVER); $datas['##ticket.autoclose##'] = __('Never'); $datas['##lang.ticket.autoclosewarning##'] = ""; if ($autoclose_value > 0) { $datas['##ticket.autoclose##'] = $autoclose_value; $datas['##lang.ticket.autoclosewarning##'] = sprintf(_n('Without a reply, the ticket will be automatically closed after %s day', 'Without a reply, the ticket will be automatically closed after %s days', $autoclose_value), $autoclose_value); } $datas['##ticket.sla##'] = ''; if ($item->getField('slas_id')) { $datas['##ticket.sla##'] = Dropdown::getDropdownName('glpi_slas', $item->getField('slas_id')); } $datas['##ticket.location##'] = ''; if ($item->getField('locations_id')) { $datas['##ticket.location##'] = Dropdown::getDropdownName('glpi_locations', $item->getField('locations_id')); } // is ticket deleted $datas['##ticket.isdeleted##'] = Dropdown::getYesNo($item->getField('is_deleted')); //Tags associated with the object linked to the ticket $datas['##ticket.itemtype##'] = ''; $datas['##ticket.item.name##'] = ''; $datas['##ticket.item.serial##'] = ''; $datas['##ticket.item.otherserial##'] = ''; $datas['##ticket.item.location##'] = ''; $datas['##ticket.item.contact##'] = ''; $datas['##ticket.item.contactnumber##'] = ''; $datas['##ticket.item.user##'] = ''; $datas['##ticket.item.group##'] = ''; $datas['##ticket.item.model##'] = ''; $item_ticket = new Item_Ticket(); $items = $item_ticket->find("`tickets_id` = '" . $item->getField('id') . "'"); $datas['items'] = array(); if (count($items)) { foreach ($items as $val) { if (isset($val['itemtype']) && ($hardware = getItemForItemtype($val['itemtype'])) && isset($val["items_id"]) && $hardware->getFromDB($val["items_id"])) { $tmp = array(); //Object type $tmp['##ticket.itemtype##'] = $hardware->getTypeName(); //Object name $tmp['##ticket.item.name##'] = $hardware->getField('name'); //Object serial if ($hardware->isField('serial')) { $tmp['##ticket.item.serial##'] = $hardware->getField('serial'); } //Object contact if ($hardware->isField('contact')) { $tmp['##ticket.item.contact##'] = $hardware->getField('contact'); } //Object contact num if ($hardware->isField('contact_num')) { $tmp['##ticket.item.contactnumber##'] = $hardware->getField('contact_num'); } //Object otherserial if ($hardware->isField('otherserial')) { $tmp['##ticket.item.otherserial##'] = $hardware->getField('otherserial'); } //Object location if ($hardware->isField('locations_id')) { $tmp['##ticket.item.location##'] = Dropdown::getDropdownName('glpi_locations', $hardware->getField('locations_id')); } //Object user if ($hardware->getField('users_id')) { $user_tmp = new User(); if ($user_tmp->getFromDB($hardware->getField('users_id'))) { $tmp['##ticket.item.user##'] = $user_tmp->getName(); } } //Object group if ($hardware->getField('groups_id')) { $tmp['##ticket.item.group##'] = Dropdown::getDropdownName('glpi_groups', $hardware->getField('groups_id')); } $modeltable = getSingular($hardware->getTable()) . "models"; $modelfield = getForeignKeyFieldForTable($modeltable); if ($hardware->isField($modelfield)) { $tmp['##ticket.item.model##'] = Dropdown::getDropdownName($modeltable, $hardware->getField($modelfield)); } $datas['items'][] = $tmp; } } } $datas['##ticket.numberofitems##'] = count($datas['items']); // Get followups, log, validation, satisfaction, linked tickets if (!$simple) { // Linked tickets $linked_tickets = Ticket_Ticket::getLinkedTicketsTo($item->getField('id')); $datas['linkedtickets'] = array(); if (count($linked_tickets)) { $linkedticket = new Ticket(); foreach ($linked_tickets as $data) { if ($linkedticket->getFromDB($data['tickets_id'])) { $tmp = array(); $tmp['##linkedticket.id##'] = $data['tickets_id']; $tmp['##linkedticket.link##'] = Ticket_Ticket::getLinkName($data['link']); $tmp['##linkedticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $data['tickets_id']); $tmp['##linkedticket.title##'] = $linkedticket->getField('name'); $tmp['##linkedticket.content##'] = $linkedticket->getField('content'); $datas['linkedtickets'][] = $tmp; } } } $datas['##ticket.numberoflinkedtickets##'] = count($datas['linkedtickets']); $restrict = "`tickets_id`='" . $item->getField('id') . "'"; $problems = getAllDatasFromTable('glpi_problems_tickets', $restrict); $datas['problems'] = array(); if (count($problems)) { $problem = new Problem(); foreach ($problems as $data) { if ($problem->getFromDB($data['problems_id'])) { $tmp = array(); $tmp['##problem.id##'] = $data['problems_id']; $tmp['##problem.date##'] = $problem->getField('date'); $tmp['##problem.title##'] = $problem->getField('name'); $tmp['##problem.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "problem_" . $data['problems_id']); $tmp['##problem.content##'] = $problem->getField('content'); $datas['problems'][] = $tmp; } } } $datas['##ticket.numberofproblems##'] = count($datas['problems']); $restrict = "`tickets_id`='" . $item->getField('id') . "'"; $changes = getAllDatasFromTable('glpi_changes_tickets', $restrict); $datas['changes'] = array(); if (count($changes)) { $change = new Change(); foreach ($changes as $data) { if ($change->getFromDB($data['changes_id'])) { $tmp = array(); $tmp['##change.id##'] = $data['changes_id']; $tmp['##change.date##'] = $change->getField('date'); $tmp['##change.title##'] = $change->getField('name'); $tmp['##change.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $data['changes_id']); $tmp['##change.content##'] = $change->getField('content'); $datas['changes'][] = $tmp; } } } $datas['##ticket.numberofchanges##'] = count($datas['changes']); if (!isset($options['additionnaloption']['show_private']) || !$options['additionnaloption']['show_private']) { $restrict .= " AND `is_private` = '0'"; } $restrict .= " ORDER BY `date` DESC, `id` ASC"; //Followup infos $followups = getAllDatasFromTable('glpi_ticketfollowups', $restrict); $datas['followups'] = array(); foreach ($followups as $followup) { $tmp = array(); $tmp['##followup.isprivate##'] = Dropdown::getYesNo($followup['is_private']); $tmp['##followup.author##'] = Html::clean(getUserName($followup['users_id'])); $tmp['##followup.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $followup['requesttypes_id']); $tmp['##followup.date##'] = Html::convDateTime($followup['date']); $tmp['##followup.description##'] = $followup['content']; $datas['followups'][] = $tmp; } $datas['##ticket.numberoffollowups##'] = count($datas['followups']); // Approbation of solution $restrict .= " LIMIT 1"; $replysolved = getAllDatasFromTable('glpi_ticketfollowups', $restrict); $data = current($replysolved); $datas['##ticket.solution.approval.description##'] = $data['content']; $datas['##ticket.solution.approval.date##'] = Html::convDateTime($data['date']); $datas['##ticket.solution.approval.author##'] = Html::clean(getUserName($data['users_id'])); //Validation infos $restrict = "`tickets_id`='" . $item->getField('id') . "'"; if (isset($options['validation_id']) && $options['validation_id']) { $restrict .= " AND `glpi_ticketvalidations`.`id` = '" . $options['validation_id'] . "'"; } $restrict .= " ORDER BY `submission_date` DESC, `id` ASC"; $validations = getAllDatasFromTable('glpi_ticketvalidations', $restrict); $datas['validations'] = array(); foreach ($validations as $validation) { $tmp = array(); $tmp['##validation.submission.title##'] = sprintf(__('An approval request has been submitted by %s'), Html::clean(getUserName($validation['users_id']))); $tmp['##validation.answer.title##'] = sprintf(__('An answer to an an approval request was produced by %s'), Html::clean(getUserName($validation['users_id_validate']))); $tmp['##validation.author##'] = Html::clean(getUserName($validation['users_id'])); $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']); $tmp['##validation.storestatus##'] = $validation['status']; $tmp['##validation.submissiondate##'] = Html::convDateTime($validation['submission_date']); $tmp['##validation.commentsubmission##'] = $validation['comment_submission']; $tmp['##validation.validationdate##'] = Html::convDateTime($validation['validation_date']); $tmp['##validation.validator##'] = Html::clean(getUserName($validation['users_id_validate'])); $tmp['##validation.commentvalidation##'] = $validation['comment_validation']; $datas['validations'][] = $tmp; } // Ticket Satisfaction $inquest = new TicketSatisfaction(); $datas['##satisfaction.type##'] = ''; $datas['##satisfaction.datebegin##'] = ''; $datas['##satisfaction.dateanswered##'] = ''; $datas['##satisfaction.satisfaction##'] = ''; $datas['##satisfaction.description##'] = ''; if ($inquest->getFromDB($item->getField('id'))) { // internal inquest if ($inquest->fields['type'] == 1) { $datas['##ticket.urlsatisfaction##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . '_Ticket$3'); // external inquest } else { if ($inquest->fields['type'] == 2) { $datas['##ticket.urlsatisfaction##'] = Entity::generateLinkSatisfaction($item); } } $datas['##satisfaction.type##'] = $inquest->getTypeInquestName($inquest->getfield('type')); $datas['##satisfaction.datebegin##'] = Html::convDateTime($inquest->fields['date_begin']); $datas['##satisfaction.dateanswered##'] = Html::convDateTime($inquest->fields['date_answered']); $datas['##satisfaction.satisfaction##'] = $inquest->fields['satisfaction']; $datas['##satisfaction.description##'] = $inquest->fields['comment']; } } return $datas; }
public function generateNewItem($params) { global $DB; // Retrieve plugin configuration $config = new PluginOrderConfig(); $reference = new PluginOrderReference(); foreach ($params["id"] as $tmp => $values) { //If itemtype cannot be generated, go to the new occurence if (in_array($values['itemtype'], self::getTypesThanCannotBeGenerared())) { continue; } $entity = $values["entities_id"]; //------------- Template management -----------------------// //Look for a template in the entity $templateID = $reference->checkIfTemplateExistsInEntity($values["id"], $values["itemtype"], $entity); $item = new $values["itemtype"](); if ($values['itemtype']) { $order = new PluginOrderOrder(); } $order->getFromDB($values["plugin_order_orders_id"]); $reference->getFromDB($params["plugin_order_references_id"]); if ($templateID) { $item->getFromDB($templateID); unset($item->fields["is_template"]); unset($item->fields["date_mod"]); $fields = array(); foreach ($item->fields as $key => $value) { if ($value != '' && (!isset($fields[$key]) || $fields[$key] == '' || $fields[$key] == 0)) { $input[$key] = $value; } } if ($config->getGeneratedAssetState()) { $input["states_id"] = $config->getGeneratedAssetState(); } $input["entities_id"] = $entity; $input["serial"] = $values["serial"]; if ($item->fields['name']) { $input["name"] = autoName($item->fields["name"], "name", $templateID, $values["itemtype"], $entity); } else { $input["name"] = $values["name"]; } if ($item->getField('otherserial') != NOT_AVAILABLE) { if ($item->fields['otherserial']) { $input["otherserial"] = autoName($item->fields["otherserial"], "otherserial", $templateID, $values["itemtype"], $entity); } else { $input["otherserial"] = $values["otherserial"]; } } if ($config->canAddLocation()) { $input['locations_id'] = $order->fields['locations_id']; } } elseif ($values["itemtype"] == 'Contract') { $input["name"] = $values["name"]; $input["entities_id"] = $entity; $input['contracttypes_id'] = $reference->fields['types_id']; } else { if ($config->getGeneratedAssetState()) { $input["states_id"] = $config->getGeneratedAssetState(); } else { $input["states_id"] = 0; } $input["entities_id"] = $entity; $input["serial"] = $values["serial"]; $input["otherserial"] = $values["otherserial"]; $input["name"] = $values["name"]; // Get bill data if ($config->canAddLocation()) { $input['locations_id'] = $order->fields['locations_id']; } $input["manufacturers_id"] = $reference->fields["manufacturers_id"]; $typefield = getForeignKeyFieldForTable(getTableForItemType($values["itemtype"] . "Type")); $input[$typefield] = $reference->fields["types_id"]; $modelfield = getForeignKeyFieldForTable(getTableForItemType($values["itemtype"] . "Model")); $input[$modelfield] = $reference->fields["models_id"]; } $input = Toolbox::addslashes_deep($input); $newID = $item->add($input); // Attach new ticket if option is on if (isset($params['generate_ticket'])) { $tkt = new TicketTemplate(); if ($tkt->getFromDB($params['generate_ticket']['tickettemplates_id'])) { $input = array(); $input = Ticket::getDefaultValues($entity); $ttp = new TicketTemplatePredefinedField(); $predefined = $ttp->getPredefinedFields($params['generate_ticket']['tickettemplates_id'], true); if (count($predefined)) { foreach ($predefined as $predeffield => $predefvalue) { $input[$predeffield] = $predefvalue; } } $input['entities_id'] = $entity; $input['_users_id_requester'] = empty($order->fields['users_id']) ? Session::getLoginUserID() : $order->fields['users_id']; $input['items_id'] = $newID; $input['itemtype'] = $values["itemtype"]; $ticket = new Ticket(); $ticketID = $ticket->add($input); } } //-------------- End template management ---------------------------------// $result = $this->createLinkWithItem($values["id"], $newID, $values["itemtype"], $values["plugin_order_orders_id"], $entity, $templateID, false, false); //Add item's history $new_value = __("Item generated by using order", "order") . ' : ' . $order->fields["name"]; $order->addHistory($values["itemtype"], '', $new_value, $newID); //Add order's history $new_value = __("Item generated by using order", "order") . ' : '; $new_value .= $item->getTypeName() . " -> " . $item->getField("name"); $order->addHistory('PluginOrderOrder', '', $new_value, $values["plugin_order_orders_id"]); //Copy order documents if needed self::copyDocuments($values['itemtype'], $newID, $values["plugin_order_orders_id"], $entity); Session::addMessageAfterRedirect(__("Item successfully selected", "order"), true); } }
/** * Show Default Report * * @since version 0.84 **/ static function showDefaultReport() { global $DB; # Title echo "<span class='big b'>GLPI " . Report::getTypeName(2) . "</span><br><br>"; # 1. Get counts of itemtype $items = array('Computer', 'Printer', 'NetworkEquipment', 'Software', 'Monitor', 'Peripheral', 'Phone'); $linkitems = array('Printer', 'Monitor', 'Peripheral', 'Phone'); echo "<table class='tab_cadrehov'>"; foreach ($items as $itemtype) { $table_item = getTableForItemType($itemtype); $where = "WHERE `" . $table_item . "`.`is_deleted` = '0'\n AND `" . $table_item . "`.`is_template` = '0' "; $join = ""; if (in_array($itemtype, $linkitems)) { $join = "LEFT JOIN `glpi_computers_items`\n ON (`glpi_computers_items`.`itemtype` = '" . $itemtype . "'\n AND `glpi_computers_items`.`items_id` = `" . $table_item . "`.`id`)"; } $query = "SELECT COUNT(*)\n FROM `" . $table_item . "`\n {$join}\n {$where} " . getEntitiesRestrictRequest("AND", $table_item); $result = $DB->query($query); $number = $DB->result($result, 0, 0); echo "<tr class='tab_bg_2'><td>" . $itemtype::getTypeName(2) . "</td>"; echo "<td class='numeric'>{$number}</td></tr>"; } echo "<tr class='tab_bg_1'><td colspan='2' class='b'>" . __('Operating system') . "</td></tr>"; # 2. Get some more number data (operating systems per computer) $where = "WHERE `is_deleted` = '0'\n AND `is_template` = '0' "; $query = "SELECT COUNT(*) AS count, `glpi_operatingsystems`.`name` AS name\n FROM `glpi_computers`\n LEFT JOIN `glpi_operatingsystems`\n ON (`glpi_computers`.`operatingsystems_id` = `glpi_operatingsystems`.`id`)\n {$where} " . getEntitiesRestrictRequest("AND", "glpi_computers") . "\n GROUP BY `glpi_operatingsystems`.`name`"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { if (empty($data['name'])) { $data['name'] = Dropdown::EMPTY_VALUE; } echo "<tr class='tab_bg_2'><td>" . $data['name'] . "</td>"; echo "<td class='numeric'>" . $data['count'] . "</td></tr>"; } # Get counts of types $val = array_flip($items); unset($val["Software"]); $items = array_flip($val); foreach ($items as $itemtype) { echo "<tr class='tab_bg_1'><td colspan='2' class='b'>" . $itemtype::getTypeName(2) . "</td></tr>"; $table_item = getTableForItemType($itemtype); $typeclass = $itemtype . "Type"; $type_table = getTableForItemType($typeclass); $typefield = getForeignKeyFieldForTable(getTableForItemType($typeclass)); $where = "WHERE `" . $table_item . "`.`is_deleted` = '0'\n AND `" . $table_item . "`.`is_template` = '0' "; $join = ""; if (in_array($itemtype, $linkitems)) { $join = "LEFT JOIN `glpi_computers_items`\n ON (`glpi_computers_items`.`itemtype` = '" . $itemtype . "'\n AND `glpi_computers_items`.`items_id` = `" . $table_item . "`.`id`)"; } $query = "SELECT COUNT(*) AS count, `" . $type_table . "`.`name` AS name\n FROM `" . $table_item . "`\n LEFT JOIN `" . $type_table . "`\n ON (`" . $table_item . "`.`" . $typefield . "`\n = `" . $type_table . "`.`id`)\n {$join}\n {$where} " . getEntitiesRestrictRequest("AND", $table_item) . "\n GROUP BY `" . $type_table . "`.`name`"; $result = $DB->query($query); while ($data = $DB->fetch_assoc($result)) { if (empty($data['name'])) { $data['name'] = Dropdown::EMPTY_VALUE; } echo "<tr class='tab_bg_2'><td>" . $data['name'] . "</td>"; echo "<td class='numeric'>" . $data['count'] . "</td></tr>"; } } echo "</table>"; }
static function getSoftwares($protocol, $params = array(), $original_params = array()) { global $DB, $WEBSERVICE_LINKED_OBJECTS; if (!Session::haveRight("software", READ)) { return array(); } $item = new $params['options']['itemtype'](); $resp = array(); $software = new Software(); //Store softwares, versions and licenses $softwares = array(); if ($item->can($params['data']['id'], READ) && $software->can(-1, READ)) { foreach (array('SoftwareVersion', 'SoftwareLicense') as $itemtype) { $link_table = "glpi_computers_" . Toolbox::addslashes_deep(strtolower($itemtype)) . "s"; $table = getTableForItemType($itemtype); $query = "SELECT DISTINCT `gsv`.*\n FROM `" . Toolbox::addslashes_deep($link_table) . "` AS gcsv,\n `" . Toolbox::addslashes_deep($table) . "` AS gsv\n WHERE `gcsv`.`computers_id`\n = '" . Toolbox::addslashes_deep($params['data']['id']) . "'\n AND `gcsv`.`" . getForeignKeyFieldForTable($table) . "` = `gsv`.`id`\n GROUP BY `gsv`.`softwares_id`\n ORDER BY `gsv`.`softwares_id` ASC"; foreach ($DB->request($query) as $version_or_license) { //Software is not yet in the list if (!isset($softwares['Software'][$version_or_license['softwares_id']])) { $software->getFromDB($version_or_license['softwares_id']); $toformat = array('data' => $software->fields, 'searchOptions' => Search::getOptions('Software'), 'options' => $params['options']); $tmp = array(); parent::formatDataForOutput($toformat, $tmp); $softwares['Software'][$version_or_license['softwares_id']] = $tmp; } $toformat2 = array('data' => $version_or_license, 'searchOptions' => Search::getOptions($itemtype), 'options' => $params['options']); $tmp = array(); parent::formatDataForOutput($toformat2, $tmp); $softwares['Software'][$version_or_license['softwares_id']][$itemtype][$version_or_license['id']] = $tmp; } } } return $softwares; }
static function getDeviceForeignKey() { return getForeignKeyFieldForTable(getTableForItemType(static::getDeviceType())); }
/** * 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; } }
/** * @param $itemtype * @param $type * @param $begin (default '') * @param $end (default '') * @param $param (default '') * @param $value (default '') * @param $value2 (default '') */ static function constructEntryValues($itemtype, $type, $begin = "", $end = "", $param = "", $value = "", $value2 = "") { global $DB; if (!($item = getItemForItemtype($itemtype))) { return; } $table = $item->getTable(); $fkfield = $item->getForeignKeyField(); if (!($userlinkclass = getItemForItemtype($item->userlinkclass))) { return; } $userlinktable = $userlinkclass->getTable(); if (!($grouplinkclass = getItemForItemtype($item->grouplinkclass))) { return; } $grouplinktable = $grouplinkclass->getTable(); if (!($supplierlinkclass = getItemForItemtype($item->supplierlinkclass))) { return; } $supplierlinktable = $supplierlinkclass->getTable(); $tasktable = getTableForItemType($item->getType() . 'Task'); $closed_status = $item->getClosedStatusArray(); $solved_status = array_merge($closed_status, $item->getSolvedStatusArray()); $query = ""; $WHERE = "WHERE NOT `{$table}`.`is_deleted` " . getEntitiesRestrictRequest("AND", $table); $LEFTJOIN = ""; $LEFTJOINUSER = "******"; $LEFTJOINGROUP = "LEFT JOIN `{$grouplinktable}`\n ON (`{$grouplinktable}`.`{$fkfield}` = `{$table}`.`id`)"; $LEFTJOINSUPPLIER = "LEFT JOIN `{$supplierlinktable}`\n ON (`{$supplierlinktable}`.`{$fkfield}` = `{$table}`.`id`)"; switch ($param) { case "technicien": $LEFTJOIN = $LEFTJOINUSER; $WHERE .= " AND (`{$userlinktable}`.`users_id` = '{$value}'\n AND `{$userlinktable}`.`type`='" . CommonITILActor::ASSIGN . "')"; break; case "technicien_followup": $WHERE .= " AND `{$tasktable}`.`users_id` = '{$value}'"; $LEFTJOIN = " LEFT JOIN `{$tasktable}`\n ON (`{$tasktable}`.`{$fkfield}` = `{$table}`.`id`)"; break; case "user": $LEFTJOIN = $LEFTJOINUSER; $WHERE .= " AND (`{$userlinktable}`.`users_id` = '{$value}'\n AND `{$userlinktable}`.`type` ='" . CommonITILActor::REQUESTER . "')"; break; case "usertitles_id": $LEFTJOIN = $LEFTJOINUSER; $LEFTJOIN .= " LEFT JOIN `glpi_users`\n ON (`glpi_users`.`id` = `{$userlinktable}`.`users_id`)"; $WHERE .= " AND (`glpi_users`.`usertitles_id` = '{$value}'\n AND `{$userlinktable}`.`type` = '" . CommonITILActor::REQUESTER . "')"; break; case "usercategories_id": $LEFTJOIN = $LEFTJOINUSER; $LEFTJOIN .= " LEFT JOIN `glpi_users`\n ON (`glpi_users`.`id` = `{$userlinktable}`.`users_id`)"; $WHERE .= " AND (`glpi_users`.`usercategories_id` = '{$value}'\n AND `{$userlinktable}`.`type` = '" . CommonITILActor::REQUESTER . "')"; break; case "itilcategories_tree": if ($value == $value2) { $categories = array($value); } else { $categories = getSonsOf("glpi_itilcategories", $value); } $condition = implode("','", $categories); $WHERE .= " AND `{$table}`.`itilcategories_id` IN ('{$condition}')"; break; case 'locations_tree': if ($value == $value2) { $categories = array($value); } else { $categories = getSonsOf('glpi_locations', $value); } $condition = implode("','", $categories); $WHERE .= " AND `{$table}`.`locations_id` IN ('{$condition}')"; break; case 'group_tree': case 'groups_tree_assign': $grptype = $param == 'group_tree' ? CommonITILActor::REQUESTER : CommonITILActor::ASSIGN; if ($value == $value2) { $groups = array($value); } else { $groups = getSonsOf("glpi_groups", $value); } $condition = implode("','", $groups); $LEFTJOIN = $LEFTJOINGROUP; $WHERE .= " AND (`{$grouplinktable}`.`groups_id` IN ('{$condition}')\n AND `{$grouplinktable}`.`type` = '{$grptype}')"; break; case "group": $LEFTJOIN = $LEFTJOINGROUP; $WHERE .= " AND (`{$grouplinktable}`.`groups_id` = '{$value}'\n AND `{$grouplinktable}`.`type` = '" . CommonITILActor::REQUESTER . "')"; break; case "groups_id_assign": $LEFTJOIN = $LEFTJOINGROUP; $WHERE .= " AND (`{$grouplinktable}`.`groups_id` = '{$value}'\n AND `{$grouplinktable}`.`type` = '" . CommonITILActor::ASSIGN . "')"; break; case "suppliers_id_assign": $LEFTJOIN = $LEFTJOINSUPPLIER; $WHERE .= " AND (`{$supplierlinktable}`.`suppliers_id` = '{$value}'\n AND `{$supplierlinktable}`.`type` = '" . CommonITILActor::ASSIGN . "')"; break; case "requesttypes_id": case "solutiontypes_id": case "urgency": case "impact": case "priority": case "users_id_recipient": case "type": case "itilcategories_id": case 'locations_id': $WHERE .= " AND `{$table}`.`{$param}` = '{$value}'"; break; case "device": $devtable = getTableForItemType('Computer_' . $value2); $fkname = getForeignKeyFieldForTable(getTableForItemType($value2)); //select computers IDs that are using this device; $LEFTJOIN = ''; $linkdetable = $table; if ($itemtype == 'Ticket') { $linkedtable = 'glpi_items_tickets'; $LEFTJOIN .= " LEFT JOIN `glpi_items_tickets`\n ON (`glpi_tickets`.`id` = `glpi_items_tickets`.`tickets_id`)"; } $LEFTJOIN .= " INNER JOIN `glpi_computers`\n ON (`glpi_computers`.`id` = `{$linkedtable}`.`items_id`\n AND `{$linkedtable}`.`itemtype` = 'Computer')\n INNER JOIN `{$devtable}`\n ON (`glpi_computers`.`id` = `{$devtable}`.`computers_id`\n AND `{$devtable}`.`{$fkname}` = '{$value}')"; $WHERE .= " AND `glpi_computers`.`is_template` <> '1' "; break; case "comp_champ": $ftable = getTableForItemType($value2); $champ = getForeignKeyFieldForTable($ftable); $LEFTJOIN = ''; $linkdetable = $table; if ($itemtype == 'Ticket') { $linkedtable = 'glpi_items_tickets'; $LEFTJOIN .= " LEFT JOIN `glpi_items_tickets`\n ON (`glpi_tickets`.`id` = `glpi_items_tickets`.`tickets_id`)"; } $LEFTJOIN .= " INNER JOIN `glpi_computers`\n ON (`glpi_computers`.`id` = `{$linkedtable}`.`items_id`\n AND `{$linkedtable}`.`itemtype` = 'Computer')"; $WHERE .= " AND `glpi_computers`.`{$champ}` = '{$value}'\n AND `glpi_computers`.`is_template` <> '1'"; break; } switch ($type) { case "inter_total": $WHERE .= " AND " . getDateRequest("`{$table}`.`date`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`date`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`date`"; break; case "inter_solved": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_solved_late": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND `{$table}`.`due_date` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end) . "\n AND `{$table}`.`solvedate` > `{$table}`.`due_date`"; $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_closed": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_avgsolvedtime": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n AVG(solve_delay_stat) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_avgclosedtime": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n AVG(close_delay_stat) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_avgactiontime": if ($param == "technicien_followup") { $actiontime_table = $tasktable; } else { $actiontime_table = $table; } $WHERE .= " AND `{$actiontime_table}`.`actiontime` > '0'\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n AVG(`{$actiontime_table}`.`actiontime`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_avgtakeaccount": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $solved_status) . "')\n AND `{$table}`.`solvedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`solvedate`", $begin, $end); $query = "SELECT `{$table}`.`id`,\n FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`solvedate`),'%Y-%m')\n AS date_unix,\n AVG(`{$table}`.`takeintoaccount_delay_stat`) AS total_visites\n FROM `{$table}`\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`solvedate`"; break; case "inter_opensatisfaction": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n INNER JOIN `glpi_ticketsatisfactions`\n ON (`{$table}`.`id` = `glpi_ticketsatisfactions`.`tickets_id`)\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_answersatisfaction": $WHERE .= " AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND `glpi_ticketsatisfactions`.`date_answered` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n COUNT(`{$table}`.`id`) AS total_visites\n FROM `{$table}`\n INNER JOIN `glpi_ticketsatisfactions`\n ON (`{$table}`.`id` = `glpi_ticketsatisfactions`.`tickets_id`)\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; case "inter_avgsatisfaction": $WHERE .= " AND `glpi_ticketsatisfactions`.`date_answered` IS NOT NULL\n AND `{$table}`.`status` IN ('" . implode("','", $closed_status) . "')\n AND `{$table}`.`closedate` IS NOT NULL\n AND " . getDateRequest("`{$table}`.`closedate`", $begin, $end); $query = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(`{$table}`.`closedate`),'%Y-%m')\n AS date_unix,\n AVG(`glpi_ticketsatisfactions`.`satisfaction`) AS total_visites\n FROM `{$table}`\n INNER JOIN `glpi_ticketsatisfactions`\n ON (`{$table}`.`id` = `glpi_ticketsatisfactions`.`tickets_id`)\n {$LEFTJOIN}\n {$WHERE}\n GROUP BY date_unix\n ORDER BY `{$table}`.`closedate`"; break; } $entrees = array(); $count = array(); if (empty($query)) { return array(); } $result = $DB->query($query); if ($result && $DB->numrows($result) > 0) { while ($row = $DB->fetch_assoc($result)) { $date = $row['date_unix']; //$visites = round($row['total_visites']); $entrees["{$date}"] = $row['total_visites']; } } // Remplissage de $entrees pour les mois ou il n'y a rien // $min=-1; // $max=0; // if (count($entrees)==0) { // return $entrees; // } // foreach ($entrees as $key => $val) { // $time=strtotime($key."-01"); // if ($min>$time || $min<0) { // $min=$time; // } // if ($max<$time) { // $max=$time; // } // } $end_time = strtotime(date("Y-m", strtotime($end)) . "-01"); $begin_time = strtotime(date("Y-m", strtotime($begin)) . "-01"); // if ($max<$end_time) { // $max=$end_time; // } // if ($min>$begin_time) { // $min=$begin_time; // } $current = $begin_time; while ($current <= $end_time) { $curentry = date("Y-m", $current); if (!isset($entrees["{$curentry}"])) { $entrees["{$curentry}"] = 0; } $month = date("m", $current); $year = date("Y", $current); $current = mktime(0, 0, 0, intval($month) + 1, 1, intval($year)); } ksort($entrees); return $entrees; }
/** * @covers ::getForeignKeyFieldForTable * @dataProvider dataTableKey **/ public function testGetForeignKeyFieldForTable($table, $key) { $this->assertEquals($key, getForeignKeyFieldForTable($table)); }