Example #1
0
/**
 * DO NOT FORGET TO REPLACE XX AND XY OCCURENCES WITH CORRECT VALUES
 * Update from XX to XY
 *
 * @return bool for success (will die for most error)
**/
function updateXXtoXY()
{
    global $DB, $migration, $CFG_GLPI;
    $current_config = Config::getConfigurationValues('core');
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), 'XY'));
    $migration->setVersion('XY');
    $backup_tables = false;
    // table already exist but deleted during the migration
    // not table created during the migration
    $newtables = array();
    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);
    }
    //put you migration script here
    // ************ Keep it at the end **************
    $migration->executeMigration();
    return $updateresult;
}
Example #2
0
function loadDataset()
{
    global $CFG_GLPI;
    // Unit test data definition
    $data = ['_version' => 2, 'Entity' => [['name' => '_test_root_entity', 'entities_id' => 0], ['name' => '_test_child_1', 'entities_id' => '_test_root_entity'], ['name' => '_test_child_2', 'entities_id' => '_test_root_entity']], 'Computer' => [['name' => '_test_pc01', 'entities_id' => '_test_root_entity'], ['name' => '_test_pc02', 'entities_id' => '_test_root_entity'], ['name' => '_test_pc11', 'entities_id' => '_test_child_1'], ['name' => '_test_pc12', 'entities_id' => '_test_child_1'], ['name' => '_test_pc21', 'entities_id' => '_test_child_2'], ['name' => '_test_pc22', 'entities_id' => '_test_child_2']], 'Software' => [['name' => '_test_soft', 'entities_id' => '_test_root_entity', 'is_recursive' => 1]], 'SoftwareVersion' => [['name' => '_test_softver_1', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft'], ['name' => '_test_softver_2', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft']], 'Printer' => [['name' => '_test_printer_all', 'entities_id' => '_test_root_entity', 'is_recursive' => 1], ['name' => '_test_printer_ent0', 'entities_id' => '_test_root_entity', 'is_recursive' => 0], ['name' => '_test_printer_ent1', 'entities_id' => '_test_child_1', 'is_recursive' => 0], ['name' => '_test_printer_ent2', 'entities_id' => '_test_child_2', 'is_recursive' => 0]], 'User' => [['name' => TU_USER, 'password' => TU_PASS, 'password2' => TU_PASS, 'entities_id' => '_test_root_entity', 'profiles_id' => 4, '_entities_id' => '_test_root_entity', '_profiles_id' => 4, '_is_recursive' => 1]]];
    // To bypass various right checks
    $_SESSION['glpicronuserrunning'] = "cron_phpunit";
    $_SESSION['glpi_use_mode'] = Session::NORMAL_MODE;
    $CFG_GLPI['root_doc'] = '/glpi';
    // need to set theses in DB, because tests for API use http call and this bootstrap file is not called
    Config::setConfigurationValues('core', ['url_base' => GLPI_URI, 'url_base_api' => GLPI_URI . '/apirest.php']);
    $CFG_GLPI['url_base'] = GLPI_URI;
    $CFG_GLPI['url_base_api'] = GLPI_URI . '/apirest.php';
    @mkdir(GLPI_LOG_DIR, 0755, true);
    $conf = Config::getConfigurationValues('phpunit');
    if (isset($conf['dataset']) && $conf['dataset'] == $data['_version']) {
        printf("\nGLPI dataset version %d already loaded\n\n", $data['_version']);
    } else {
        printf("\nLoading GLPI dataset version %d\n", $data['_version']);
        $ids = array();
        foreach ($data as $type => $inputs) {
            if ($type[0] == '_') {
                continue;
            }
            foreach ($inputs as $input) {
                // Resolve FK
                foreach ($input as $k => $v) {
                    if (isForeignKeyField($k) && isset($ids[$v]) && !is_numeric($v)) {
                        $input[$k] = $ids[$v];
                    }
                }
                if (isset($input['name']) && ($item = getItemByTypeName($type, $input['name']))) {
                    $input['id'] = $ids[$input['name']] = $item->getField('id');
                    $item->update($input);
                    echo ".";
                } else {
                    // Not found, create it
                    $item = getItemForItemtype($type);
                    $id = $item->add($input);
                    echo "+";
                    if (isset($input['name'])) {
                        $ids[$input['name']] = $id;
                    }
                }
            }
        }
        echo "\nDone\n\n";
        Config::setConfigurationValues('phpunit', ['dataset' => $data['_version']]);
    }
}
Example #3
0
/**
 * Update from 9.1 to 9.1.1
 *
 * @return bool for success (will die for most error)
**/
function update91to911()
{
    global $DB, $migration, $CFG_GLPI;
    $current_config = Config::getConfigurationValues('core');
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '9.1.1'));
    $migration->setVersion('9.1.1');
    $backup_tables = false;
    // table already exist but deleted during the migration
    // not table created during the migration
    $newtables = array();
    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);
    }
    // rectify missing right in 9.1 update
    if (countElementsInTable("glpi_profilerights", "`name` = 'license'") == 0) {
        foreach ($DB->request("glpi_profilerights", "`name` = 'software'") as $profrights) {
            $query = "INSERT INTO `glpi_profilerights`\n                          (`id`, `profiles_id`, `name`, `rights`)\n                   VALUES (NULL, '" . $profrights['profiles_id'] . "', 'license',\n                           '" . $profrights['rights'] . "')";
            $DB->queryOrDie($query, "9.1 add right for softwarelicense");
        }
    }
    // rectify indexes in 9.1 update
    $migration->addKey('glpi_tickets', 'slts_ttr_id');
    $migration->dropKey('glpi_tickets', 'slalevels_id');
    $migration->addKey('glpi_tickets', 'ttr_slalevels_id');
    $migration->migrationOneTable('glpi_tickets');
    //put you migration script here
    // ************ Keep it at the end **************
    $migration->executeMigration();
    return $updateresult;
}
Example #4
0
 function showFormExample()
 {
     global $CFG_GLPI;
     if (!Session::haveRight("config", UPDATE)) {
         return false;
     }
     $my_config = Config::getConfigurationValues('plugin:Example');
     echo "<form name='form' action=\"" . Toolbox::getItemTypeFormURL('Config') . "\" method='post'>";
     echo "<div class='center' id='tabsbody'>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='4'>" . __('Example setup') . "</th></tr>";
     echo "<td >" . __('My boolean choice :') . "</td>";
     echo "<td colspan='3'>";
     echo "<input type='hidden' name='config_class' value='" . __CLASS__ . "'>";
     echo "<input type='hidden' name='config_context' value='plugin:Example'>";
     Dropdown::showYesNo("configuration", $my_config['configuration']);
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td colspan='4' class='center'>";
     echo "<input type='submit' name='update' class='submit' value=\"" . _sx('button', 'Save') . "\">";
     echo "</td></tr>";
     echo "</table></div>";
     Html::closeForm();
 }
