public function getAvailableValues() { if (!empty($this->fields['values'])) { $ldap_values = json_decode($this->fields['values']); $ldap_dropdown = new RuleRightParameter(); if (!$ldap_dropdown->getFromDB($ldap_values->ldap_attribute)) { return array(); } $attribute = array($ldap_dropdown->fields['value']); $config_ldap = new AuthLDAP(); if (!$config_ldap->getFromDB($ldap_values->ldap_auth)) { return array(); } if (!function_exists('warning_handler')) { function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) { if (0 === error_reporting()) { return false; } throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } } set_error_handler("warning_handler", E_WARNING); try { $tab_values = array(); $ds = $config_ldap->connect(); ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); $cookie = ''; do { if (AuthLDAP::isLdapPageSizeAvailable($config_ldap)) { ldap_control_paged_result($ds, $config_ldap->fields['pagesize'], true, $cookie); } $result = ldap_search($ds, $config_ldap->fields['basedn'], $ldap_values->ldap_filter, $attribute); $entries = ldap_get_entries($ds, $result); array_shift($entries); foreach ($entries as $id => $attr) { if (isset($attr[$attribute[0]]) && !in_array($attr[$attribute[0]][0], $tab_values)) { $tab_values[$id] = $attr[$attribute[0]][0]; } } if (AuthLDAP::isLdapPageSizeAvailable($config_ldap)) { ldap_control_paged_result_response($ds, $result, $cookie); } } while ($cookie !== null && $cookie != ''); if ($this->fields['show_empty']) { $tab_values = array('' => '-----') + $tab_values; } asort($tab_values); return $tab_values; } catch (Exception $e) { return array(); } restore_error_handler(); } else { return array(); } }
Session::addMessageAfterRedirect(__('Test successful')); } else { Session::addMessageAfterRedirect(__('Test failed'), false, ERROR); } Html::redirect($CFG_GLPI["root_doc"] . "/front/authldap.php?next=extauth_ldap&id=" . $newID); } } Html::back(); } else { if (isset($_POST["delete"])) { $config_ldap->delete($_POST); $_SESSION['glpi_authconfig'] = 1; $config_ldap->redirectToList(); } else { if (isset($_POST["test_ldap"])) { $config_ldap->getFromDB($_POST["id"]); if (AuthLdap::testLDAPConnection($_POST["id"])) { //TRANS: %s is the description of the test $_SESSION["LDAP_TEST_MESSAGE"] = sprintf(__('Test successful: %s'), sprintf(__('Main server %s'), $config_ldap->fields["name"])); } else { //TRANS: %s is the description of the test $_SESSION["LDAP_TEST_MESSAGE"] = sprintf(__('Test failed: %s'), sprintf(__('Main server %s'), $config_ldap->fields["name"])); } Html::back(); } else { if (isset($_POST["test_ldap_replicate"])) { foreach ($_POST["test_ldap_replicate"] as $replicate_id => $value) { $replicate = new AuthLdapReplicate(); $replicate->getFromDB($replicate_id); if (AuthLdap::testLDAPConnection($_POST["id"], $replicate_id)) { //TRANS: %s is the description of the test
/** * Display information from LDAP server for user **/ private function showLdapDebug() { if ($this->fields['authtype'] != Auth::LDAP) { return false; } echo "<div class='spaced'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='4'>" . __('LDAP directory') . "</th></tr>"; echo "<tr class='tab_bg_2'><td>" . __('User DN') . "</td>"; echo "<td>" . $this->fields['user_dn'] . "</td></tr>\n"; if ($this->fields['user_dn']) { echo "<tr class='tab_bg_2'><td>" . __('User information') . "</td><td>"; $config_ldap = new AuthLDAP(); $ds = false; if ($config_ldap->getFromDB($this->fields['auths_id'])) { $ds = $config_ldap->connect(); } if ($ds) { $info = AuthLdap::getUserByDn($ds, $this->fields['user_dn'], array('*', 'createTimeStamp', 'modifyTimestamp')); if (is_array($info)) { Html::printCleanArray($info); } else { _e('No item to display'); } } else { _e('Connection failed'); } echo "</td></tr>\n"; } echo "</table></div>"; }
/** * @param $authldap AuthLDAP object **/ static function showUserImportForm(AuthLDAP $authldap) { global $DB; //Get data related to entity (directory and ldap filter) $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); echo "<div class='center'>"; echo "<form method='post' action='" . $_SERVER['PHP_SELF'] . "'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='4' class='middle'><div class='relative'>"; echo "<span>" . ($_SESSION['ldap_import']['mode'] ? __('Synchronizing already imported users') : __('Import new users')); // Expert interface allow user to override configuration. // If not coming from the ticket form, then give expert/simple link if ((Config::canUpdate() || Entity::canUpdate()) && !isset($_SESSION['ldap_import']['no_expert_mode'])) { echo "</span> <span class='floatright'><a href='" . $_SERVER['PHP_SELF'] . "?action=" . $_SESSION['ldap_import']['action'] . "&mode=" . $_SESSION['ldap_import']['mode']; if ($_SESSION['ldap_import']['interface'] == self::SIMPLE_INTERFACE) { echo "&interface=" . self::EXPERT_INTERFACE . "'>" . __('Expert mode') . "</a>"; } else { echo "&interface=" . self::SIMPLE_INTERFACE . "'>" . __('Simple mode') . "</a>"; } } else { $_SESSION['ldap_import']['interface'] = self::SIMPLE_INTERFACE; } echo "</span></div>"; echo "</th></tr>"; switch ($_SESSION['ldap_import']['interface']) { case self::EXPERT_INTERFACE: //If more than one directory configured //Display dropdown ldap servers if ($_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && $_SESSION['ldap_import']['authldaps_id'] > 0) { if (self::getNumberOfServers() > 1) { echo "<tr class='tab_bg_2'><td>" . __('LDAP directory choice') . "</td>"; echo "<td colspan='3'>"; self::dropdown(array('name' => 'authldaps_id', 'value' => $_SESSION['ldap_import']['authldaps_id'], 'condition' => "`is_active` = '1'", 'display_emptychoice' => false)); echo " <input class='submit' type='submit' name='change_directory'\n value=\"" . _sx('button', 'To change') . "\">"; echo "</td></tr>"; } echo "<tr class='tab_bg_2'><td>" . __('BaseDN') . "</td><td colspan='3'>"; echo "<input type='text' class='form-control' name='basedn' value=\"" . $_SESSION['ldap_import']['basedn'] . "\" size='90' " . (!$_SESSION['ldap_import']['basedn'] ? "disabled" : "") . ">"; echo "</td></tr>"; echo "<tr class='tab_bg_2'><td>" . __('Search filter for users') . "</td><td colspan='3'>"; echo "<input type='text' class='form-control' name='ldap_filter' value=\"" . $_SESSION['ldap_import']['ldap_filter'] . "\" size='90'>"; echo "</td></tr>"; } break; //case self::SIMPLE_INTERFACE : //case self::SIMPLE_INTERFACE : default: //If multi-entity mode and more than one entity visible //else no need to select entity if (Session::isMultiEntitiesMode() && count($_SESSION['glpiactiveentities']) > 1) { echo "<tr class='tab_bg_2'><td>" . __('Select the desired entity') . "</td>" . "<td colspan='3'>"; Entity::dropdown(array('value' => $_SESSION['ldap_import']['entities_id'], 'entity' => $_SESSION['glpiactiveentities'], 'on_change' => 'submit()')); echo "</td></tr>"; } else { //Only one entity is active, store it echo "<tr><td><input type='hidden' name='entities_id' value='" . $_SESSION['glpiactive_entity'] . "'></td></tr>"; } if (isset($_SESSION['ldap_import']['begin_date']) && !empty($_SESSION['ldap_import']['begin_date']) || isset($_SESSION['ldap_import']['end_date']) && !empty($_SESSION['ldap_import']['end_date'])) { $enabled = 1; } else { $enabled = 0; } Dropdown::showAdvanceDateRestrictionSwitch($enabled); echo "<table class='tab_cadre_fixe'>"; if ($_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && $_SESSION['ldap_import']['authldaps_id'] > 0) { $field_counter = 0; $fields = array('login_field' => __('Login'), 'email1_field' => __('Email'), 'email2_field' => sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '2'), 'email3_field' => sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '3'), 'email4_field' => sprintf(__('%1$s %2$s'), _n('Email', 'Emails', 1), '4'), 'realname_field' => __('Surname'), 'firstname_field' => __('First name'), 'phone_field' => __('Phone'), 'phone2_field' => __('Phone 2'), 'mobile_field' => __('Mobile phone'), 'title_field' => _x('person', 'Title'), 'category_field' => __('Category'), 'picture_field' => __('Picture')); $available_fields = array(); foreach ($fields as $field => $label) { if (isset($authldap->fields[$field]) && $authldap->fields[$field] != '') { $available_fields[$field] = $label; } } echo "<tr><th colspan='4'>" . __('Search criteria for users') . "</th></tr>"; foreach ($available_fields as $field => $label) { if ($field_counter == 0) { echo "<tr class='tab_bg_1'>"; } echo "<td>{$label}</td><td>"; $field_counter++; echo "<input type='text' class='form-control' name='criterias[{$field}]' value='" . (isset($_SESSION['ldap_import']['criterias'][$field]) ? $_SESSION['ldap_import']['criterias'][$field] : '') . "'>"; echo "</td>"; if ($field_counter == 2) { echo "</tr>"; $field_counter = 0; } } if ($field_counter > 0) { while ($field_counter < 2) { echo "<td colspan='2'></td>"; $field_counter++; } $field_counter = 0; echo "</tr>"; } } break; } if ($_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && $_SESSION['ldap_import']['authldaps_id'] > 0) { if ($_SESSION['ldap_import']['authldaps_id']) { echo "<tr class='tab_bg_2'><td colspan='4' class='center'>"; echo "<input class='submit' type='submit' name='search' value=\"" . _sx('button', 'Search') . "\">"; echo "</td></tr>"; } else { echo "<tr class='tab_bg_2'><" . "td colspan='4' class='center'>" . __('No directory selected') . "</td></tr>"; } } else { echo "<tr class='tab_bg_2'><td colspan='4' class='center'>" . __('No directory associated to entity: impossible search') . "</td></tr>"; } echo "</table>"; Html::closeForm(); echo "</div>"; }
/** * Validate form fields before add or update a question * * @param Array $input Datas used to add the item * * @return Array The modified $input array * * @param [type] $input [description] * @return [type] [description] */ private function checkBeforeSave($input) { // Control fields values : // - name is required if (empty($input['name'])) { Session::addMessageAfterRedirect(__('The title is required', 'formcreator'), false, ERROR); return array(); } // - field type is required if (empty($input['fieldtype'])) { Session::addMessageAfterRedirect(__('The field type is required', 'formcreator'), false, ERROR); return array(); } // - section is required if (empty($input['plugin_formcreator_sections_id'])) { Session::addMessageAfterRedirect(__('The section is required', 'formcreator'), false, ERROR); return array(); } // Values are required for GLPI dropdowns, dropdowns, multiple dropdowns, checkboxes, radios, LDAP $itemtypes = array('select', 'multiselect', 'checkboxes', 'radios', 'ldap'); if (empty($input['values']) && in_array($input['fieldtype'], $itemtypes)) { Session::addMessageAfterRedirect(__('The field value is required:', 'formcreator') . ' ' . $input['name'], false, ERROR); return array(); } // Fields are differents for dropdown lists, so we need to replace these values into the good ones if ($input['fieldtype'] == 'dropdown') { if (empty($input['dropdown_values'])) { Session::addMessageAfterRedirect(__('The field value is required:', 'formcreator') . ' ' . $input['name'], false, ERROR); return array(); } $input['values'] = $input['dropdown_values']; $input['default_values'] = isset($input['dropdown_default_value']) ? $input['dropdown_default_value'] : ''; } // Fields are differents for GLPI object lists, so we need to replace these values into the good ones if ($input['fieldtype'] == 'glpiselect') { if (empty($input['glpi_objects'])) { Session::addMessageAfterRedirect(__('The field value is required:', 'formcreator') . ' ' . $input['name'], false, ERROR); return array(); } $input['values'] = $input['glpi_objects']; $input['default_values'] = isset($input['dropdown_default_value']) ? $input['dropdown_default_value'] : ''; } // A description field should have a description if ($input['fieldtype'] == 'description' && empty($input['description'])) { Session::addMessageAfterRedirect(__('A description field should have a description:', 'formcreator') . ' ' . $input['name'], false, ERROR); return array(); } // format values for numbers if ($input['fieldtype'] == 'integer' || $input['fieldtype'] == 'float') { $input['default_values'] = !empty($input['default_values']) ? (double) str_replace(',', '.', $input['default_values']) : null; $input['range_min'] = !empty($input['range_min']) ? (double) str_replace(',', '.', $input['range_min']) : null; $input['range_max'] = !empty($input['range_max']) ? (double) str_replace(',', '.', $input['range_max']) : null; } // LDAP fields validation if ($input['fieldtype'] == 'ldapselect') { // Fields are differents for dropdown lists, so we need to replace these values into the good ones if (!empty($input['ldap_auth'])) { $config_ldap = new AuthLDAP(); $config_ldap->getFromDB($input['ldap_auth']); $ldap_dropdown = new RuleRightParameter(); $ldap_dropdown->getFromDB($input['ldap_attribute']); $attribute = array($ldap_dropdown->fields['value']); // Set specific error handler too catch LDAP errors if (!function_exists('warning_handler')) { function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) { if (0 === error_reporting()) { return false; } throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } } set_error_handler("warning_handler", E_WARNING); try { $ds = $config_ldap->connect(); ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_control_paged_result($ds, 1); $sn = ldap_search($ds, $config_ldap->fields['basedn'], $input['ldap_filter'], $attribute); $entries = ldap_get_entries($ds, $sn); } catch (Exception $e) { Session::addMessageAfterRedirect(__('Cannot recover LDAP informations!', 'formcreator'), false, ERROR); } restore_error_handler(); $input['values'] = json_encode(array('ldap_auth' => $input['ldap_auth'], 'ldap_filter' => $input['ldap_filter'], 'ldap_attribute' => strtolower($input['ldap_attribute']))); } } // Add leading and trailing regex marker automaticaly if (!empty($input['regex'])) { if (substr($input['regex'], 0, 1) != '/') { if (substr($input['regex'], 0, 1) != '^') { $input['regex'] = '/^' . $input['regex']; } else { $input['regex'] = '/' . $input['regex']; } } if (substr($input['regex'], -1, 1) != '/') { if (substr($input['regex'], -1, 1) != '$') { $input['regex'] = $input['regex'] . '$/'; } else { $input['regex'] = $input['regex'] . '/'; } } } return $input; }
static function showUserImportForm(AuthLDAP $authldap) { global $DB, $LANG; //Get data related to entity (directory and ldap filter) $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); echo "<div class='center'>"; echo "<form method='post' action='" . $_SERVER['PHP_SELF'] . "'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='4' class='middle'><div class='relative'>"; echo "<span>" . ($_SESSION['ldap_import']['mode'] ? $LANG['ldap'][1] : $LANG['ldap'][2]); // Expert interface allow user to override configuration. // If not coming from the ticket form, then give expert/simple link if ((haveRight('config', 'w') || haveRight('entity', 'w')) && !isset($_SESSION['ldap_import']['no_expert_mode'])) { echo "</span> <span class='ldap_right'>" . $LANG['common'][65] . " : "; echo "<a href='" . $_SERVER['PHP_SELF'] . "?action=" . $_SESSION['ldap_import']['action'] . "&mode=" . $_SESSION['ldap_import']['mode'] . "&interface=" . ($_SESSION['ldap_import']['interface'] == self::SIMPLE_INTERFACE ? self::EXPERT_INTERFACE : self::SIMPLE_INTERFACE) . "'>" . ($_SESSION['ldap_import']['interface'] == self::SIMPLE_INTERFACE ? $LANG['ldap'][39] : $LANG['ldap'][40]) . "</a>"; } else { $_SESSION['ldap_import']['interface'] = self::SIMPLE_INTERFACE; } echo "</span></div>"; echo "</th></tr>"; switch ($_SESSION['ldap_import']['interface']) { case self::EXPERT_INTERFACE: //If more than one directory configured //Display dropdown ldap servers if ($_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && $_SESSION['ldap_import']['authldaps_id'] > 0) { if (self::getNumberOfServers() > 1) { echo "<tr class='tab_bg_2'><td>" . $LANG['ldap'][4] . "</td><td colspan='3'>"; Dropdown::show('AuthLdap', array('name' => 'authldaps_id', 'value' => $_SESSION['ldap_import']['authldaps_id'], 'condition' => "`is_active` = '1'", 'display_emptychoice' => false)); echo " <input class='submit' type='submit' name='change_directory'\n value=\"" . $LANG['ldap'][41] . "\">"; echo "</td></tr>"; } echo "<tr class='tab_bg_2'><td>Basedn</td><td colspan='3'>"; echo "<input type='text' name='basedn' value=\"" . $_SESSION['ldap_import']['basedn'] . "\" size='90' " . (!$_SESSION['ldap_import']['basedn'] ? "disabled" : "") . ">"; echo "</td></tr>"; echo "<tr class='tab_bg_2'><td>" . $LANG['setup'][263] . "</td><td colspan='3'>"; echo "<input type='text' name='ldap_filter' value=\"" . $_SESSION['ldap_import']['ldap_filter'] . "\" size='90'>"; echo "</td></tr>"; } break; //case self::SIMPLE_INTERFACE : //case self::SIMPLE_INTERFACE : default: //If multi-entity mode and more than one entity visible //else no need to select entity if (isMultiEntitiesMode() && count($_SESSION['glpiactiveentities']) > 1) { echo "<tr class='tab_bg_2'><td>" . $LANG['entity'][10] . "</td><td colspan='3'>"; Dropdown::show('Entity', array('value' => $_SESSION['ldap_import']['entities_id'], 'entity' => $_SESSION['glpiactiveentities'], 'auto_submit' => 1)); echo "</td></tr>"; } else { //Only one entity is active, store it echo "<tr><td><input type='hidden' name='entities_id' value='" . $_SESSION['glpiactive_entity'] . "'></td></tr>"; } if (isset($_SESSION['ldap_import']['days']) && $_SESSION['ldap_import']['days']) { $enabled = 1; } else { $enabled = 0; } Dropdown::showAdvanceDateRestrictionSwitch($enabled); echo "<table class='tab_cadre_fixe'>"; if ($_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && $_SESSION['ldap_import']['authldaps_id'] > 0) { $field_counter = 0; $fields = array('login_field' => $LANG['login'][6], 'email_field' => $LANG['setup'][14], 'realname_field' => $LANG['common'][48], 'firstname_field' => $LANG['common'][43], 'phone_field' => $LANG['help'][35], 'phone2_field' => $LANG['help'][35] . " 2", 'mobile_field' => $LANG['common'][42], 'title_field' => $LANG['users'][1], 'category_field' => $LANG['users'][2]); $available_fields = array(); foreach ($fields as $field => $label) { if (isset($authldap->fields[$field]) && $authldap->fields[$field] != '') { $available_fields[$field] = $label; } } echo "<tr><th colspan='4'>" . $LANG['ldap'][38] . "</th></tr>"; foreach ($available_fields as $field => $label) { if ($field_counter == 0) { echo "<tr class='tab_bg_1'>"; } echo "<td>{$label}</td><td>"; $field_counter++; echo "<input type='text' name='criterias[{$field}]' value='" . (isset($_SESSION['ldap_import']['criterias'][$field]) ? $_SESSION['ldap_import']['criterias'][$field] : '') . "'>"; echo "</td>"; if ($field_counter == 2) { echo "</tr>"; $field_counter = 0; } } if ($field_counter > 0) { while ($field_counter < 2) { echo "<td colspan='2'></td>"; $field_counter++; } $field_counter = 0; echo "</tr>"; } } break; } if ($_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && $_SESSION['ldap_import']['authldaps_id'] > 0) { if ($_SESSION['ldap_import']['authldaps_id']) { echo "<tr class='tab_bg_2'><td colspan='4' class='center'>"; echo "<input class='submit' type='submit' name='search' value=\"" . $LANG['buttons'][0] . "\">"; echo "</td></tr>"; } else { echo "<tr class='tab_bg_2'><td colspan='4' class='center'>" . $LANG['ldap'][42] . "</td></tr>"; } } else { echo "<tr class='tab_bg_2'><td colspan='4' class='center'>" . $LANG['ldap'][36] . "</td></tr>"; } echo "</table></form></div>"; }
if (!defined('GLPI_ROOT')) { include '../inc/includes.php'; } Session::checkRight("import_externalauth_users", 'w'); // Need REQUEST to manage initial walues and posted ones AuthLdap::manageValuesInSession($_REQUEST); if (isset($_SESSION['ldap_import']['popup']) && $_SESSION['ldap_import']['popup']) { Html::popHeader(__('LDAP directory link'), $_SERVER['PHP_SELF']); } else { Html::header(__('LDAP directory link'), $_SERVER['PHP_SELF'], "admin", "user", "ldap"); } if (isset($_GET['start'])) { $_SESSION['ldap_import']['start'] = $_GET['start']; } if (isset($_GET['order'])) { $_SESSION['ldap_import']['order'] = $_GET['order']; } if ($_SESSION['ldap_import']['action'] == 'show') { $authldap = new AuthLDAP(); $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); AuthLdap::showUserImportForm($authldap); if (isset($_SESSION['ldap_import']['authldaps_id']) && $_SESSION['ldap_import']['authldaps_id'] != NOT_AVAILABLE && isset($_SESSION['ldap_import']['criterias']) && !empty($_SESSION['ldap_import']['criterias'])) { echo "<br />"; AuthLdap::searchUser($authldap); } } if (isset($_SESSION['ldap_import']['popup']) && $_SESSION['ldap_import']['popup']) { Html::ajaxFooter(); } else { Html::footer(); }
/** * Update from 0.80.3 to 0.83 * * @return bool for success (will die for most error) **/ function update0803to083() { global $DB, $migration; $updateresult = true; $ADDTODISPLAYPREF = array(); //TRANS: %s is the number of new version $migration->displayTitle(sprintf(__('Update to %s'), '0.83')); $migration->setVersion('0.83'); $backup_tables = false; $newtables = array('glpi_entities_knowbaseitems', 'glpi_entities_reminders', 'glpi_groups_problems', 'glpi_groups_knowbaseitems', 'glpi_groups_reminders', 'glpi_knowbaseitems_profiles', 'glpi_knowbaseitems_users', 'glpi_items_problems', 'glpi_problems', 'glpi_problemtasks', 'glpi_problems_ticket', 'glpi_problems_users', 'glpi_profiles_reminders', 'glpi_reminders_users', 'glpi_ticketrecurrents', 'glpi_tickettemplates', 'glpi_tickettemplatehiddenfields', 'glpi_tickettemplatemandatoryfields', 'glpi_tickettemplatepredefinedfields', 'glpi_useremails'); foreach ($newtables as $new_table) { // rename new tables if exists ? if (TableExists($new_table)) { $migration->dropTable("backup_{$new_table}"); $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}."); $backup_tables = true; $query = $migration->renameTable("{$new_table}", "backup_{$new_table}"); } } if ($backup_tables) { $migration->displayWarning("You can delete backup tables if you have no need of them.", true); } //TRANS: %s is the table or item implied $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Problems')); // Clean ticket validations : already done in 0.80 $query = "DELETE\n FROM `glpi_ticketvalidations`\n WHERE `glpi_ticketvalidations`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n FROM `glpi_tickets`)"; $DB->queryOrDie($query, "0.83 clean glpi_ticketvalidations"); // Problems management if (!TableExists('glpi_problems')) { $query = "CREATE TABLE `glpi_problems` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) DEFAULT NULL,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n `status` varchar(255) DEFAULT NULL,\n `content` longtext DEFAULT NULL,\n `date_mod` DATETIME DEFAULT NULL,\n `date` DATETIME DEFAULT NULL,\n `solvedate` DATETIME DEFAULT NULL,\n `closedate` DATETIME DEFAULT NULL,\n `due_date` DATETIME DEFAULT NULL,\n `users_id_recipient` int(11) NOT NULL DEFAULT '0',\n `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n `suppliers_id_assign` int(11) NOT NULL DEFAULT '0',\n `urgency` int(11) NOT NULL DEFAULT '1',\n `impact` int(11) NOT NULL DEFAULT '1',\n `priority` int(11) NOT NULL DEFAULT '1',\n `itilcategories_id` int(11) NOT NULL DEFAULT '0',\n `impactcontent` longtext DEFAULT NULL,\n `causecontent` longtext DEFAULT NULL,\n `symptomcontent` longtext DEFAULT NULL,\n `solutiontypes_id` int(11) NOT NULL DEFAULT '0',\n `solution` text COLLATE utf8_unicode_ci,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `begin_waiting_date` datetime DEFAULT NULL,\n `waiting_duration` int(11) NOT NULL DEFAULT '0',\n `close_delay_stat` int(11) NOT NULL DEFAULT '0',\n `solve_delay_stat` int(11) NOT NULL DEFAULT '0',\n `notepad` LONGTEXT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `is_deleted` (`is_deleted`),\n KEY `date` (`date`),\n KEY `closedate` (`closedate`),\n KEY `status` (`status`(1)),\n KEY `priority` (`priority`),\n KEY `date_mod` (`date_mod`),\n KEY `suppliers_id_assign` (`suppliers_id_assign`),\n KEY `itilcategories_id` (`itilcategories_id`),\n KEY `users_id_recipient` (`users_id_recipient`),\n KEY `solvedate` (`solvedate`),\n KEY `solutiontypes_id` (`solutiontypes_id`),\n KEY `urgency` (`urgency`),\n KEY `impact` (`impact`),\n KEY `due_date` (`due_date`),\n KEY `users_id_lastupdater` (`users_id_lastupdater`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 create glpi_problems"); $ADDTODISPLAYPREF['Problem'] = array(21, 12, 19, 15, 3, 7, 18); } if (FieldExists('glpi_tickets', 'ticket_waiting_duration', false)) { $migration->changeField('glpi_tickets', 'ticket_waiting_duration', 'waiting_duration', 'integer'); } if (!TableExists('glpi_problems_users')) { $query = "CREATE TABLE `glpi_problems_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`problems_id`,`type`,`users_id`,`alternative_email`),\n KEY `user` (`users_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_problems_users"); } if (!TableExists('glpi_groups_problems')) { $query = "CREATE TABLE `glpi_groups_problems` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`problems_id`,`type`,`groups_id`),\n KEY `group` (`groups_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_groups_problems"); } if (!TableExists('glpi_items_problems')) { $query = "CREATE TABLE `glpi_items_problems` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) default NULL,\n `items_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`problems_id`,`itemtype`,`items_id`),\n KEY `item` (`itemtype`,`items_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_items_problems"); } if (!TableExists('glpi_problems_tickets')) { $query = "CREATE TABLE `glpi_problems_tickets` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`problems_id`,`tickets_id`),\n KEY `tickets_id` (`tickets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_problems_tickets"); } if (!TableExists('glpi_problemtasks')) { $query = "CREATE TABLE `glpi_problemtasks` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n `date` datetime DEFAULT NULL,\n `begin` datetime DEFAULT NULL,\n `end` datetime DEFAULT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `users_id_tech` int(11) NOT NULL DEFAULT '0',\n `content` longtext COLLATE utf8_unicode_ci,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `state` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `problems_id` (`problems_id`),\n KEY `users_id` (`users_id`),\n KEY `users_id_tech` (`users_id_tech`),\n KEY `date` (`date`),\n KEY `begin` (`begin`),\n KEY `end` (`end`),\n KEY `state` (`state`),\n KEY `taskcategories_id` (taskcategories_id)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_problemtasks"); } $migration->addField("glpi_profiles", "show_my_problem", "char", array('update' => "1", 'condition' => " WHERE `own_ticket` = 1")); $migration->addField("glpi_profiles", "show_all_problem", "char", array('update' => "1", 'condition' => " WHERE `show_all_ticket` = 1")); $migration->addField("glpi_profiles", "edit_all_problem", "char", array('update' => "1", 'condition' => " WHERE `update_ticket` = 1")); $migration->changeField("glpi_profiles", 'helpdesk_status', 'ticket_status', "text", array('comment' => "json encoded array of from/dest allowed status change")); $migration->addField('glpi_profiles', 'problem_status', "text", array('comment' => "json encoded array of from/dest allowed status change")); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Changes')); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'TicketPlanning')); // Merge tickettasks and ticket planning if (TableExists('glpi_ticketplannings')) { $migration->addField("glpi_tickettasks", "begin", "datetime"); $migration->addField("glpi_tickettasks", "end", "datetime"); $migration->addField("glpi_tickettasks", "state", "integer", array('value' => '1')); $migration->addField("glpi_tickettasks", "users_id_tech", "integer"); $migration->migrationOneTable('glpi_tickettasks'); // migrate DATA $task = new TicketTask(); foreach ($DB->request('glpi_ticketplannings') as $data) { if ($task->getFromDB($data['tickettasks_id'])) { $query = "UPDATE `glpi_tickettasks`\n SET `begin` = " . ($data['begin'] == 'NULL' || is_null($data['begin']) ? 'NULL' : "'" . $data['begin'] . "'") . ",\n `end` = " . ($data['end'] == 'NULL' || is_null($data['end']) ? 'NULL' : "'" . $data['end'] . "'") . ",\n `users_id_tech` = '" . $data['users_id'] . "',\n `state` = '" . $data['state'] . "'\n WHERE `id` = '" . $data['tickettasks_id'] . "'"; $DB->queryOrDie($query, "0.83 migrate planning to glpi_tickettasks"); } } $migration->dropTable("glpi_ticketplannings"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Notification')); // Migrate templates $from = array('task.planning.user##', 'task.planning.begin##', 'task.planning.end##', 'task.planning.status##'); $to = array('task.user##', 'task.begin##', 'task.end##', 'task.status##'); $query = "SELECT `glpi_notificationtemplatetranslations`.*\n FROM `glpi_notificationtemplatetranslations`\n INNER JOIN `glpi_notificationtemplates`\n ON (`glpi_notificationtemplates`.`id`\n = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n WHERE `glpi_notificationtemplates`.`itemtype` = 'Ticket'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query = "UPDATE `glpi_notificationtemplatetranslations`\n SET `subject` = '" . addslashes(str_replace($from, $to, $data['subject'])) . "',\n `content_text` = '" . addslashes(str_replace($from, $to, $data['content_text'])) . "',\n `content_html` = '" . addslashes(str_replace($from, $to, $data['content_html'])) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->queryOrDie($query, "0.83 fix tags usage for multi users"); } } } } $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `name` = 'Problems'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Problems', 'Problem', NOW())"; $DB->queryOrDie($query, "0.83 add problem notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##problem.action## ##problem.title##',\n '##IFproblem.storestatus=solved##\n ##lang.problem.url## : ##problem.urlapprove##\n ##lang.problem.solvedate## : ##problem.solvedate##\n ##lang.problem.solution.type## : ##problem.solution.type##\n ##lang.problem.solution.description## : ##problem.solution.description## ##ENDIFproblem.storestatus##\n ##ELSEproblem.storestatus## ##lang.problem.url## : ##problem.url## ##ENDELSEproblem.storestatus##\n\n ##lang.problem.description##\n\n ##lang.problem.title##  :##problem.title##\n ##lang.problem.authors##  :##IFproblem.authors## ##problem.authors## ##ENDIFproblem.authors## ##ELSEproblem.authors##--##ENDELSEproblem.authors##\n ##lang.problem.creationdate##  :##problem.creationdate##\n ##IFproblem.assigntousers## ##lang.problem.assigntousers##  : ##problem.assigntousers## ##ENDIFproblem.assigntousers##\n ##lang.problem.status##  : ##problem.status##\n ##IFproblem.assigntogroups## ##lang.problem.assigntogroups##  : ##problem.assigntogroups## ##ENDIFproblem.assigntogroups##\n ##lang.problem.urgency##  : ##problem.urgency##\n ##lang.problem.impact##  : ##problem.impact##\n ##lang.problem.priority## : ##problem.priority##\n##IFproblem.category## ##lang.problem.category##  :##problem.category## ##ENDIFproblem.category## ##ELSEproblem.category## ##lang.problem.nocategoryassigned## ##ENDELSEproblem.category##\n ##lang.problem.content##  : ##problem.content##\n\n##IFproblem.storestatus=closed##\n ##lang.problem.solvedate## : ##problem.solvedate##\n ##lang.problem.solution.type## : ##problem.solution.type##\n ##lang.problem.solution.description## : ##problem.solution.description##\n##ENDIFproblem.storestatus##\n ##lang.problem.numberoftickets## : ##problem.numberoftickets##\n\n##FOREACHtickets##\n [##ticket.date##] ##lang.problem.title## : ##ticket.title##\n ##lang.problem.content## ##ticket.content##\n\n##ENDFOREACHtickets##\n ##lang.problem.numberoftasks## : ##problem.numberoftasks##\n\n##FOREACHtasks##\n [##task.date##]\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##\n',\n '<p>##IFproblem.storestatus=solved##</p>\n<div>##lang.problem.url## : <a href=\"##problem.urlapprove##\">##problem.urlapprove##</a></div>\n<div><span style=\"color: #888888;\"><strong><span style=\"text-decoration: underline;\">##lang.problem.solvedate##</span></strong></span> : ##problem.solvedate##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.problem.solution.type##</strong></span> : ##problem.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.problem.solution.description##</strong></span> : ##problem.solution.description## ##ENDIFproblem.storestatus##</div>\n<div>##ELSEproblem.storestatus## ##lang.problem.url## : <a href=\"##problem.url##\">##problem.url##</a> ##ENDELSEproblem.storestatus##</div>\n<p class=\"description b\"><strong>##lang.problem.description##</strong></p>\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.title##</span> :##problem.title## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.authors##</span> :##IFproblem.authors## ##problem.authors## ##ENDIFproblem.authors## ##ELSEproblem.authors##--##ENDELSEproblem.authors## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.creationdate##</span> :##problem.creationdate## <br /> ##IFproblem.assigntousers## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.assigntousers##</span> : ##problem.assigntousers## ##ENDIFproblem.assigntousers##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.problem.status## </span> : ##problem.status##<br /> ##IFproblem.assigntogroups## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.assigntogroups##</span> : ##problem.assigntogroups## ##ENDIFproblem.assigntogroups##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.urgency##</span> : ##problem.urgency##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.impact##</span> : ##problem.impact##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.priority##</span> : ##problem.priority## <br />##IFproblem.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.problem.category## </span> :##problem.category## ##ENDIFproblem.category## ##ELSEproblem.category## ##lang.problem.nocategoryassigned## ##ENDELSEproblem.category## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.problem.content##</span> : ##problem.content##</p>\n<p>##IFproblem.storestatus=closed##<br /><span style=\"text-decoration: underline;\"><strong><span style=\"color: #888888;\">##lang.problem.solvedate##</span></strong></span> : ##problem.solvedate##<br /><span style=\"color: #888888;\"><strong><span style=\"text-decoration: underline;\">##lang.problem.solution.type##</span></strong></span> : ##problem.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.problem.solution.description##</strong></span> : ##problem.solution.description##<br />##ENDIFproblem.storestatus##</p>\n<div class=\"description b\">##lang.problem.numberoftickets## : ##problem.numberoftickets##</div>\n<p>##FOREACHtickets##</p>\n<div><strong> [##ticket.date##] <em>##lang.problem.title## : <a href=\"##ticket.url##\">##ticket.title## </a></em></strong><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> </span><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.problem.content## </span> ##ticket.content##\n<p>##ENDFOREACHtickets##</p>\n<div class=\"description b\">##lang.problem.numberoftasks## : ##problem.numberoftasks##</div>\n<p>##FOREACHtasks##</p>\n<div class=\"description b\"><strong>[##task.date##] </strong><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.author##</span> ##task.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.description##</span> ##task.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.time##</span> ##task.time##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.category##</span> ##task.category##</div>\n<p>##ENDFOREACHtasks##</p>\n</div>')"; $DB->queryOrDie($query, "0.83 add problem notification translation"); $notifications = array('new' => array(), 'update' => array(Notification::ASSIGN_TECH, Notification::OLD_TECH_IN_CHARGE), 'solved' => array(), 'add_task' => array(), 'update_task' => array(), 'delete_task' => array(), 'closed' => array(), 'delete' => array()); $notif_names = array('new' => 'New Problem', 'update' => 'Update Problem', 'solved' => 'Resolve Problem', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Problem', 'delete' => 'Delete Problem'); foreach ($notifications as $key => $val) { $notifications[$key][] = Notification::AUTHOR; $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR; $notifications[$key][] = Notification::OBSERVER; } foreach ($notifications as $type => $targets) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('" . $notif_names[$type] . "', 0, 'Problem', '{$type}', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.83 add problem {$type} notification"); $notifid = $DB->insert_id(); foreach ($targets as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});"; $DB->queryOrDie($query, "0.83 add problem {$type} notification target"); } } } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'Clean Vlans')); // Clean `glpi_networkports_vlans` datas (`networkports_id` whithout networkports) $query = "DELETE\n FROM `glpi_networkports_vlans`\n WHERE `networkports_id` NOT IN (SELECT `id`\n FROM `glpi_networkports`)"; $DB->queryOrDie($query, "0.83 clean networkports_vlans datas"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Rename Solution objects')); // rename glpi_ticketsolutiontypes to glpi_solutiontypes $migration->renameTable('glpi_ticketsolutiontypes', 'glpi_solutiontypes'); // rename glpi_ticketsolutiontemplates to glpi_solutiontemplates $migration->renameTable('glpi_ticketsolutiontemplates', 'glpi_solutiontemplates'); $migration->changeField('glpi_tickets', 'ticketsolutiontypes_id', 'solutiontypes_id', 'integer'); $migration->changeField('glpi_solutiontemplates', 'ticketsolutiontypes_id', 'solutiontypes_id', 'integer'); $migration->changeField('glpi_tickets_users', 'use_notification', 'use_notification', 'bool', array('value' => '1')); // to have correct name of key $migration->dropKey('glpi_tickets', 'ticketsolutiontypes_id'); $migration->migrationOneTable('glpi_tickets'); $migration->addKey('glpi_tickets', 'solutiontypes_id'); $migration->dropKey('glpi_solutiontemplates', 'ticketsolutiontypes_id'); $migration->migrationOneTable('glpi_solutiontemplates'); $migration->addKey('glpi_solutiontemplates', 'solutiontypes_id'); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Rename Category objects')); $migration->renameTable('glpi_ticketcategories', 'glpi_itilcategories'); $migration->dropKey('glpi_itilcategories', 'ticketcategories_id'); $migration->changeField('glpi_itilcategories', 'ticketcategories_id', 'itilcategories_id', 'integer'); $migration->migrationOneTable('glpi_itilcategories'); $migration->addKey('glpi_itilcategories', 'itilcategories_id'); $migration->dropKey('glpi_tickets', 'ticketcategories_id'); $migration->changeField('glpi_tickets', 'ticketcategories_id', 'itilcategories_id', 'integer'); $migration->migrationOneTable('glpi_tickets'); $migration->addKey('glpi_tickets', 'itilcategories_id'); // Update Itemtype datas in tables $itemtype_tables = array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences"); $typestochange = array('TicketSolutionTemplate' => 'SolutionTemplate', 'TicketSolutionType' => 'SolutionType', 'TicketCategory' => 'ITILCategory'); foreach ($itemtype_tables as $table) { foreach ($typestochange as $key => $val) { $query = "UPDATE `{$table}`\n SET `itemtype` = '{$val}'\n WHERE `itemtype` = '{$key}'"; $DB->queryOrDie($query, "0.83 update itemtype of table {$table} for {$val}"); } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Add various fields')); $migration->addField("glpi_states", 'states_id', "integer"); $migration->addField("glpi_states", 'completename', "text"); $migration->addField("glpi_states", 'level', "integer"); $migration->addField("glpi_states", 'ancestors_cache', "longtext"); $migration->addField("glpi_states", 'sons_cache', "longtext"); $migration->migrationOneTable('glpi_states'); $migration->addKey("glpi_states", array('states_id', 'name'), 'unicity'); regenerateTreeCompleteName("glpi_states"); $migration->addField("glpi_knowbaseitemcategories", 'ancestors_cache', "longtext"); $migration->addField("glpi_knowbaseitemcategories", 'sons_cache', "longtext"); $migration->changeField("glpi_authldaps", 'group_condition', 'group_condition', "text"); $migration->dropKey("glpi_groups", 'ldap_value'); $migration->changeField("glpi_groups", 'ldap_value', 'ldap_value', "text"); $migration->dropKey("glpi_groups", 'ldap_group_dn'); $migration->changeField("glpi_groups", 'ldap_group_dn', 'ldap_group_dn', "text"); $migration->addField("glpi_groups", 'groups_id', "integer"); $migration->addField("glpi_groups", 'completename', "text"); $migration->addField("glpi_groups", 'level', "integer"); $migration->addField("glpi_groups", 'ancestors_cache', "longtext"); $migration->addField("glpi_groups", 'sons_cache', "longtext"); $migration->migrationOneTable('glpi_groups'); $migration->addKey("glpi_groups", 'ldap_value', '', 'INDEX', 200); $migration->addKey("glpi_groups", 'ldap_group_dn', '', 'INDEX', 200); $migration->addKey("glpi_groups", 'groups_id'); regenerateTreeCompleteName("glpi_groups"); $migration->addField("glpi_entitydatas", 'notification_subject_tag', "string", array('after' => 'admin_reply_name')); $migration->addField("glpi_vlans", 'tag', "integer"); $ADDTODISPLAYPREF['Vlan'] = array(11); $migration->addField("glpi_profiles", 'create_ticket_on_login', "bool"); $migration->addField("glpi_reminders", 'begin_view_date', "datetime"); $migration->addField("glpi_reminders", 'end_view_date', "datetime"); // only to change latin1 to utf-8 if not done in update 0.68.3 to 0.71 // because there is an index fulltext based on 2 fields (perhaps both are not in same encoding) $migration->changeField("glpi_knowbaseitems", 'answer', 'answer', "longtext"); $migration->changeField("glpi_knowbaseitems", 'question', 'name', "text"); $migration->addField("glpi_configs", "ajax_min_textsearch_load", "integer", array('after' => 'use_ajax')); $migration->addField("glpi_configs", "use_anonymous_followups", "bool", array('after' => 'use_anonymous_helpdesk')); $migration->addField("glpi_configs", "show_count_on_tabs", "bool", array('value' => '1')); $migration->addField("glpi_users", "show_count_on_tabs", "tinyint(1) NULL DEFAULT NULL"); $migration->addField("glpi_configs", "refresh_ticket_list", "integer"); $migration->addField("glpi_users", "refresh_ticket_list", "int(11) NULL DEFAULT NULL"); $migration->addField("glpi_configs", "set_default_tech", "bool", array('value' => '1')); $migration->addField("glpi_users", "set_default_tech", "tinyint(1) NULL DEFAULT NULL"); $migration->addField("glpi_reservations", "group", "integer"); $migration->addKey("glpi_reservations", array('reservationitems_id', 'group'), "resagroup"); /// Add document types $types = array('csv' => array('name' => 'Comma-Separated Values', 'icon' => 'csv-dist.png'), 'svg' => array('name' => 'Scalable Vector Graphics', 'icon' => 'svg-dist.png')); foreach ($types as $ext => $data) { $query = "SELECT *\n FROM `glpi_documenttypes`\n WHERE `ext` = '{$ext}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_documenttypes`\n (`name`, `ext`, `icon`, `is_uploadable`, `date_mod`)\n VALUES ('" . $data['name'] . "', '{$ext}', '" . $data['icon'] . "', '1', NOW())"; $DB->queryOrDie($query, "0.83 add document type {$ext}"); } } } /// Update icons $types = array('c' => 'c-dist.png', 'h' => 'h-dist.png', 'swf' => 'swf-dist.png', 'pas' => 'pas-dist.png', 'wmv' => 'wmv-dist.png', 'zip' => 'zip-dist.png'); foreach ($types as $ext => $icon) { $query = "SELECT `id`\n FROM `glpi_documenttypes`\n WHERE `ext` = '{$ext}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 1) { $query = "UPDATE `glpi_documenttypes`\n SET `icon` = '{$icon}', `date_mod` = NOW()\n WHERE `id` = '" . $DB->result($result, 0, 0) . "'"; $DB->queryOrDie($query, "0.83 update icon for doc type {$ext}"); } } } /// add missing indexes for fields $migration->addKey("glpi_authldaps", "is_active"); $migration->addKey("glpi_authmails", "is_active"); $migration->addKey("glpi_ocsservers", "is_active"); $migration->changeField("glpi_users", 'token', 'password_forget_token', "char(40) NULL DEFAULT NULL"); $migration->changeField("glpi_users", 'tokendate', 'password_forget_token_date', "datetime"); $migration->addField("glpi_users", "personal_token", 'string'); $migration->addField("glpi_users", "personal_token_date", "datetime"); $migration->addField("glpi_tickets", "is_deleted", "bool"); $migration->addKey("glpi_tickets", "is_deleted"); $migration->addField("glpi_contracts", "template_name", 'string'); $migration->addField("glpi_contracts", "is_template", 'bool'); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Give consumable to groups')); if ($migration->addField("glpi_consumables", "itemtype", "VARCHAR(100) DEFAULT NULL", array("after" => "date_out", "update" => "'User'"))) { $migration->dropKey("glpi_consumables", 'users_id'); $migration->changeField("glpi_consumables", 'users_id', 'items_id', 'integer'); $migration->addKey("glpi_consumables", array('itemtype', 'items_id'), 'item'); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Several emails for users')); // Several email per users if (!TableExists('glpi_useremails')) { $query = "CREATE TABLE `glpi_useremails` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `is_default` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `is_dynamic` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `email` varchar( 255 ) NULL DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`users_id`,`email`),\n KEY `email` (`email`),\n KEY `is_default` (`is_default`),\n KEY `is_dynamic` (`is_dynamic`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_useremails"); } // Manage migration : populate is_default=1 // and is_dynamic depending of authldap config / authtype / auths_id if (FieldExists("glpi_users", 'email', false)) { $query = "SELECT *\n FROM `glpi_users`\n WHERE `email` <> '' AND `email` IS NOT NULL"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $is_dynamic = 0; $ldap_servers = array(); // manage is_dynamic : if ($data['authtype'] == Auth::MAIL) { $is_dynamic = 1; } else { if (Auth::isAlternateAuth($data["authtype"]) && $data['auths_id'] > 0 || $data['authtype'] == Auth::LDAP) { if (!isset($ldap_servers[$data['auths_id']])) { $ldap_servers[$data['auths_id']] = 0; $ldap = new AuthLDAP(); if ($ldap->getFromDB($data['auths_id'])) { if (!empty($ldap->fields['email_field'])) { $ldap_servers[$data['auths_id']] = 1; } } } $is_dynamic = $ldap_servers[$data['auths_id']]; } } $query2 = "INSERT INTO `glpi_useremails`\n (`users_id`, `is_default`, `is_dynamic`, `email`)\n VALUES ('" . $data['id'] . "','1','{$is_dynamic}','" . addslashes($data['email']) . "')"; $DB->queryOrDie($query2, "0.83 move emails to glpi_useremails"); } } } // Drop email field from glpi_users $migration->dropField("glpi_users", 'email'); } // check unicity for users email : unset rule and display warning foreach ($DB->request("glpi_fieldunicities", "`itemtype` = 'User' AND `fields` LIKE '%email%'") as $data) { $query = "UPDATE `glpi_fieldunicities`\n SET `is_active` = '0'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); echo "<div class='red'><p>A unicity check use email for users. "; echo "Due to new feature permit several email per users, this rule have been disabled.</p></div>"; } // multiple manager in groups $migration->changeField("glpi_authldaps", 'email_field', 'email1_field', 'string'); $migration->addField("glpi_authldaps", 'email2_field', 'string'); $migration->addField("glpi_authldaps", 'email3_field', 'string'); $migration->addField("glpi_authldaps", 'email4_field', 'string'); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Multiple managers for groups')); /// migration : multiple group managers $migration->addField("glpi_groups_users", "is_manager", 'bool'); $migration->addKey("glpi_groups_users", "is_manager"); $migration->migrationOneTable('glpi_groups_users'); if (FieldExists("glpi_groups", 'users_id', false)) { $query = "SELECT *\n FROM `glpi_groups`\n WHERE `users_id` > 0"; $user = new User(); if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { if ($user->getFromDB($data['users_id'])) { $query = "SELECT `id`\n FROM `glpi_groups_users`\n WHERE `groups_id` = '" . $data['id'] . "'\n AND `users_id` = '" . $data['users_id'] . "'"; if ($result2 = $DB->query($query)) { // add manager to groups_users setting if not present if ($DB->numrows($result2) == 0) { $query2 = "INSERT INTO`glpi_groups_users`\n (`users_id`, `groups_id`, `is_manager`)\n VALUES ('" . $data['users_id'] . "' ,'" . $data['id'] . "', '1')"; $DB->queryOrDie($query2, "0.83 insert manager of groups"); } else { // Update user as manager if presnet in groups_users $query2 = "UPDATE `glpi_groups_users`\n SET `is_manager` = '1'\n WHERE `groups_id` = '" . $data['id'] . "'\n AND `users_id` = '" . $data['users_id'] . "'"; $DB->queryOrDie($query2, "0.83 set manager of groups"); } } } } } } // Drop field glpi_groups $migration->dropField("glpi_groups", 'users_id'); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Add entities information on document links')); if ($migration->addField("glpi_documents_items", "entities_id", "integer")) { $migration->addField("glpi_documents_items", "is_recursive", "bool"); $migration->migrationOneTable('glpi_documents_items'); $query_doc_i = "UPDATE `glpi_documents_items` as `doc_i`\n INNER JOIN `glpi_documents` as `doc`\n ON `doc`.`id` = `doc_i`.`documents_id`\n SET `doc_i`.`entities_id` = `doc`.`entities_id`,\n `doc_i`.`is_recursive` = `doc`.`is_recursive`"; $DB->queryOrDie($query_doc_i, "0.83 update entities_id and is_recursive in glpi_documents_items"); /// create index for search count on tab $migration->dropKey("glpi_documents_items", "item"); $migration->migrationOneTable('glpi_documents_items'); $migration->addKey("glpi_documents_items", array('itemtype', 'items_id', 'entities_id', 'is_recursive'), 'item'); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket')); $changes['RuleTicket'] = array('ticketcategories_id' => 'itilcategories_id'); $DB->query("SET SESSION group_concat_max_len = 4194304;"); foreach ($changes as $ruletype => $tab) { // Get rules $query = "SELECT GROUP_CONCAT(`id`)\n FROM `glpi_rules`\n WHERE `sub_type` = '" . $ruletype . "'\n GROUP BY `sub_type`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Get rule string $rules = $DB->result($result, 0, 0); // Update actions foreach ($tab as $old => $new) { $query = "UPDATE `glpi_ruleactions`\n SET `field` = '{$new}'\n WHERE `field` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.83 update datas for rules actions"); } // Update criteria 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.83 update datas for rules criteria"); } } } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'Ticket templates')); $default_ticket_template = 0; if (!TableExists('glpi_tickettemplates')) { $query = "CREATE TABLE `glpi_tickettemplates` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar( 255 ) NULL DEFAULT NULL,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `comment` TEXT DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_tickettemplates"); $query = "INSERT INTO `glpi_tickettemplates`\n (`name`, `is_recursive`)\n VALUES ('Default', 1)"; $DB->queryOrDie($query, "0.83 add default ticket template"); $default_ticket_template = $DB->insert_id(); } $migration->addField('glpi_itilcategories', 'tickettemplates_id_incident', "integer"); $migration->addKey('glpi_itilcategories', 'tickettemplates_id_incident'); $migration->addField('glpi_itilcategories', 'tickettemplates_id_demand', "integer"); $migration->addKey('glpi_itilcategories', 'tickettemplates_id_demand'); $migration->addField('glpi_itilcategories', 'is_incident', "integer", array('value' => 1)); $migration->addKey('glpi_itilcategories', 'is_incident'); $migration->addField('glpi_itilcategories', 'is_request', "integer", array('value' => 1)); $migration->addKey('glpi_itilcategories', 'is_request'); $migration->addField('glpi_itilcategories', 'is_problem', "integer", array('value' => 1)); $migration->addKey('glpi_itilcategories', 'is_problem'); if (!TableExists('glpi_tickettemplatehiddenfields')) { $query = "CREATE TABLE `glpi_tickettemplatehiddenfields` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `num` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `unicity` (`tickettemplates_id`,`num`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatehiddenfields"); } if (!TableExists('glpi_tickettemplatepredefinedfields')) { $query = "CREATE TABLE `glpi_tickettemplatepredefinedfields` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `num` int(11) NOT NULL DEFAULT '0',\n `value` TEXT DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `unicity` (`tickettemplates_id`,`num`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatepredefinedfields"); } if (!TableExists('glpi_tickettemplatemandatoryfields')) { $query = "CREATE TABLE `glpi_tickettemplatemandatoryfields` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `num` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `unicity` (`tickettemplates_id`,`num`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatemandatoryfields"); /// Add mandatory fields to default template if ($default_ticket_template > 0) { foreach ($DB->request('glpi_configs') as $data) { if (isset($data['is_ticket_title_mandatory']) && $data['is_ticket_title_mandatory']) { $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n (`tickettemplates_id`, `num`)\n VALUES ('{$default_ticket_template}', 1)"; $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template"); } if (isset($data['is_ticket_content_mandatory']) && $data['is_ticket_content_mandatory']) { $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n (`tickettemplates_id`, `num`)\n VALUES ('{$default_ticket_template}', 21)"; $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template"); } if (isset($data['is_ticket_category_mandatory']) && $data['is_ticket_category_mandatory']) { $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n (`tickettemplates_id`, `num`)\n VALUES ('{$default_ticket_template}', 7)"; $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template"); } } // Update itil categories $migration->migrationOneTable('glpi_itilcategories'); $query = "UPDATE `glpi_itilcategories`\n SET `tickettemplates_id_incident` = '{$default_ticket_template}',\n `tickettemplates_id_demand` = '{$default_ticket_template}'"; $DB->queryOrDie($query, "0.83 update default templates used by itil categories"); } } // Drop global mandatory config $migration->dropField('glpi_configs', 'is_ticket_title_mandatory'); $migration->dropField('glpi_configs', 'is_ticket_content_mandatory'); $migration->dropField('glpi_configs', 'is_ticket_category_mandatory'); $migration->addField('glpi_profiles', 'tickettemplate', "char", array('update' => '`sla`')); $migration->addField("glpi_entitydatas", "tickettemplates_id", 'integer', array('value' => '-2')); $migration->displayMessage(sprintf(__('Data migration - %s'), 'Tech Groups on items')); // Group of technicians in charge of Helpdesk items $migration->addField('glpi_computers', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_computers', 'groups_id_tech'); $migration->addField('glpi_monitors', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_monitors', 'groups_id_tech'); $migration->addField('glpi_networkequipments', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_networkequipments', 'groups_id_tech'); $migration->addField('glpi_peripherals', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_peripherals', 'groups_id_tech'); $migration->addField('glpi_phones', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_phones', 'groups_id_tech'); $migration->addField('glpi_printers', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_printers', 'groups_id_tech'); $migration->addField('glpi_softwares', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_softwares', 'groups_id_tech'); $migration->addField('glpi_cartridgeitems', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_cartridgeitems', 'groups_id_tech'); $migration->addField('glpi_consumableitems', 'groups_id_tech', "integer", array('after' => "users_id_tech")); $migration->addKey('glpi_consumableitems', 'groups_id_tech'); $migration->addField('glpi_printers', 'last_pages_counter', 'integer', array('after' => 'init_pages_counter')); $migration->addKey('glpi_printers', 'last_pages_counter'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'various cleaning DB')); // Clean ticket satisfactions $query = "DELETE\n FROM `glpi_ticketsatisfactions`\n WHERE `glpi_ticketsatisfactions`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n FROM `glpi_tickets`)"; $DB->queryOrDie($query, "0.83 clean glpi_ticketsatisfactions"); // Clean unused slalevels $query = "DELETE\n FROM `glpi_slalevels_tickets`\n WHERE (`glpi_slalevels_tickets`.`tickets_id`, `glpi_slalevels_tickets`.`slalevels_id`)\n NOT IN (SELECT `glpi_tickets`.`id`, `glpi_tickets`.`slalevels_id`\n FROM `glpi_tickets`)"; $DB->queryOrDie($query, "0.83 clean glpi_slalevels_tickets"); $migration->displayMessage(sprintf(__('Data migration - %s'), 'recurrent tickets')); if (!TableExists('glpi_ticketrecurrents')) { $query = "CREATE TABLE `glpi_ticketrecurrents` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar( 255 ) NULL DEFAULT NULL,\n `comment` TEXT DEFAULT NULL,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n `begin_date` datetime DEFAULT NULL,\n `periodicity` int(11) NOT NULL DEFAULT '0',\n `create_before` int(11) NOT NULL DEFAULT '0',\n `next_creation_date` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `is_active` (`is_active`),\n KEY `tickettemplates_id` (`tickettemplates_id`),\n KEY `next_creation_date` (`next_creation_date`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_ticketrecurrents"); $ADDTODISPLAYPREF['TicketRecurrent'] = array(11, 12, 13, 15, 14); } if (!countElementsInTable('glpi_crontasks', "`itemtype`='TicketRecurrent' AND `name`='ticketrecurrent'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('TicketRecurrent', 'ticketrecurrent', 3600, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.83 populate glpi_crontasks for ticketrecurrent"); } $migration->addField('glpi_profiles', 'ticketrecurrent', "char", array('update' => '`sla`')); $migration->displayMessage(sprintf(__('Data migration - %s'), 'various fields add')); // Ticket delegation $migration->addField('glpi_groups_users', 'is_userdelegate', 'bool'); $migration->addKey('glpi_groups_users', 'is_userdelegate'); //Software dictionary update $migration->addField("glpi_rulecachesoftwares", "entities_id", "string"); $migration->addField("glpi_rulecachesoftwares", "new_entities_id", "string"); $migration->addField("glpi_entitydatas", "entities_id_software", 'integer', array('value' => '-2')); // Groups perm $migration->addField('glpi_groups', 'is_requester', 'bool', array('value' => '1')); $migration->addField('glpi_groups', 'is_assign', 'bool', array('value' => '1')); $migration->addField('glpi_groups', 'is_notify', 'bool', array('value' => '1')); $migration->addField('glpi_groups', 'is_itemgroup', 'bool', array('value' => '1')); $migration->addField('glpi_groups', 'is_usergroup', 'bool', array('value' => '1')); $migration->addKey('glpi_groups', 'is_requester'); $migration->addKey('glpi_groups', 'is_assign'); $migration->addKey('glpi_groups', 'is_notify'); $migration->addKey('glpi_groups', 'is_itemgroup'); $migration->addKey('glpi_groups', 'is_usergroup'); // Ticket solution by entity $migration->addfield('glpi_solutiontypes', 'entities_id', 'integer'); $migration->addfield('glpi_solutiontypes', 'is_recursive', 'bool', array('value' => '1')); $migration->addKey('glpi_solutiontypes', 'entities_id'); $migration->addKey('glpi_solutiontypes', 'is_recursive'); // Fix solution template index $migration->dropKey('glpi_solutiontemplates', 'unicity'); $migration->addKey('glpi_solutiontemplates', 'entities_id'); // New index for count on tab $migration->addKey('glpi_ruleactions', array('field', 'value'), '', 'INDEX', 50); $migration->displayMessage(sprintf(__('Data migration - %s'), 'Create new default profiles')); $profiles = array('hotliner' => array('name' => 'Hotliner', 'interface' => 'central', 'user' => 'r', 'import_externalauth_users' => 'w', 'create_ticket' => '1', 'assign_ticket' => '1', 'global_add_followups' => '1', 'add_followups' => '1', 'update_ticket' => '1', 'observe_ticket' => '1', 'show_all_ticket' => '1', 'show_full_ticket' => '1', 'show_all_problem' => '1', 'show_planning' => '1', 'statistic' => '1', 'tickettemplate' => 'r', 'password_update' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'create_validation' => '1', 'update_own_followups' => '1', 'create_ticket_on_login' => '1'), 'technician' => array('name' => 'Technician', 'interface' => 'central', 'password_update' => '1', 'computer' => 'w', 'monitor' => 'w', 'software' => 'w', 'networking' => 'w', 'printer' => 'w', 'peripheral' => 'w', 'cartridge' => 'w', 'consumable' => 'w', 'phone' => 'w', 'notes' => 'w', 'document' => 'w', 'knowbase' => 'w', 'faq' => 'w', 'reservation_helpdesk' => '1', 'reservation_central' => 'w', 'reports' => 'r', 'view_ocsng' => 'r', 'sync_ocsng' => 'w', 'user' => 'w', 'group' => 'r', 'entity' => 'r', 'transfer' => 'r', 'reminder_public' => 'w', 'create_ticket' => '1', 'add_followups' => '1', 'global_add_followups' => '1', 'global_add_tasks' => '1', 'update_ticket' => '1', 'own_ticket' => '1', 'show_all_ticket' => '1', 'show_assign_ticket' => '1', 'show_full_ticket' => '1', 'observe_ticket' => '1', 'update_followups' => '1', 'update_tasks' => '1', 'show_planning' => '1', 'statistic' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'import_externalauth_users' => 'w', 'create_validation' => '1', 'sla' => 'r', 'update_own_followups' => '1', 'show_my_problem' => '1', 'show_all_problem' => '1', 'tickettemplate' => 'r', 'ticketrecurrent' => 'r'), 'supervisor' => array('name' => 'Supervisor', 'interface' => 'central', 'password_update' => '1', 'computer' => 'w', 'monitor' => 'w', 'software' => 'w', 'networking' => 'w', 'printer' => 'w', 'peripheral' => 'w', 'cartridge' => 'w', 'consumable' => 'w', 'phone' => 'w', 'notes' => 'w', 'document' => 'w', 'knowbase' => 'w', 'faq' => 'w', 'reservation_helpdesk' => '1', 'reservation_central' => 'w', 'reports' => 'r', 'view_ocsng' => 'r', 'sync_ocsng' => 'w', 'entity_dropdown' => 'w', 'rule_ticket' => 'r', 'entity_rule_ticket' => 'w', 'user' => 'w', 'group' => 'r', 'entity' => 'r', 'transfer' => 'r', 'logs' => 'r', 'reminder_public' => 'w', 'create_ticket' => '1', 'delete_ticket' => '1', 'add_followups' => '1', 'global_add_followups' => '1', 'global_add_tasks' => '1', 'update_ticket' => '1', 'update_priority' => '1', 'own_ticket' => '1', 'steal_ticket' => '1', 'assign_ticket' => '1', 'show_all_ticket' => '1', 'show_assign_ticket' => '1', 'show_full_ticket' => '1', 'observe_ticket' => '1', 'update_followups' => '1', 'update_tasks' => '1', 'show_planning' => '1', 'show_all_planning' => '1', 'statistic' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'import_externalauth_users' => 'w', 'rule_mailcollector' => 'w', 'validate_ticket' => '1', 'create_validation' => '1', 'calendar' => 'w', 'sla' => 'w', 'update_own_followups' => '1', 'delete_followups' => '1', 'show_my_problem' => '1', 'show_all_problem' => '1', 'edit_all_problem' => '1', 'tickettemplate' => 'w', 'ticketrecurrent' => 'w')); foreach ($profiles as $profile => $data) { $query = "INSERT INTO `glpi_profiles`\n (`" . implode("`, `", array_keys($data)) . "`)\n VALUES ('" . implode("', '", $data) . "')"; $DB->queryOrDie($query, "0.83 create new profile {$profile}"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'Reminder visibility')); if (!TableExists('glpi_reminders_users')) { $query = "CREATE TABLE `glpi_reminders_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `reminders_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `reminders_id` (`reminders_id`),\n KEY `users_id` (`users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_reminders_users"); } if (!TableExists('glpi_groups_reminders')) { $query = "CREATE TABLE `glpi_groups_reminders` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `reminders_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `reminders_id` (`reminders_id`),\n KEY `groups_id` (`groups_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_groups_reminders"); } if (!TableExists('glpi_profiles_reminders')) { $query = "CREATE TABLE `glpi_profiles_reminders` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `reminders_id` int(11) NOT NULL DEFAULT '0',\n `profiles_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `reminders_id` (`reminders_id`),\n KEY `profiles_id` (`profiles_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_profiles_reminders"); } if (!TableExists('glpi_entities_reminders')) { $query = "CREATE TABLE `glpi_entities_reminders` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `reminders_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `reminders_id` (`reminders_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_entities_reminders"); } /// Migrate datas for is_helpdesk_visible : add all helpdesk profiles / drop field is_helpdesk_visible if (FieldExists("glpi_reminders", 'is_helpdesk_visible', false)) { $query = "SELECT `id`\n FROM `glpi_reminders`\n WHERE `is_helpdesk_visible` = 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Grab helpdesk profiles $helpdesk_profiles = array(); foreach ($DB->request("glpi_profiles", "`interface` = 'helpdesk' AND `reminder_public` = 'r'") as $data2) { $helpdesk_profiles[$data2['id']] = $data2['id']; } if (count($helpdesk_profiles)) { while ($data = $DB->fetch_assoc($result)) { foreach ($helpdesk_profiles as $pid) { $query = "INSERT INTO `glpi_profiles_reminders`\n (`reminders_id`, `profiles_id`)\n VALUES ('" . $data['id'] . "', '{$pid}');"; $DB->queryOrDie($query, "0.83 migrate data for is_helpdesk_visible drop on glpi_reminders"); } } } } } $migration->dropField("glpi_reminders", 'is_helpdesk_visible'); } // Migrate datas for entities + drop fields : is_private / entities_id / is_recursive if (FieldExists("glpi_reminders", 'is_private', false)) { $query = "SELECT *\n FROM `glpi_reminders`\n WHERE `is_private` = 0"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $query = "INSERT INTO `glpi_entities_reminders`\n (`reminders_id`, `entities_id`, `is_recursive`)\n VALUES ('" . $data['id'] . "', '" . $data['entities_id'] . "',\n '" . $data['is_recursive'] . "');"; $DB->queryOrDie($query, "0.83 migrate data for public reminders"); } } } $migration->dropField("glpi_reminders", 'is_private'); $migration->dropField("glpi_reminders", 'entities_id'); $migration->dropField("glpi_reminders", 'is_recursive'); } $ADDTODISPLAYPREF['Reminder'] = array(2, 3, 4, 5, 6, 7); $migration->displayMessage(sprintf(__('Data migration - %s'), 'KnowbaseItem visibility')); if (!TableExists('glpi_knowbaseitems_users')) { $query = "CREATE TABLE `glpi_knowbaseitems_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `knowbaseitems_id` (`knowbaseitems_id`),\n KEY `users_id` (`users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_knowbaseitems_users"); } if (!TableExists('glpi_groups_knowbaseitems')) { $query = "CREATE TABLE `glpi_groups_knowbaseitems` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `knowbaseitems_id` (`knowbaseitems_id`),\n KEY `groups_id` (`groups_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_groups_knowbaseitems"); } if (!TableExists('glpi_knowbaseitems_profiles')) { $query = "CREATE TABLE `glpi_knowbaseitems_profiles` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n `profiles_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `knowbaseitems_id` (`knowbaseitems_id`),\n KEY `profiles_id` (`profiles_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_knowbaseitems_profiles"); } if (!TableExists('glpi_entities_knowbaseitems')) { $query = "CREATE TABLE `glpi_entities_knowbaseitems` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `knowbaseitems_id` (`knowbaseitems_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.83 add table glpi_entities_knowbaseitems"); } /// Migrate datas for entities_id / is_recursive if (FieldExists("glpi_knowbaseitems", 'entities_id', false)) { $query = "SELECT *\n FROM `glpi_knowbaseitems`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $query = "INSERT INTO `glpi_entities_knowbaseitems`\n (`knowbaseitems_id`, `entities_id`, `is_recursive`)\n VALUES ('" . $data['id'] . "', '" . $data['entities_id'] . "',\n '" . $data['is_recursive'] . "');"; $DB->queryOrDie($query, "0.83 migrate data for entities on glpi_entities_knowbaseitems"); } } } $migration->dropField("glpi_knowbaseitems", 'entities_id'); $migration->dropField("glpi_knowbaseitems", 'is_recursive'); } // Plugins $migration->addField('glpi_plugins', 'license', 'string'); $migration->migrationOneTable('glpi_entitydatas'); $restore_root_entity_value = false; // create root entity if not exist with old default values if (countElementsInTable('glpi_entitydatas', 'entities_id=0') == 0) { $query = "INSERT INTO `glpi_entitydatas`\n (`entities_id`, `entities_id_software`,\n `autofill_order_date`, `autofill_delivery_date`, `autofill_buy_date`,\n `autofill_use_date`, `autofill_warranty_date`,\n `inquest_config`, `inquest_rate`, `inquest_delay`,\n `tickettype`, `calendars_id`, `tickettemplates_id`,\n `autoclose_delay`, `auto_assign_mode`,\n `cartridges_alert_repeat`, `consumables_alert_repeat`,\n `use_licenses_alert`, `use_infocoms_alert`, `notclosed_delay`,\n `use_contracts_alert`, `use_reservations_alert`)\n VALUES (0, -10,\n 0, 0, 0,\n 0, 0,\n 1, 0, 0,\n 1, 0, '{$default_ticket_template}',\n -1, -1,\n -1, -1,\n -1, -1, -1,\n -1, -1)"; // -1 to keep config value - see 1647 $DB->queryOrDie($query, "0.83 add entities_id 0 in glpi_entitydatas"); $restore_root_entity_value = true; } else { $query = "UPDATE `glpi_entitydatas`\n SET `tickettemplates_id` = '{$default_ticket_template}'\n WHERE `entities_id` = 0\n AND `tickettemplates_id` = -2"; $DB->queryOrDie($query, "0.83 update tickettemplates_id for root entity in glpi_entitydatas"); $query = "UPDATE `glpi_entitydatas`\n SET `entities_id_software` = -10\n WHERE `entities_id` = 0\n AND `entities_id_software` = -2"; $DB->queryOrDie($query, "0.83 update entities_id_software for root entity in glpi_entitydatas"); // For root entity already exists in entitydatas in 0.78 $query = "UPDATE `glpi_entitydatas`\n SET `tickettype` = 1\n WHERE `entities_id` = 0\n AND `tickettype` = 0"; $DB->queryOrDie($query, "0.83 update tickettype for root entity in glpi_entitydatas"); $query = "UPDATE `glpi_entitydatas`\n SET `inquest_config` = 1\n WHERE `entities_id` = 0\n AND `inquest_config` = 0"; $DB->queryOrDie($query, "0.83 update inquest_config for root entity in glpi_entitydatas "); $query = "UPDATE `glpi_entitydatas`\n SET `inquest_rate` = 0\n WHERE `entities_id` = 0\n AND `inquest_rate` = '-1'"; $DB->queryOrDie($query, "0.83 update inquest_rate for root entity in glpi_entitydatas "); $query = "UPDATE `glpi_entitydatas`\n SET `inquest_delay` = 0\n WHERE `entities_id` = 0\n AND `inquest_delay` = '-1'"; $DB->queryOrDie($query, "0.83 update inquest_delay for root entity in glpi_entitydatas "); } // migration to new values for inherit parent (0 => -2) $field0 = array('calendars_id', 'tickettype', 'inquest_config'); foreach ($field0 as $field_0) { if (FieldExists("glpi_entitydatas", $field_0, false)) { $query = "UPDATE `glpi_entitydatas`\n SET `{$field_0}` = '-2'\n WHERE `{$field_0}` = '0'\n AND `entities_id` > 0"; $DB->queryOrDie($query, "0.83 new value for inherit parent 0 in glpi_entitydatas"); } } // new default value $migration->changeField("glpi_entitydatas", "calendars_id", "calendars_id", "int(11) NOT NULL DEFAULT '-2'"); $migration->changeField("glpi_entitydatas", "tickettype", "tickettype", "int(11) NOT NULL DEFAULT '-2'"); $migration->changeField("glpi_entitydatas", "inquest_config", "inquest_config", "int(11) NOT NULL DEFAULT '-2'"); $migration->changeField("glpi_entitydatas", "inquest_rate", "inquest_rate", "int(11) NOT NULL DEFAULT '0'"); $migration->changeField("glpi_entitydatas", "inquest_delay", "inquest_delay", "int(11) NOT NULL DEFAULT '-10'"); // migration to new values for inherit parent (-1 => -2) $fieldparent = array('autofill_buy_date', 'autofill_delivery_date', 'autofill_warranty_date', 'autofill_order_date', 'autofill_use_date'); foreach ($fieldparent as $field_parent) { if (FieldExists("glpi_entitydatas", $field_parent, false)) { $query = "UPDATE `glpi_entitydatas`\n SET `{$field_parent}` = '-2'\n WHERE `{$field_parent}` = '-1'"; $DB->queryOrDie($query, "0.83 new value for inherit parent -1 in glpi_entitydatas"); } } // new default value $migration->changeField("glpi_entitydatas", "autofill_buy_date", "autofill_buy_date", 'string', array('value' => '-2')); $migration->changeField("glpi_entitydatas", "autofill_delivery_date", "autofill_delivery_date", 'string', array('value' => '-2')); $migration->changeField("glpi_entitydatas", "autofill_warranty_date", "autofill_warranty_date", 'string', array('value' => '-2')); $migration->changeField("glpi_entitydatas", "autofill_order_date", "autofill_order_date", 'string', array('value' => '-2')); $migration->changeField("glpi_entitydatas", "autofill_use_date", "autofill_use_date", 'string', array('value' => '-2')); // migration to new values for inherit config $fieldconfig = array('auto_assign_mode', 'autoclose_delay', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'notclosed_delay', 'use_contracts_alert', 'use_infocoms_alert', 'use_licenses_alert', 'use_reservations_alert'); $query = "SELECT *\n FROM `glpi_configs`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { if ($data = $DB->fetch_assoc($result)) { foreach ($fieldconfig as $field_config) { if (FieldExists("glpi_entitydatas", $field_config, false) && FieldExists("glpi_configs", $field_config, false)) { // value of general config $query = "UPDATE `glpi_entitydatas`\n SET `{$field_config}` = '" . $data[$field_config] . "'\n WHERE `{$field_config}` = -1"; $DB->queryOrDie($query, "0.83 migrate data from config to glpi_entitydatas"); $migration->changeField("glpi_entitydatas", "{$field_config}", "{$field_config}", "int(11) NOT NULL DEFAULT '-2'"); $migration->dropField("glpi_configs", $field_config); } } if (FieldExists("glpi_entitydatas", "auto_assign_mode", false)) { // new value for never $query = "UPDATE `glpi_entitydatas`\n SET `auto_assign_mode` = -10\n WHERE `auto_assign_mode` = 0"; $DB->queryOrDie($query, "0.83 change value Never in glpi_entitydatas for auto_assign_mode"); } } } } // value of config in each entity $fieldconfig = array('default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold'); $query = "SELECT *\n FROM `glpi_configs`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { if ($data = $DB->fetch_assoc($result)) { foreach ($fieldconfig as $field_config) { if (FieldExists("glpi_configs", $field_config, false) && !FieldExists("glpi_entitydatas", $field_config, false)) { // add config fields in entitydatas $migration->addField("glpi_entitydatas", $field_config, 'integer', array('update' => $data[$field_config], 'value' => $field_config == "default_alarm_threshold" ? 10 : 0)); $migration->dropField("glpi_configs", $field_config); } } } } } if ($restore_root_entity_value) { $query = "UPDATE `glpi_entitydatas`\n SET `calendars_id` = 0\n WHERE `entities_id` = 0;"; $DB->queryOrDie($query, "0.83 restore root entity default value"); } $migration->addKey('glpi_computervirtualmachines', 'computers_id'); $migration->addKey('glpi_computervirtualmachines', 'entities_id'); $migration->addKey('glpi_computervirtualmachines', 'name'); $migration->addKey('glpi_computervirtualmachines', 'virtualmachinestates_id'); $migration->addKey('glpi_computervirtualmachines', 'virtualmachinesystems_id'); $migration->addKey('glpi_computervirtualmachines', 'vcpu'); $migration->addKey('glpi_computervirtualmachines', 'ram'); // $ADDTODISPLAYPREF['KnowbaseItem'] = array(2,3,4,5,6,7); $renametables = array('TicketSolutionType' => 'SolutionType', 'TicketSolutionTemplate' => 'SolutionTemplate', 'TicketCategory' => 'ITILCategory'); $itemtype_tables = array("glpi_bookmarks" => 'itemtype', "glpi_bookmarks_users" => 'itemtype', "glpi_displaypreferences" => 'itemtype', "glpi_logs" => 'itemtype', "glpi_events" => 'type'); foreach ($itemtype_tables as $table => $field) { foreach ($renametables as $key => $val) { $query = "UPDATE `{$table}`\n SET `{$field}` = '" . $val . "'\n WHERE `{$field}` = '" . $key . "'"; $DB->queryOrDie($query, "0.83 update itemtype of table {$table} for {$val}"); } } // ************ Keep it at the end ************** $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences')); // Change is_recursive index $query = "UPDATE `glpi_displaypreferences`\n SET `num` = '86'\n WHERE `itemtype` = 'Group'\n AND `num` = '6'"; $DB->query($query); foreach ($ADDTODISPLAYPREF as $type => $tab) { $query = "SELECT DISTINCT `users_id`\n FROM `glpi_displaypreferences`\n WHERE `itemtype` = '{$type}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $query = "SELECT MAX(`rank`)\n FROM `glpi_displaypreferences`\n WHERE `users_id` = '" . $data['users_id'] . "'\n AND `itemtype` = '{$type}'"; $result = $DB->query($query); $rank = $DB->result($result, 0, 0); $rank++; foreach ($tab as $newval) { $query = "SELECT *\n FROM `glpi_displaypreferences`\n WHERE `users_id` = '" . $data['users_id'] . "'\n AND `num` = '{$newval}'\n AND `itemtype` = '{$type}'"; if ($result2 = $DB->query($query)) { if ($DB->numrows($result2) == 0) { $query = "INSERT INTO `glpi_displaypreferences`\n (`itemtype` ,`num` ,`rank` ,`users_id`)\n VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n '" . $data['users_id'] . "')"; $DB->query($query); } } } } } else { // Add for default user $rank = 1; foreach ($tab as $newval) { $query = "INSERT INTO `glpi_displaypreferences`\n (`itemtype` ,`num` ,`rank` ,`users_id`)\n VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')"; $DB->query($query); } } } } // must always be at the end $migration->executeMigration(); return $updateresult; }
public static function displayValue($value, $values) { if (!empty($values)) { $ldap_values = json_decode($values); $ldap_dropdown = new RuleRightParameter(); $ldap_dropdown->getFromDB($ldap_values->ldap_attribute); $attribute = array($ldap_dropdown->fields['value']); $config_ldap = new AuthLDAP(); $config_ldap->getFromDB($ldap_values->ldap_auth); $ds = $config_ldap->connect(); $sn = ldap_search($ds, $config_ldap->fields['basedn'], $ldap_values->ldap_filter, $attribute); $entries = ldap_get_entries($ds, $sn); array_shift($entries); $tab_values = array(); foreach ($entries as $id => $attr) { if (isset($attr[$attribute[0]]) && !in_array($attr[$attribute[0]][0], $tab_values)) { $tab_values[$id] = $attr[$attribute[0]][0]; } } sort($tab_values); } return $value != '' ? $tab_values[$value] : ''; }
function plugin_moreldap_item_add_or_update_user($user) { //Ignore users without auths_id if (!isset($user->input["auths_id"])) { return; } // We update LDAP field only if LDAP directory is defined if (isset($user->input["locations_id"])) { return; } // default : store locations outside of any entity $entityID = -1; $pluginAuthLDAP = new PluginMoreldapAuthLDAP(); $authsId = isset($user->input["auths_id"]) ? $user->input["auths_id"] : $user->fields["auths_id"]; if ($authsId > 0 && $pluginAuthLDAP->getFromDBByQuery("WHERE `id`='{$authsId}'")) { // The target entity for the locations to be created $entityID = $pluginAuthLDAP->fields['entities_id']; // find from config all attributes to read from LDAP $fields = array(); $locationHierarchy = explode('>', $pluginAuthLDAP->fields['location']); foreach ($locationHierarchy as $locationSubAttribute) { $locationSubAttribute = trim($locationSubAttribute); if (strlen($locationSubAttribute) > 0) { $fields[] = $locationSubAttribute; } } // LDAP query to read the needed attributes for the user $ldap_connection = 0; if (!isset($user->input["_ldap_conn"]) || !isset($user->fields["_ldap_conn"])) { $ldap = new AuthLDAP(); $ldap->getFromDB($authsId); $ldap_connection = $ldap->connect(); } else { $ldap_connection = isset($user->input["_ldap_conn"]) ? $user->input["_ldap_conn"] : $user->fields["_ldap_conn"]; } $userdn = isset($user->input["user_dn"]) ? $user->input["user_dn"] : $user->fields["user_dn"]; $userdn = str_replace('\\\\', '\\', $userdn); $sr = @ldap_read($ldap_connection, $userdn, "objectClass=*", $fields); if (!is_resource($sr) || ldap_errno($ldap_connection) > 0) { return; } $v = AuthLDAP::get_entries_clean($ldap_connection, $sr); //Find all locations needed to create the deepest one $locationPath = array(); $incompleteLocation = false; foreach ($fields as $locationSubAttribute) { $locationSubAttribute = strtolower($locationSubAttribute); if (isset($v[0][$locationSubAttribute][0])) { $locationPath[] = $v[0][$locationSubAttribute][0]; } else { // A LDAP attribute is not defined for the user. Cannot build the completename // Therefore we must giveup importing this location $incompleteLocation = true; } } // TODO : test if location import is enabled earlier in this function if ($pluginAuthLDAP->fields['location_enabled'] == 'Y') { if ($incompleteLocation == false) { $location = new Location(); $locationAncestor = 0; $locationCompleteName = array(); $allLocationsExist = true; // Assume we created or found all locations // while ($locatinItem = array_shift($locationPath) && $allLocationsExist) { foreach ($locationPath as $locationItem) { if ($allLocationsExist) { $locationCompleteName[] = $locationItem; $locationItem = Toolbox::addslashes_deep(array('entities_id' => $entityID, 'name' => $locationItem, 'locations_id' => $locationAncestor, 'completename' => implode(' > ', $locationCompleteName), 'is_recursive' => $pluginAuthLDAP->fields['is_recursive'], 'comment' => __("Created by MoreLDAP", "moreldap"))); $locationAncestor = $location->findID($locationItem); if ($locationAncestor == -1) { // The location does not exists yet $locationAncestor = $location->add($locationItem); } if ($locationAncestor == false) { // If a location could not be imported and does not exist // then give up importing children items $allLocationsExist = false; } } } if ($allLocationsExist) { // All locations exist to match the path described un LDAP $locations_id = $locationAncestor; $myuser = new User(); // new var to prevent user->input erasing (object are always passed by "reference") $myuser->update(array('id' => $user->getID(), 'locations_id' => $locations_id)); } } } else { // If the location retrieval is disabled, enablig this line will erase the location for the user. // $fields['locations_id'] = 0; } } }
} else { addMessageAfterRedirect($LANG['login'][23], false, ERROR); } glpi_header($CFG_GLPI["root_doc"] . "/front/authldap.php?next=extauth_ldap&id=" . $newID); } } glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_POST["delete"])) { $config_ldap->delete($_POST); $_SESSION['glpi_authconfig'] = 1; $config_ldap->redirectToList(); } else { if (isset($_POST["test_ldap"])) { $ldap = new AuthLDAP(); $ldap->getFromDB($_POST["id"]); if (AuthLdap::testLDAPConnection($_POST["id"])) { $_SESSION["LDAP_TEST_MESSAGE"] = $LANG['login'][22] . " (" . $LANG['ldap'][21] . " : " . $ldap->fields["name"] . ")"; } else { $_SESSION["LDAP_TEST_MESSAGE"] = $LANG['login'][23] . " (" . $LANG['ldap'][21] . " : " . $ldap->fields["name"] . ")"; } glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_POST["test_ldap_replicate"])) { foreach ($_POST["test_ldap_replicate"] as $replicate_id => $value) { $replicate = new AuthLdapReplicate(); $replicate->getFromDB($replicate_id); if (AuthLdap::testLDAPConnection($_POST["id"], $replicate_id)) { $_SESSION["LDAP_TEST_MESSAGE"] = $LANG['login'][22] . " (" . $LANG['ldap'][19] . " : " . $replicate->fields["name"] . ")"; } else { $_SESSION["LDAP_TEST_MESSAGE"] = $LANG['login'][23] . " (" . $LANG['ldap'][19] . " : " . $replicate->fields["name"] . ")";
/** * Display information from LDAP server for user **/ private function showLdapDebug() { global $LANG; if ($this->fields['authtype'] != Auth::LDAP) { return false; } echo "<div class='spaced'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='4'>" . $LANG['setup'][137] . ' - ' . $LANG['login'][2] . "</th></tr>"; echo "<tr class='tab_bg_2'><td>" . $LANG['ldap'][26] . " :</td>"; echo "<td>" . $this->fields['user_dn'] . "</td></tr>\n"; if ($this->fields['user_dn']) { echo "<tr class='tab_bg_2'><td>" . $LANG['title'][13] . " :</td><td>"; $config_ldap = new AuthLDAP(); $ds = false; if ($config_ldap->getFromDB($this->fields['auths_id'])) { $ds = $config_ldap->connect(); } if ($ds) { $info = AuthLdap::getUserByDn($ds, $this->fields['user_dn'], array('*', 'createTimeStamp', 'modifyTimestamp')); if (is_array($info)) { printCleanArray($info); } else { echo $LANG['stats'][2]; } } else { echo $LANG['log'][41]; } echo "</td></tr>\n"; } echo "</table></div>"; }