Example #5
0
function updateDbUpTo031()
{
    global $DB, $migration;
    $ret = array();
    // Before 0.31
    if (!TableExists("glpi_config") && !TableExists("glpi_configs")) {
        $query = "CREATE TABLE `glpi_config` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `num_of_events` varchar(200) NOT NULL default '',\n                  `jobs_at_login` varchar(200) NOT NULL default '',\n                  `sendexpire` varchar(200) NOT NULL default '',\n                  `cut` varchar(200) NOT NULL default '',\n                  `expire_events` varchar(200) NOT NULL default '',\n                  `list_limit` varchar(200) NOT NULL default '',\n                  `version` varchar(200) NOT NULL default '',\n                  `logotxt` varchar(200) NOT NULL default '',\n                  `root_doc` varchar(200) NOT NULL default '',\n                  `event_loglevel` varchar(200) NOT NULL default '',\n                  `mailing` varchar(200) NOT NULL default '',\n                  `imap_auth_server` varchar(200) NOT NULL default '',\n                  `imap_host` varchar(200) NOT NULL default '',\n                  `ldap_host` varchar(200) NOT NULL default '',\n                  `ldap_basedn` varchar(200) NOT NULL default '',\n                  `ldap_rootdn` varchar(200) NOT NULL default '',\n                  `ldap_pass` varchar(200) NOT NULL default '',\n                  `admin_email` varchar(200) NOT NULL default '',\n                  `mailing_signature` varchar(200) NOT NULL default '',\n                  `mailing_new_admin` varchar(200) NOT NULL default '',\n                  `mailing_followup_admin` varchar(200) NOT NULL default '',\n                  `mailing_finish_admin` varchar(200) NOT NULL default '',\n                  `mailing_new_all_admin` varchar(200) NOT NULL default '',\n                  `mailing_followup_all_admin` varchar(200) NOT NULL default '',\n                  `mailing_finish_all_admin` varchar(200) NOT NULL default '',\n                  `mailing_new_all_normal` varchar(200) NOT NULL default '',\n                  `mailing_followup_all_normal` varchar(200) NOT NULL default '',\n                  `mailing_finish_all_normal` varchar(200) NOT NULL default '',\n                  `mailing_new_attrib` varchar(200) NOT NULL default '',\n                  `mailing_followup_attrib` varchar(200) NOT NULL default '',\n                  `mailing_finish_attrib` varchar(200) NOT NULL default '',\n                  `mailing_new_user` varchar(200) NOT NULL default '',\n                  `mailing_followup_user` varchar(200) NOT NULL default '',\n                  `mailing_finish_user` varchar(200) NOT NULL default '',\n                  `ldap_field_name` varchar(200) NOT NULL default '',\n                  `ldap_field_email` varchar(200) NOT NULL default '',\n                  `ldap_field_location` varchar(200) NOT NULL default '',\n                  `ldap_field_realname` varchar(200) NOT NULL default '',\n                  `ldap_field_phone` varchar(200) NOT NULL default '',\n                PRIMARY KEY (`ID`)\n                ) TYPE=MyISAM AUTO_INCREMENT=2 ";
        $DB->queryOrDie($query);
        $query = "INSERT INTO `glpi_config`\n                VALUES (1, '10', '1', '1', '80', '30', '15', ' 0.31', 'GLPI powered by indepnet',\n                        '/glpi', '5', '0', '', '', '', '', '', '', '*****@*****.**', 'SIGNATURE',\n                        '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0','1', '1', '1',\n                        'uid', 'mail', 'physicaldeliveryofficename', 'cn', 'telephonenumber')";
        $DB->queryOrDie($query);
        echo "<p class='center'>Version > 0.31  </p>";
    }
    // Save if problem with session during update
    $glpilanguage = $_SESSION["glpilanguage"];
    // < 0.78
    if (TableExists("glpi_config")) {
        // Get current version
        // Use language from session, even if sometime not reliable
        $query = "SELECT `version`, 'language'\n                FROM `glpi_config`";
        $result = $DB->queryOrDie($query, "get current version");
        $current_version = trim($DB->result($result, 0, 0));
        $glpilanguage = trim($DB->result($result, 0, 1));
        // < 0.85
    } else {
        if (FieldExists('glpi_configs', 'version')) {
            // Get current version and language
            $query = "SELECT `version`, `language`\n                FROM `glpi_configs`";
            $result = $DB->queryOrDie($query, "get current version");
            $current_version = trim($DB->result($result, 0, 0));
            $glpilanguage = trim($DB->result($result, 0, 1));
        } else {
            $configurationValues = Config::getConfigurationValues('core', array('version', 'language'));
            $current_version = $configurationValues['version'];
            $glpilanguage = $configurationValues['language'];
        }
    }
    // To prevent problem of execution time
    ini_set("max_execution_time", "0");
    $migration = new Migration($current_version);
    switch ($current_version) {
        case "0.31":
            include "update_031_04.php";
            update031to04();
        case "0.4":
        case "0.41":
            include "update_04_042.php";
            update04to042();
        case "0.42":
            showLocationUpdateForm();
            include "update_042_05.php";
            update042to05();
        case "0.5":
            include "update_05_051.php";
            update05to051();
        case "0.51":
        case "0.51a":
            include "update_051_06.php";
            update051to06();
        case "0.6":
            include "update_06_065.php";
            update06to065();
        case "0.65":
            include "update_065_068.php";
            update065to068();
        case "0.68":
            include "update_068_0681.php";
            update068to0681();
        case "0.68.1":
        case "0.68.2":
        case "0.68.3":
            // Force update content
            if (showLocationUpdateForm()) {
                $query = "UPDATE `glpi_config`\n                      SET `version` = ' 0.68.3x'";
                $DB->queryOrDie($query, "0.68.3");
                showContentUpdateForm();
                exit;
            }
        case "0.68.3x":
            // Special version for replay upgrade process from here
            include "update_0681_07.php";
            update0681to07();
        case "0.7":
        case "0.70.1":
        case "0.70.2":
            include "update_07_071.php";
            update07to071();
        case "0.71":
        case "0.71.1":
            include "update_071_0712.php";
            update071to0712();
        case "0.71.2":
            include "update_0712_0713.php";
            update0712to0713();
        case "0.71.3":
        case "0.71.4":
        case "0.71.5":
        case "0.71.6":
            include "update_0713_072.php";
            update0713to072();
        case "0.72":
            include "update_072_0721.php";
            update072to0721();
        case "0.72.1":
            include "update_0721_0722.php";
            update0721to0722();
        case "0.72.2":
        case "0.72.21":
            include "update_0722_0723.php";
            update0722to0723();
        case "0.72.3":
        case "0.72.4":
            include "update_0723_078.php";
            update0723to078();
        case "0.78":
            include "update_078_0781.php";
            update078to0781();
        case "0.78.1":
            include "update_0781_0782.php";
            update0781to0782();
        case "0.78.2":
        case "0.78.3":
        case "0.78.4":
        case "0.78.5":
            include "update_0782_080.php";
            update0782to080();
        case "0.80":
            include "update_080_0801.php";
            update080to0801();
        case "0.80.1":
        case "0.80.2":
            include "update_0801_0803.php";
            update0801to0803();
        case "0.80.3":
        case "0.80.4":
        case "0.80.5":
        case "0.80.6":
        case "0.80.61":
        case "0.80.7":
            include "update_0803_083.php";
            update0803to083();
        case "0.83":
            include "update_083_0831.php";
            update083to0831();
        case "0.83.1":
        case "0.83.2":
            include "update_0831_0833.php";
            update0831to0833();
        case "0.83.3":
        case "0.83.31":
        case "0.83.4":
        case "0.83.5":
        case "0.83.6":
        case "0.83.7":
        case "0.83.8":
        case "0.83.9":
        case "0.83.91":
            include "update_0831_084.php";
            update0831to084();
        case "0.84":
            include "update_084_0841.php";
            update084to0841();
        case "0.84.1":
        case "0.84.2":
            include "update_0841_0843.php";
            update0841to0843();
        case "0.84.3":
            include "update_0843_0844.php";
            update0843to0844();
        case "0.84.4":
        case "0.84.5":
            include "update_0845_0846.php";
            update0845to0846();
        case "0.84.6":
        case "0.84.7":
        case "0.84.8":
        case "0.84.9":
            include "update_084_085.php";
            update084to085();
        case "0.85":
        case "0.85.1":
        case "0.85.2":
            include "update_085_0853.php";
            update085to0853();
        case "0.85.3":
        case "0.85.4":
        case "0.85.5":
            include "update_0853_090.php";
            update0853to090();
        case "0.90":
            break;
        default:
            include "update_031_04.php";
            update031to04();
            include "update_04_042.php";
            update04to042();
            showLocationUpdateForm();
            include "update_042_05.php";
            update042to05();
            include "update_05_051.php";
            update05to051();
            include "update_051_06.php";
            update051to06();
            include "update_06_065.php";
            update06to065();
            include "update_065_068.php";
            update065to068();
            include "update_068_0681.php";
            update068to0681();
            // Force update content
            $query = "UPDATE `glpi_config`\n                   SET `version` = ' 0.68.3x'";
            $DB->queryOrDie($query, "0.68.3");
            showContentUpdateForm();
            exit;
    }
    // Update version number and default langage and new version_founded ---- LEAVE AT THE END
    Config::setConfigurationValues('core', array('version' => '0.90', 'language' => $glpilanguage, 'founded_new_version' => ''));
    // Update process desactivate all plugins
    $plugin = new Plugin();
    $plugin->unactivateAll();
    DBmysql::optimize_tables($migration);
    return $ret;
}
Example #6
0
    // Get current version
    // Use language from session, even if sometime not reliable
    $query = "SELECT `version`, 'language'\n             FROM `glpi_config`";
    $result = $DB->queryOrDie($query, "get current version");
    $current_version = trim($DB->result($result, 0, 0));
    $glpilanguage = trim($DB->result($result, 0, 1));
    // < 0.85
} else {
    if (FieldExists('glpi_configs', 'version')) {
        // Get current version and language
        $query = "SELECT `version`, `language`\n             FROM `glpi_configs`";
        $result = $DB->queryOrDie($query, "get current version");
        $current_version = trim($DB->result($result, 0, 0));
        $glpilanguage = trim($DB->result($result, 0, 1));
    } else {
        $configurationValues = Config::getConfigurationValues('core', array('version', 'language'));
        $current_version = $configurationValues['version'];
        $glpilanguage = $configurationValues['language'];
    }
}
$migration = new CliMigration(GLPI_VERSION);
$migration->displayWarning("Current GLPI Data version: {$current_version}");
$migration->displayWarning("Current GLPI Code version: " . GLPI_VERSION);
$migration->displayWarning("Default GLPI Language: {$glpilanguage}");
// To prevent problem of execution time
ini_set("max_execution_time", "0");
// for change name of the version - to delete in next version
if ($current_version != "0.91" && GLPI_VERSION != 9.1) {
    if (version_compare($current_version, GLPI_VERSION, 'ne') && !in_array('--upgrade', $_SERVER['argv'])) {
        die("Upgrade required\n");
    }
Example #7
0
     } else {
         $config_object->forceTable('glpi_configs');
         if ($config_object->getFromDB(1)) {
             if (isset($config_object->fields['context'])) {
                 $current_config = Config::getConfigurationValues('core');
             } else {
                 $current_config = $config_object->fields;
             }
             $config_ok = true;
         }
     }
 } else {
     // Normal load process : use normal config table. If problem try old one
     if ($config_object->getFromDB(1)) {
         if (isset($config_object->fields['context'])) {
             $current_config = Config::getConfigurationValues('core');
         } else {
             $current_config = $config_object->fields;
         }
     } else {
         // Manage glpi_config table before 0.80
         $config_object->forceTable('glpi_config');
         if ($config_object->getFromDB(1)) {
             $current_config = $config_object->fields;
         }
     }
 }
 if (count($current_config) > 0) {
     $CFG_GLPI = array_merge($CFG_GLPI, $current_config);
     if (isset($CFG_GLPI['priority_matrix'])) {
         $CFG_GLPI['priority_matrix'] = importArrayFromDB($CFG_GLPI['priority_matrix'], true);
Example #8
0
/**
 * Update from 0.85 to 0.85.3
 *
 * @return bool for success (will die for most error)
**/
function update085to0853()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.85.3'));
    $migration->setVersion('0.85.3');
    $backup_tables = false;
    $newtables = array();
    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);
    }
    // Increase cron_limit
    $current_config = Config::getConfigurationValues('core');
    if ($current_config['cron_limit'] = 1) {
        Config::setConfigurationValues('core', array('cron_limit' => 5));
    }
    Config::setConfigurationValues('core', array('task_state' => Planning::TODO));
    $migration->addField("glpi_users", "task_state", "int(11) DEFAULT NULL");
    $migration->addField('glpi_projecttasks', 'is_milestone', 'bool');
    $migration->addKey('glpi_projecttasks', 'is_milestone');
    // Change Ticket items
    // Add glpi_items_tickets table for associated elements
    if (!TableExists('glpi_items_tickets')) {
        $query = "CREATE TABLE `glpi_items_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(255) DEFAULT NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`itemtype`, `items_id`, `tickets_id`),\n                  KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_items_tickets");
        $query = "SELECT `itemtype`, `items_id`, `id`\n                FROM `glpi_tickets`\n                WHERE `itemtype` IS NOT NULL\n                    AND `itemtype` <> ''\n                AND `items_id` != 0";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_items_tickets`\n                             (`id`, `items_id`, `itemtype`, `tickets_id`)\n                          VALUES (NULL, '" . $data['items_id'] . "', '" . $data['itemtype'] . "', '" . $data['id'] . "')";
                    $DB->queryOrDie($query, "0.85 associated ticket sitems migration");
                }
            }
        }
        // Delete old columns and keys
        $migration->dropField("glpi_tickets", "itemtype");
        $migration->dropField("glpi_tickets", "items_id");
        $migration->dropKey("glpi_tickets", "item");
    }
    // correct value of status for changes
    $query = "UPDATE `glpi_changes`\n             SET `status` = 1\n             WHERE `status` = 2";
    $DB->queryOrDie($query, "0.85.3 correct status for change");
    if ($migration->addField("glpi_entities", "is_notif_enable_default", "integer", array('value' => -2))) {
        $migration->migrationOneTable('glpi_entities');
        // Set directly to root entity
        $query = 'UPDATE `glpi_entities`
                SET `is_notif_enable_default` = 1
                WHERE `id` = 0';
        $DB->queryOrDie($query, "0.85.3 default value for is_notif_enable_default for root entity");
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // change type of field solution in ticket.change and problem
    $migration->changeField('glpi_tickets', 'solution', 'solution', 'longtext');
    $migration->changeField('glpi_changes', 'solution', 'solution', 'longtext');
    $migration->changeField('glpi_problems', 'solution', 'solution', 'longtext');
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
Example #9
0
/**
 * Update from 0.90.5 to 9.1
 *
 * @return bool for success (will die for most error)
**/
function update0905to91()
{
    global $DB, $migration, $CFG_GLPI;
    $current_config = Config::getConfigurationValues('core');
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '9.1'));
    $migration->setVersion('9.1');
    $backup_tables = false;
    $newtables = array('glpi_objectlocks');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Add of - %s to database'), 'Object Locks'));
    /************** Lock Objects *************/
    if (!TableExists('glpi_objectlocks')) {
        $query = "CREATE TABLE `glpi_objectlocks` (\n                 `id` INT(11) NOT NULL AUTO_INCREMENT,\n                 `itemtype` VARCHAR(100) NOT NULL COMMENT 'Type of locked object',\n                 `items_id` INT(11) NOT NULL COMMENT 'RELATION to various tables, according to itemtype (ID)',\n                 `users_id` INT(11) NOT NULL COMMENT 'id of the locker',\n                 `date_mod` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Timestamp of the lock',\n                 PRIMARY KEY (`id`),\n                 UNIQUE INDEX `item` (`itemtype`, `items_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "9.1 add table glpi_objectlocks");
        // insert new profile (read only access for locks)
        $query = "INSERT INTO `glpi_profiles`\n                       (`name`, `interface`, `is_default`, `helpdesk_hardware`, `helpdesk_item_type`,\n                        `ticket_status`, `date_mod`, `comment`, `problem_status`,\n                        `create_ticket_on_login`, `tickettemplates_id`, `change_status`)\n                VALUES ('Read-Only','central','0','0','[]',\n                        '{\"1\":{\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\"2\":{\"1\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\"3\":{\"1\":0,\"2\":0,\"4\":0,\"5\":0,\"6\":0},\"4\":{\"1\":0,\"2\":0,\"3\":0,\"5\":0,\"6\":0},\"5\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"6\":0},\"6\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0}}',\n                        NULL,\n                        'This profile defines read-only access. It is used when objects are locked. It can also be used to give to users rights to unlock objects.',\n                        '{\"1\":{\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"7\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"2\":{\"1\":0,\"7\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"3\":{\"1\":0,\"7\":0,\"2\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"4\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"5\":0,\"8\":0,\"6\":0},\"5\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"8\":0,\"6\":0},\"8\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\"6\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0}}',\n                        0, 0,\n                        '{\"1\":{\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"9\":{\"1\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"10\":{\"1\":0,\"9\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"7\":{\"1\":0,\"9\":0,\"10\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"4\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"11\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"12\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"5\":0,\"8\":0,\"6\":0},\"5\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"8\":0,\"6\":0},\"8\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"6\":0},\"6\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0}}')";
        $DB->queryOrDie($query, "9.1 update profile with Unlock profile");
        $ro_p_id = $DB->insert_id();
        $DB->queryOrDie("INSERT INTO `glpi_profilerights`\n                              (`profiles_id`, `name`, `rights`)\n                       VALUES ({$ro_p_id}, 'backup',                    '1'),\n                              ({$ro_p_id}, 'bookmark_public',           '1'),\n                              ({$ro_p_id}, 'budget',                    '161'),\n                              ({$ro_p_id}, 'calendar',                  '1'),\n                              ({$ro_p_id}, 'cartridge',                 '161'),\n                              ({$ro_p_id}, 'change',                    '1185'),\n                              ({$ro_p_id}, 'changevalidation',          '0'),\n                              ({$ro_p_id}, 'computer',                  '161'),\n                              ({$ro_p_id}, 'config',                    '1'),\n                              ({$ro_p_id}, 'consumable',                '161'),\n                              ({$ro_p_id}, 'contact_enterprise',        '161'),\n                              ({$ro_p_id}, 'contract',                  '161'),\n                              ({$ro_p_id}, 'device',                    '0'),\n                              ({$ro_p_id}, 'document',                  '161'),\n                              ({$ro_p_id}, 'domain',                    '1'),\n                              ({$ro_p_id}, 'dropdown',                  '1'),\n                              ({$ro_p_id}, 'entity',                    '1185'),\n                              ({$ro_p_id}, 'followup',                  '8193'),\n                              ({$ro_p_id}, 'global_validation',         '0'),\n                              ({$ro_p_id}, 'group',                     '129'),\n                              ({$ro_p_id}, 'infocom',                   '1'),\n                              ({$ro_p_id}, 'internet',                  '129'),\n                              ({$ro_p_id}, 'itilcategory',              '1'),\n                              ({$ro_p_id}, 'knowbase',                  '2177'),\n                              ({$ro_p_id}, 'knowbasecategory',          '1'),\n                              ({$ro_p_id}, 'link',                      '129'),\n                              ({$ro_p_id}, 'location',                  '1'),\n                              ({$ro_p_id}, 'logs',                      '1'),\n                              ({$ro_p_id}, 'monitor',                   '161'),\n                              ({$ro_p_id}, 'netpoint',                  '1'),\n                              ({$ro_p_id}, 'networking',                '161'),\n                              ({$ro_p_id}, 'notification',              '1'),\n                              ({$ro_p_id}, 'password_update',           '0'),\n                              ({$ro_p_id}, 'peripheral',                '161'),\n                              ({$ro_p_id}, 'phone',                     '161'),\n                              ({$ro_p_id}, 'planning',                  '3073'),\n                              ({$ro_p_id}, 'printer',                   '161'),\n                              ({$ro_p_id}, 'problem',                   '1185'),\n                              ({$ro_p_id}, 'profile',                   '129'),\n                              ({$ro_p_id}, 'project',                   '1185'),\n                              ({$ro_p_id}, 'projecttask',               '1'),\n                              ({$ro_p_id}, 'queuedmail',                '1'),\n                              ({$ro_p_id}, 'reminder_public',           '129'),\n                              ({$ro_p_id}, 'reports',                   '1'),\n                              ({$ro_p_id}, 'reservation',               '1'),\n                              ({$ro_p_id}, 'rssfeed_public',            '129'),\n                              ({$ro_p_id}, 'rule_dictionnary_dropdown', '1'),\n                              ({$ro_p_id}, 'rule_dictionnary_printer',  '1'),\n                              ({$ro_p_id}, 'rule_dictionnary_software', '1'),\n                              ({$ro_p_id}, 'rule_import',               '1'),\n                              ({$ro_p_id}, 'rule_ldap',                 '1'),\n                              ({$ro_p_id}, 'rule_mailcollector',        '1'),\n                              ({$ro_p_id}, 'rule_softwarecategories',   '1'),\n                              ({$ro_p_id}, 'rule_ticket',               '1'),\n                              ({$ro_p_id}, 'search_config',             '0'),\n                              ({$ro_p_id}, 'show_group_hardware',       '1'),\n                              ({$ro_p_id}, 'sla',                       '1'),\n                              ({$ro_p_id}, 'software',                  '161'),\n                              ({$ro_p_id}, 'solutiontemplate',          '1'),\n                              ({$ro_p_id}, 'state',                     '1'),\n                              ({$ro_p_id}, 'statistic',                 '1'),\n                              ({$ro_p_id}, 'task',                      '8193'),\n                              ({$ro_p_id}, 'taskcategory',              '1'),\n                              ({$ro_p_id}, 'ticket',                    '7297'),\n                              ({$ro_p_id}, 'ticketcost',                '1'),\n                              ({$ro_p_id}, 'ticketrecurrent',           '1'),\n                              ({$ro_p_id}, 'tickettemplate',            '1'),\n                              ({$ro_p_id}, 'ticketvalidation',          '0'),\n                              ({$ro_p_id}, 'transfer',                  '1'),\n                              ({$ro_p_id}, 'typedoc',                   '1'),\n                              ({$ro_p_id}, 'user',                      '2177')");
        // updates rights for Super-Admin profile
        foreach ($CFG_GLPI['lock_lockable_objects'] as $itemtype) {
            $rightnames[] = "'" . $itemtype::$rightname . "'";
        }
        $query = "UPDATE `glpi_profilerights`\n                SET `rights` = `rights` | " . UNLOCK . "\n                WHERE `profiles_id` = '4'\n                      AND `name` IN (" . implode(",", $rightnames) . ")";
        $DB->queryOrDie($query, "update super-admin profile with UNLOCK right");
        Config::setConfigurationValues('core', array('lock_use_lock_item' => 0, 'lock_autolock_mode' => 1, 'lock_directunlock_notification' => 0, 'lock_item_list' => '[]', 'lock_lockprofile_id' => $ro_p_id));
    }
    // cron task
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='ObjectLock' AND `name`='unlockobject'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('ObjectLock', 'unlockobject', 86400, 4, 0, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL); ";
        $DB->queryOrDie($query, "9.1 Add UnlockObject cron task");
    }
    // notification template
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'ObjectLock'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Unlock Item request', 'ObjectLock', NOW())";
            $DB->queryOrDie($query, "9.1 Add unlock request notification template");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                (`notificationtemplates_id`, `language`,\n                                 `subject`,\n                                 `content_text`,\n                                 `content_html`)\n                         VALUES ({$notid}, '', '##objectlock.action##',\n      '##objectlock.type## ###objectlock.id## - ##objectlock.name##\n\n      ##lang.objectlock.url##\n      ##objectlock.url##\n\n      ##lang.objectlock.date_mod##\n      ##objectlock.date_mod##\n\n      Hello ##objectlock.lockedby.firstname##,\n      Could go to this item and unlock it for me?\n      Thank you,\n      Regards,\n      ##objectlock.requester.firstname##',\n      '&lt;table&gt;\n      &lt;tbody&gt;\n      &lt;tr&gt;&lt;th colspan=\"2\"&gt;&lt;a href=\"##objectlock.url##\"&gt;##objectlock.type## ###objectlock.id## - ##objectlock.name##&lt;/a&gt;&lt;/th&gt;&lt;/tr&gt;\n      &lt;tr&gt;\n      &lt;td&gt;##lang.objectlock.url##&lt;/td&gt;\n      &lt;td&gt;##objectlock.url##&lt;/td&gt;\n      &lt;/tr&gt;\n      &lt;tr&gt;\n      &lt;td&gt;##lang.objectlock.date_mod##&lt;/td&gt;\n      &lt;td&gt;##objectlock.date_mod##&lt;/td&gt;\n      &lt;/tr&gt;\n      &lt;/tbody&gt;\n      &lt;/table&gt;\n      &lt;p&gt;&lt;span style=\"font-size: small;\"&gt;Hello ##objectlock.lockedby.firstname##,&lt;br /&gt;Could go to this item and unlock it for me?&lt;br /&gt;Thank you,&lt;br /&gt;Regards,&lt;br /&gt;##objectlock.requester.firstname## ##objectlock.requester.lastname##&lt;/span&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "9.1 add Unlock Request notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                                (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                                 `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                                 `date_mod`)\n                         VALUES ('Request Unlock Items', 0, 'ObjectLock', 'unlock', 'mail',\n                                   {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "9.1 add Unlock Request notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::USER . ");";
            $DB->queryOrDie($query, "9.1 add Unlock Request notification target");
        }
    }
    $migration->addField("glpi_users", "lock_autolock_mode", "tinyint(1) NULL DEFAULT NULL");
    $migration->addField("glpi_users", "lock_directunlock_notification", "tinyint(1) NULL DEFAULT NULL");
    /************** Default Requester *************/
    Config::setConfigurationValues('core', array('set_default_requester' => 1));
    $migration->addField("glpi_users", "set_default_requester", "tinyint(1) NULL DEFAULT NULL");
    // ************ Networkport ethernets **************
    if (!TableExists("glpi_networkportfiberchannels")) {
        $query = "CREATE TABLE `glpi_networkportfiberchannels` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `items_devicenetworkcards_id` int(11) NOT NULL DEFAULT '0',\n                  `netpoints_id` int(11) NOT NULL DEFAULT '0',\n                  `wwn` varchar(16) COLLATE utf8_unicode_ci DEFAULT '',\n                  `speed` int(11) NOT NULL DEFAULT '10' COMMENT 'Mbit/s: 10, 100, 1000, 10000',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `card` (`items_devicenetworkcards_id`),\n                  KEY `netpoint` (`netpoints_id`),\n                  KEY `wwn` (`wwn`),\n                  KEY `speed` (`speed`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->query($query);
    }
    /************** Kernel version for os *************/
    $migration->addField("glpi_computers", "os_kernel_version", "string");
    /************** os architecture *************/
    $migration->addField("glpi_computers", "operatingsystemarchitectures_id", "integer");
    $migration->addKey("glpi_computers", "operatingsystemarchitectures_id");
    if (!TableExists('glpi_operatingsystemarchitectures')) {
        $query = "CREATE TABLE `glpi_operatingsystemarchitectures` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n        `comment` text COLLATE utf8_unicode_ci,\n        `date_mod` datetime DEFAULT NULL,\n        `date_creation` datetime DEFAULT NULL,\n        PRIMARY KEY (`id`),\n        KEY `name` (`name`),\n        KEY `date_mod` (`date_mod`),\n        KEY `date_creation` (`date_creation`)\n      ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "9.1 add table glpi_operatingsystemarchitectures");
    }
    /************** Task's templates *************/
    if (!TableExists('glpi_tasktemplates')) {
        $query = "CREATE TABLE `glpi_tasktemplates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `content` text COLLATE utf8_unicode_ci,\n                  `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `taskcategories_id` (`taskcategories_id`),\n                  KEY `entities_id` (`entities_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "9.1 add table glpi_tasktemplates");
    }
    /************** Installation date for softwares *************/
    $migration->addField("glpi_computers_softwareversions", "date_install", "DATE");
    $migration->addKey("glpi_computers_softwareversions", "date_install");
    /************** Location for budgets *************/
    $migration->addField("glpi_budgets", "locations_id", "integer");
    $migration->addKey("glpi_budgets", "locations_id");
    if (!TableExists('glpi_budgettypes')) {
        $query = "CREATE TABLE `glpi_budgettypes` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n        `comment` text COLLATE utf8_unicode_ci,\n        `date_mod` datetime DEFAULT NULL,\n        `date_creation` datetime DEFAULT NULL,\n        PRIMARY KEY (`id`),\n        KEY `name` (`name`),\n        KEY `date_mod` (`date_mod`),\n        KEY `date_creation` (`date_creation`)\n      ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "add table glpi_budgettypes");
    }
    $new = $migration->addField("glpi_budgets", "budgettypes_id", "integer");
    $migration->addKey("glpi_budgets", "budgettypes_id");
    if ($new) {
        $query = "UPDATE `glpi_displaypreferences`\n                SET `num`='6' WHERE `itemtype`='Budget' AND `num`='4'";
        $DB->queryOrDie($query, "change budget display preference");
    }
    /************** New Planning with fullcalendar.io *************/
    $migration->addField("glpi_users", "plannings", "text");
    /************** API Rest *************/
    Config::setConfigurationValues('core', array('enable_api' => 0));
    Config::setConfigurationValues('core', array('enable_api_login_credentials' => 0));
    Config::setConfigurationValues('core', array('enable_api_login_external_token' => 1));
    Config::setConfigurationValues('core', array('url_base_api' => trim($current_config['url_base'], "/") . "/apirest.php/"));
    if (!TableExists('glpi_apiclients')) {
        $query = "CREATE TABLE `glpi_apiclients` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` INT NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT(1) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  `is_active` TINYINT(1) NOT NULL DEFAULT '0',\n                  `ipv4_range_start` BIGINT NULL ,\n                  `ipv4_range_end` BIGINT NULL ,\n                  `ipv6` VARCHAR( 255 ) NULL,\n                  `app_token` VARCHAR( 255 ) NULL,\n                  `app_token_date` DATETIME DEFAULT NULL,\n                  `dolog_method` TINYINT NOT NULL DEFAULT '0',\n                  `comment` TEXT NULL ,\n                  PRIMARY KEY (`id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `is_active` (`is_active`)\n                  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "9.1 add table glpi_apiclients");
        $query = "INSERT INTO `glpi_apiclients`\n                VALUES (1, 0, 1, 'full access from localhost', NOW(), 1, INET_ATON('127.0.0.1'), INET_ATON('127.0.0.1'), '::1', '', NULL, 0, NULL);";
        $DB->queryOrDie($query, "9.1 insert first line into table glpi_apiclients");
    }
    /************** Date mod/creation for itemtypes *************/
    $migration->displayMessage(sprintf(__('date_mod and date_creation')));
    $types = array('AuthLDAP', 'Blacklist', 'BlacklistedMailContent', 'Budget', 'Calendar', 'CartridgeItemType', 'Change', 'ChangeTask', 'ComputerDisk', 'ComputerVirtualMachine', 'ConsumableItemType', 'Contact', 'ContactType', 'Contract', 'ContractType', 'Crontask', 'DeviceCaseType', 'DeviceMemoryType', 'Document', 'DocumentCategory', 'DocumentType', 'Domain', 'Entity', 'FQDN', 'Fieldblacklist', 'FieldUnicity', 'Filesystem', 'Group', 'Holiday', 'Infocom', 'InterfaceType', 'IPNetwork', 'ITILCategory', 'KnowbaseItemCategory', 'Location', 'Link', 'MailCollector', 'Manufacturer', 'Netpoint', 'Network', 'NetworkEquipmentFirmware', 'NetworkName', 'NetworkPort', 'Notification', 'NotificationTemplate', 'PhonePowerSupply', 'Problem', 'ProblemTask', 'Profile', 'Project', 'ProjectState', 'ProjectTaskType', 'ProjectType', 'Reminder', 'RequestType', 'RSSFeed', 'Rule', 'RuleRightParameter', 'SLA', 'SoftwareLicenseType', 'SoftwareVersion', 'SolutionTemplate', 'SolutionType', 'SsoVariable', 'State', 'Supplier', 'SupplierType', 'TaskCategory', 'TaskTemplate', 'Ticket', 'TicketFollowup', 'TicketTask', 'User', 'UserCategory', 'UserTitle', 'VirtualMachineState', 'VirtualMachineSystem', 'VirtualMachineType', 'Vlan', 'WifiNetwork');
    $types = array_merge($types, $CFG_GLPI["infocom_types"]);
    $types = array_merge($types, $CFG_GLPI["dictionnary_types"]);
    $types = array_merge($types, $CFG_GLPI["device_types"]);
    $types = array_merge($types, $CFG_GLPI['networkport_instantiations']);
    foreach ($types as $type) {
        $table = getTableForItemType($type);
        if (!FieldExists($table, 'date_mod')) {
            $migration->displayMessage(sprintf(__('Add date_mod to %s'), $table));
            //Add date_mod field if it doesn't exists
            $migration->addField($table, 'date_mod', 'datetime');
            $migration->addKey($table, 'date_mod');
            $migration->migrationOneTable($table);
        }
        if (!FieldExists($table, 'date_creation')) {
            $migration->displayMessage(sprintf(__('Add date_creation to %s'), $table));
            //Add date_creation field
            $migration->addField($table, 'date_creation', 'datetime');
            $migration->addKey($table, 'date_creation');
            $migration->migrationOneTable($table);
        }
    }
    /************** Enhance Associated items for ticket ***************/
    // TEMPLATE UPDATE
    $migration->dropKey('glpi_tickettemplatepredefinedfields', 'unicity');
    // Get associated item searchoption num
    if (!isset($CFG_GLPI["use_rich_text"])) {
        $CFG_GLPI["use_rich_text"] = false;
    }
    $searchOption = Search::getOptions('Ticket');
    $item_num = 0;
    $itemtype_num = 0;
    foreach ($searchOption as $num => $option) {
        if (is_array($option)) {
            if ($option['field'] == 'items_id') {
                $item_num = $num;
            } else {
                if ($option['field'] == 'itemtype') {
                    $itemtype_num = $num;
                }
            }
        }
    }
    foreach (array('glpi_tickettemplatepredefinedfields', 'glpi_tickettemplatehiddenfields', 'glpi_tickettemplatemandatoryfields') as $table) {
        $columns = array();
        switch ($table) {
            case 'glpi_tickettemplatepredefinedfields':
                $columns = array('num', 'value', 'tickettemplates_id');
                break;
            default:
                $columns = array('num', 'tickettemplates_id');
                break;
        }
        $query = "SELECT `" . implode('`,`', $columns) . "`\n                FROM `{$table}`\n                WHERE `num` = '{$item_num}'\n                      OR `num` = '{$itemtype_num}';";
        $items_to_update = array();
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    if ($data['num'] == $itemtype_num) {
                        $items_to_update[$data['tickettemplates_id']]['itemtype'] = isset($data['value']) ? $data['value'] : 0;
                    } else {
                        if ($data['num'] == $item_num) {
                            $items_to_update[$data['tickettemplates_id']]['items_id'] = isset($data['value']) ? $data['value'] : 0;
                        }
                    }
                }
            }
        }
        switch ($table) {
            case 'glpi_tickettemplatepredefinedfields':
                // Update predefined items
                foreach ($items_to_update as $templates_id => $type) {
                    if (isset($type['itemtype'])) {
                        if (isset($type['items_id'])) {
                            $DB->queryOrDie("UPDATE `{$table}`\n                                      SET `value` = '" . $type['itemtype'] . "_" . $type['items_id'] . "'\n                                      WHERE `num` = '" . $item_num . "'\n                                      AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : update predefined items");
                            $DB->queryOrDie("DELETE FROM `{$table}`\n                                      WHERE `num` = '" . $itemtype_num . "'\n                                            AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : delete {$table} itemtypes");
                        }
                    }
                }
                break;
            default:
                // Update mandatory and hidden items
                foreach ($items_to_update as $templates_id => $type) {
                    if (isset($type['itemtype'])) {
                        if (isset($type['items_id'])) {
                            $DB->queryOrDie("DELETE FROM `{$table}`\n                                      WHERE `num` = '" . $item_num . "'\n                                            AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : delete {$table} itemtypes");
                        }
                        $DB->queryOrDie("UPDATE `{$table}`\n                                   SET `num` = '" . $item_num . "'\n                                   WHERE `num` = '" . $itemtype_num . "'\n                                         AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : delete {$table} itemtypes");
                    }
                }
                break;
        }
    }
    /************** Add more fields to software licenses */
    $new = $migration->addField("glpi_softwarelicenses", "is_deleted", "bool");
    $migration->addField("glpi_softwarelicenses", "locations_id", "integer");
    $migration->addField("glpi_softwarelicenses", "users_id_tech", "integer");
    $migration->addField("glpi_softwarelicenses", "users_id", "integer");
    $migration->addField("glpi_softwarelicenses", "groups_id_tech", "integer");
    $migration->addField("glpi_softwarelicenses", "groups_id", "integer");
    $migration->addField("glpi_softwarelicenses", "is_helpdesk_visible", "bool");
    $migration->addField("glpi_softwarelicenses", "is_template", "bool");
    $migration->addField("glpi_softwarelicenses", "template_name", "string");
    $migration->addField("glpi_softwarelicenses", "states_id", "integer");
    $migration->addField("glpi_softwarelicenses", "manufacturers_id", "integer");
    $migration->addKey("glpi_softwarelicenses", "locations_id");
    $migration->addKey("glpi_softwarelicenses", "users_id_tech");
    $migration->addKey("glpi_softwarelicenses", "users_id");
    $migration->addKey("glpi_softwarelicenses", "groups_id_tech");
    $migration->addKey("glpi_softwarelicenses", "groups_id");
    $migration->addKey("glpi_softwarelicenses", "is_helpdesk_visible");
    $migration->addKey("glpi_softwarelicenses", "is_deleted");
    $migration->addKey("glpi_softwarelicenses", "is_template");
    $migration->addKey("glpi_softwarelicenses", "states_id");
    $migration->addKey("glpi_softwarelicenses", "manufacturers_id");
    $migration->addField("glpi_infocoms", "decommission_date", "datetime");
    $migration->addField("glpi_entities", "autofill_decommission_date", "string", array('value' => '-2'));
    $migration->addField("glpi_states", "is_visible_softwarelicense", "bool");
    $migration->addKey("glpi_states", "is_visible_softwarelicense");
    /************* Add is_recursive on assets ***/
    foreach (array('glpi_computers', 'glpi_monitors', 'glpi_phones', 'glpi_peripherals') as $table) {
        $migration->addField($table, "is_recursive", "bool");
        $migration->addKey($table, "is_recursive");
    }
    /************* Add antivirus table */
    if (!TableExists('glpi_computerantiviruses')) {
        $query = "CREATE TABLE `glpi_computerantiviruses` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `computers_id` int(11) NOT NULL DEFAULT '0',\n        `name` varchar(255) DEFAULT NULL,\n        `manufacturers_id` int(11) NOT NULL DEFAULT '0',\n        `antivirus_version` varchar(255) DEFAULT NULL,\n        `signature_version` varchar(255) DEFAULT NULL,\n        `is_active` tinyint(1) NOT NULL DEFAULT '0',\n        `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n        `is_uptodate` tinyint(1) NOT NULL DEFAULT '0',\n        `is_dynamic` tinyint(1) NOT NULL DEFAULT '0',\n        `date_expiration` datetime DEFAULT NULL,\n        `date_mod` datetime DEFAULT NULL,\n        `date_creation` datetime DEFAULT NULL,\n        PRIMARY KEY (`id`),\n        KEY `name` (`name`),\n        KEY `antivirus_version` (`antivirus_version`),\n        KEY `signature_version` (`signature_version`),\n        KEY `is_active` (`is_active`),\n        KEY `is_uptodate` (`is_uptodate`),\n        KEY `is_dynamic` (`is_dynamic`),\n        KEY `is_deleted` (`is_deleted`),\n        KEY `computers_id` (`computers_id`),\n        KEY `date_expiration` (`date_expiration`),\n        KEY `date_mod` (`date_mod`),\n        KEY `date_creation` (`date_creation`)\n      ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";
        $DB->queryOrDie($query, "Add antivirus table");
    }
    if ($new) {
        //new right for software license
        //copy the software right value to the new license right
        foreach ($DB->request("glpi_profilerights", "`name` = 'software'") as $profrights) {
            $query = "INSERT INTO `glpi_profilerights`\n                          (`id`, `profiles_id`, `name`, `rights`)\n                   VALUES (NULL, '" . $profrights['profiles_id'] . "', 'license',\n                           '" . $profrights['rights'] . "')";
            $DB->queryOrDie($query, "9.1 add right for softwarelicense");
        }
    }
    //new right for survey
    foreach ($DB->request("glpi_profilerights", "`name` = 'ticket'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                SET `rights` = `rights` | " . Ticket::SURVEY . "\n                WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticket'";
        $DB->queryOrDie($query, "9.1 update ticket with survey right");
    }
    //new field
    $migration->addField('glpi_authldaps', 'location_field', 'string', ['after' => 'email4_field']);
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    $ADDTODISPLAYPREF['SoftwareLicense'] = array(3, 10, 162, 5);
    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);
                }
            }
        }
    }
    /** ************ New SLA structure ************ */
    if (!TableExists('glpi_slts')) {
        $query = "CREATE TABLE `glpi_slts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `number_time` int(11) NOT NULL,\n                  `calendars_id` int(11) NOT NULL DEFAULT '0',\n                  `date_mod` datetime DEFAULT NULL,\n                  `definition_time` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `end_of_working_day` tinyint(1) NOT NULL DEFAULT '0',\n                  `date_creation` datetime DEFAULT NULL,\n                  `slas_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `calendars_id` (`calendars_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `date_creation` (`date_creation`),\n                  KEY `slas_id` (`slas_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.91 add table glpi_slts");
        // Sla migration
        $query = "SELECT *\n                FROM `glpi_slas`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_slts`\n                                (`id`, `name`,`entities_id`, `is_recursive`, `type`, `comment`,\n                                 `number_time`, `date_mod`, `definition_time`,\n                                 `end_of_working_day`, `date_creation`, `slas_id`)\n                         VALUES ('" . $data['id'] . "', '" . $data['name'] . "', '" . $data['entities_id'] . "',\n                                 '" . $data['is_recursive'] . "', '" . SLT::TTR . "',\n                                 '" . addslashes($data['comment']) . "', '" . $data['resolution_time'] . "',\n                                 '" . $data['date_mod'] . "',\n                                 '" . $data['definition_time'] . "', '" . $data['end_of_working_day'] . "',\n                                 '" . date('Y-m-d H:i:s') . "', '" . $data['id'] . "');";
                    $DB->queryOrDie($query, "SLA migration to SLT");
                }
            }
        }
        // Delete deprecated fields of SLA
        foreach (array('number_time', 'definition_time', 'end_of_working_day') as $field) {
            $migration->dropField('glpi_slas', $field);
        }
        // Slalevels changes
        $migration->changeField('glpi_slalevels', 'slas_id', 'slts_id', 'integer');
        $migration->dropKey('glpi_slalevels', 'slas_id');
        $migration->addKey('glpi_slalevels', 'slts_id');
        // Ticket changes
        $migration->changeField("glpi_tickets", "slas_id", "slts_ttr_id", "integer");
        $migration->dropKey('glpi_tickets', 'slas_id');
        $migration->dropKey('glpi_tickets', 'slts_ttr_id');
        $migration->addField("glpi_tickets", "slts_tto_id", "integer", array('after' => 'slts_ttr_id'));
        $migration->addField("glpi_tickets", "time_to_own", "datetime", array('after' => 'due_date'));
        $migration->addKey('glpi_tickets', 'slts_tto_id');
        $migration->addKey('glpi_tickets', 'time_to_own');
        // Unique key for slalevel_ticket
        $migration->addKey('glpi_slalevels_tickets', array('tickets_id', 'slalevels_id'), 'unicity', 'UNIQUE');
        // Sla rules criterias migration
        $DB->queryOrDie("UPDATE `glpi_rulecriterias`\n                       SET `criteria` = 'slts_ttr_id'\n                       WHERE `criteria` = 'slas_id'", "SLA rulecriterias migration");
        // Sla rules actions migration
        $DB->queryOrDie("UPDATE `glpi_ruleactions`\n                       SET `field` = 'slts_ttr_id'\n                       WHERE `field` = 'slas_id'", "SLA ruleactions migration");
    }
    // to delete in next version - fix change in update
    if (!FieldExists('glpi_slas', 'calendars_id')) {
        $migration->addField("glpi_slas", "calendars_id", "integer", array('after' => 'is_recursive'));
        $migration->addKey('glpi_slas', 'calendars_id');
    }
    if (FieldExists('glpi_slts', 'resolution_time') && !FieldExists('glpi_slts', 'number_time')) {
        $migration->changeField('glpi_slts', 'resolution_time', 'number_time', 'integer');
    }
    /************** High contrast CSS **************/
    Config::setConfigurationValues('core', array('highcontrast_css' => 0));
    $migration->addField("glpi_users", "highcontrast_css", "tinyint(1) DEFAULT 0");
    /************** SMTP option for self-signed certificates **************/
    Config::setConfigurationValues('core', array('smtp_check_certificate' => 1));
    // for group task
    $migration->addField("glpi_tickettasks", "groups_id_tech", "integer");
    $migration->addKey("glpi_tickettasks", "groups_id_tech");
    $migration->addField("glpi_changetasks", "groups_id_tech", "integer");
    $migration->addKey("glpi_changetasks", "groups_id_tech");
    $migration->addField("glpi_problemtasks", "groups_id_tech", "integer");
    $migration->addKey("glpi_problemtasks", "groups_id_tech");
    $migration->addField("glpi_groups", "is_task", "bool", array('value' => 1, 'after' => 'is_assign'));
    // for date_mod adding to tasks and to followups
    $migration->addField("glpi_tickettasks", "date_mod", "datetime");
    $migration->addKey("glpi_tickettasks", "date_mod");
    $migration->addField("glpi_problemtasks", "date_mod", "datetime");
    $migration->addKey("glpi_problemtasks", "date_mod");
    $migration->addField("glpi_changetasks", "date_mod", "datetime");
    $migration->addKey("glpi_changetasks", "date_mod");
    $migration->addField("glpi_ticketfollowups", "date_mod", "datetime");
    $migration->addKey("glpi_ticketfollowups", "date_mod");
    // for is_active adding to glpi_taskcategories
    $migration->addField("glpi_taskcategories", "is_active", "bool", array('value' => 1));
    $migration->addKey("glpi_taskcategories", "is_active");
    // for is_active, is_followup_default, is_ticketheader and is_ticketfollowup in glpi_requesttypes
    $migration->addField("glpi_requesttypes", "is_active", "bool", array('value' => 1));
    $migration->addKey("glpi_requesttypes", "is_active");
    $migration->addField("glpi_requesttypes", "is_ticketheader", "bool", array('value' => 1));
    $migration->addKey("glpi_requesttypes", "is_ticketheader");
    $migration->addField("glpi_requesttypes", "is_ticketfollowup", "bool", array('value' => 1));
    $migration->addKey("glpi_requesttypes", "is_ticketfollowup");
    $migration->addField("glpi_requesttypes", "is_followup_default", "bool", array('value' => 0));
    $migration->addKey("glpi_requesttypes", "is_followup_default");
    $migration->addField("glpi_requesttypes", "is_mailfollowup_default", "bool", array('value' => 0));
    $migration->addKey("glpi_requesttypes", "is_mailfollowup_default");
    /************** Fix autoclose_delay for root_entity in glpi_entities (from -1 to 0) **************/
    $query = "UPDATE `glpi_entities`\n             SET `autoclose_delay` = 0\n             WHERE `autoclose_delay` = '-1'\n               AND `id` = 0";
    $DB->queryOrDie($query, "glpi_entities root_entity change autoclose_delay value from -1 to 0");
    // ************ Keep it at the end **************
    $migration->executeMigration();
    return $updateresult;
}
Example #10
0
 /**
  * @depends testInitSessionCredentials
  */
 public function testProtectedConfigSettings($session_token)
 {
     $sensitiveSettings = array('proxy_passwd', 'smtp_passwd');
     // set a non empty value to the sessionts to check
     foreach ($sensitiveSettings as $name) {
         Config::setConfigurationValues('core', array($name => 'not_empty_password'));
         $value = Config::getConfigurationValues('core', array($name));
         $this->assertArrayHasKey($name, $value);
         $this->assertNotEmpty($value[$name]);
     }
     $where = "'" . implode("', '", $sensitiveSettings) . "'";
     $config = new config();
     $rows = $config->find("`context`='core' AND `name` IN ({$where})");
     $this->assertEquals(count($sensitiveSettings), count($rows));
     // Check the value is not retrieved for sensitive settings
     foreach ($rows as $row) {
         $res = $this->doHttpRequest('GET', "Config/" . $row['id'], ['headers' => ['Session-Token' => $session_token]]);
         $this->assertEquals(200, $res->getStatusCode());
         $body = $res->getBody();
         $data = json_decode($body, true);
         $this->assertEquals('', $data['value']);
     }
     // Check an other setting is disclosed (when not empty)
     $config = new Config();
     $config->getFromDBByQuery("WHERE `context`='core' AND `name`='admin_email'");
     $res = $this->doHttpRequest('GET', "Config/" . $config->getID(), ['headers' => ['Session-Token' => $session_token]]);
     $this->assertEquals(200, $res->getStatusCode());
     $body = $res->getBody();
     $data = json_decode($body, true);
     $this->assertNotEquals('', $data['value']);
     // Check a search does not disclose sensitive values
     $criteria = array();
     $queryString = "";
     foreach ($rows as $row) {
         $queryString = "&criteria[][link]=or&criteria[][field]=1&criteria[][searchtype]=equals&criteria[][value]=" . $row['name'];
     }
     $res = $this->doHttpRequest('GET', "search/Config" . "?{$queryString}", ['headers' => ['Session-Token' => $session_token], 'query' => array()]);
     $this->assertEquals(200, $res->getStatusCode());
     $body = $res->getBody();
     $data = json_decode($body, true);
     foreach ($data['data'] as $row) {
         foreach ($row as $col) {
             $this->assertNotEquals($col, 'not_empty_password');
         }
     }
 }
Example #11
0
function loadDataset()
{
    global $CFG_GLPI;
    // Unit test data definition
    $data = ['_version' => 3, 'Entity' => [['name' => '_test_root_entity', 'entities_id' => 0], ['name' => '_test_child_1', 'entities_id' => '_test_root_entity'], ['name' => '_test_child_2', 'entities_id' => '_test_root_entity']], 'Computer' => [['name' => '_test_pc01', 'entities_id' => '_test_root_entity', 'comment' => 'Comment for computer _test_pc01'], ['name' => '_test_pc02', 'entities_id' => '_test_root_entity', 'comment' => 'Comment for computer _test_pc02'], ['name' => '_test_pc11', 'entities_id' => '_test_child_1'], ['name' => '_test_pc12', 'entities_id' => '_test_child_1'], ['name' => '_test_pc21', 'entities_id' => '_test_child_2'], ['name' => '_test_pc22', 'entities_id' => '_test_child_2']], 'Software' => [['name' => '_test_soft', 'entities_id' => '_test_root_entity', 'is_recursive' => 1]], 'SoftwareVersion' => [['name' => '_test_softver_1', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft'], ['name' => '_test_softver_2', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft']], 'Printer' => [['name' => '_test_printer_all', 'entities_id' => '_test_root_entity', 'is_recursive' => 1], ['name' => '_test_printer_ent0', 'entities_id' => '_test_root_entity', 'is_recursive' => 0], ['name' => '_test_printer_ent1', 'entities_id' => '_test_child_1', 'is_recursive' => 0], ['name' => '_test_printer_ent2', 'entities_id' => '_test_child_2', 'is_recursive' => 0]], 'User' => [['name' => TU_USER, 'password' => TU_PASS, 'password2' => TU_PASS, 'entities_id' => '_test_root_entity', 'profiles_id' => 4, '_entities_id' => '_test_root_entity', '_profiles_id' => 4, '_is_recursive' => 1]], 'TaskCategory' => [['is_recursive' => 1, 'name' => '_cat_1', 'completename' => '_cat_1', 'comment' => 'Comment for category _cat_1', 'level' => 1], ['is_recursive' => 1, 'taskcategories_id' => '_cat_1', 'name' => '_subcat_1', 'completename' => '_cat_1 > _subcat_1', 'comment' => 'Comment for sub-category _subcat_1', 'level' => 2]], 'DropdownTranslation' => [['items_id' => '_cat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'name', 'value' => 'FR - _cat_1'], ['items_id' => '_cat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'comment', 'value' => 'FR - Commentaire pour cat├ęgorie _cat_1'], ['items_id' => '_subcat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'name', 'value' => 'FR - _subcat_1'], ['items_id' => '_subcat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'comment', 'value' => 'FR - Commentaire pour sous-cat├ęgorie _subcat_1']], 'Contact' => [['name' => '_contact01_name', 'firstname' => '_contact01_firstname', 'phone' => '0123456789', 'phone2' => '0123456788', 'mobile' => '0623456789', 'fax' => '0123456787', 'email' => '*****@*****.**', 'comment' => 'Comment for contact _contact01_name']], 'Supplier' => [['name' => '_suplier01_name', 'phonenumber' => '0123456789', 'fax' => '0123456787', 'email' => 'info@_supplier01_name.com', 'comment' => 'Comment for supplier _suplier01_name']], 'Location' => [['name' => '_location01', 'comment' => 'Comment for location _location01']], 'Netpoint' => [['name' => '_netpoint01', 'locations_id' => '_location01', 'comment' => 'Comment for netpoint _netpoint01']], 'BudgetType' => [['name' => '_budgettype01', 'comment' => 'Comment for budgettype _budgettype01']], 'Budget' => [['name' => '_budget01', 'comment' => 'Comment for budget _budget01', 'locations_id' => '_location01', 'budgettypes_id' => '_budgettype01', 'begin_date' => '2016-10-18', 'end_date' => '2016-12-31']], 'Ticket' => [['name' => '_ticket01', 'content' => 'Content for ticket _ticket01', 'users_id_recipient' => TU_USER]], 'TicketTask' => [['tickets_id' => '_ticket01', 'taskcategories_id' => '_subcat_1', 'users_id' => TU_USER, 'content' => 'Task to be done', 'is_private' => 0, 'users_id_tech' => TU_USER, 'date' => '2016-10-19 11:50:50']], 'UserEmail' => [['users_id' => TU_USER, 'is_default' => '1', 'is_dynamic' => '0', 'email' => TU_USER . '@glpi.com']]];
    // To bypass various right checks
    $_SESSION['glpishowallentities'] = 1;
    $_SESSION['glpicronuserrunning'] = "cron_phpunit";
    $_SESSION['glpi_use_mode'] = Session::NORMAL_MODE;
    $CFG_GLPI['root_doc'] = '/glpi';
    // need to set theses in DB, because tests for API use http call and this bootstrap file is not called
    Config::setConfigurationValues('core', ['url_base' => GLPI_URI, 'url_base_api' => GLPI_URI . '/apirest.php']);
    $CFG_GLPI['url_base'] = GLPI_URI;
    $CFG_GLPI['url_base_api'] = GLPI_URI . '/apirest.php';
    is_dir(GLPI_LOG_DIR) or mkdir(GLPI_LOG_DIR, 0755, true);
    $conf = Config::getConfigurationValues('phpunit');
    if (isset($conf['dataset']) && $conf['dataset'] == $data['_version']) {
        printf("\nGLPI dataset version %d already loaded\n\n", $data['_version']);
    } else {
        printf("\nLoading GLPI dataset version %d\n", $data['_version']);
        $ids = array();
        foreach ($data as $type => $inputs) {
            if ($type[0] == '_') {
                continue;
            }
            foreach ($inputs as $input) {
                // Resolve FK
                foreach ($input as $k => $v) {
                    // $foreigntype = $type; // by default same type than current type (is the case of the dropdowns)
                    $foreigntype = false;
                    $match = array();
                    if (isForeignKeyField($k) && (preg_match("/(.*s)_id\$/", $k, $match) || preg_match("/(.*s)_id_/", $k, $match))) {
                        $foreigntype = array_pop($match);
                        $foreigntype = getItemTypeForTable("glpi_{$foreigntype}");
                    }
                    if ($foreigntype && isset($ids[$foreigntype][$v]) && !is_numeric($v)) {
                        $input[$k] = $ids[$foreigntype][$v];
                    } else {
                        if ($k == 'items_id' && isset($input['itemtype']) && isset($ids[$input['itemtype']][$v]) && !is_numeric($v)) {
                            $input[$k] = $ids[$input['itemtype']][$v];
                        } else {
                            if ($foreigntype && $foreigntype != 'UNKNOWN' && !is_numeric($v)) {
                                // not found in ids array, then must get it from DB
                                if ($obj = getItemByTypeName($foreigntype, $v)) {
                                    $input[$k] = $obj->getID();
                                }
                            }
                        }
                    }
                }
                if (isset($input['name']) && ($item = getItemByTypeName($type, $input['name']))) {
                    $input['id'] = $ids[$type][$input['name']] = $item->getField('id');
                    $item->update($input);
                    echo ".";
                } else {
                    // Not found, create it
                    $item = getItemForItemtype($type);
                    $id = $item->add($input);
                    echo "+";
                    if (isset($input['name'])) {
                        $ids[$type][$input['name']] = $id;
                    }
                }
            }
        }
        echo "\nDone\n\n";
        Config::setConfigurationValues('phpunit', ['dataset' => $data['_version']]);
    }
}
 /**
  * Get configuration values
  *
  * @param array $options
  *
  * @return array
  */
 public static function getConfigValues($options)
 {
     $config = Config::getConfigurationValues(self::$configContext, $options);
     return $config + self::$defaultValues;
 }