コード例 #1
0
 function executeActions($output, $params)
 {
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "assign":
                     $output[$action->fields["field"]] = $action->fields["value"];
                     break;
                 case "regex_result":
                     //Regex result : assign value from the regex
                     $res = "";
                     if (isset($this->regex_results[0])) {
                         $res .= RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                     } else {
                         $res .= $action->fields["value"];
                     }
                     if ($res != '' && ($action->fields["field"] != 'user' && $action->fields["field"] != 'otherserial' && $action->fields["field"] != 'software' && $action->fields["field"] != 'softwareversion')) {
                         $res = Dropdown::importExternal(getItemTypeForTable(getTableNameForForeignKeyField($action->fields['field'])), $res);
                     }
                     $output[$action->fields["field"]] = $res;
                     break;
                 default:
                     //plugins actions
                     $executeaction = clone $this;
                     $ouput = $executeaction->executePluginsActions($action, $output, $params);
                     break;
             }
         }
     }
     return $output;
 }
コード例 #2
0
function plugin_racks_install()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/racks/inc/profile.class.php";
    $migration = new Migration("1.5.0");
    $update = false;
    if (!TableExists("glpi_plugin_rack_profiles") && !TableExists("glpi_plugin_racks_profiles")) {
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/empty-1.4.2.sql");
    } elseif (TableExists("glpi_plugin_rack_content") && !FieldExists("glpi_plugin_rack_content", "first_powersupply")) {
        $update = true;
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.0.2.sql");
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.1.0.sql");
    } elseif (!TableExists("glpi_plugin_racks_profiles")) {
        $update = true;
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.1.0.sql");
    }
    //from 1.1 version
    if (TableExists("glpi_plugin_racks_racks") && !FieldExists("glpi_plugin_racks_racks", "otherserial")) {
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.2.1.sql");
    }
    if (TableExists("glpi_plugin_racks_racks") && !FieldExists("glpi_plugin_racks_racks", "users_id_tech")) {
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.3.0.sql");
    }
    if (!TableExists("glpi_plugin_racks_racktypes")) {
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.3.2.sql");
    }
    if (TableExists("glpi_plugin_racks_racktypes") && !FieldExists("glpi_plugin_racks_racktypes", "is_recursive")) {
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.4.1.sql");
    }
    if (TableExists("glpi_plugin_racks_profiles") && !FieldExists("glpi_plugin_racks_profiles", "open_ticket")) {
        $DB->runFile(GLPI_ROOT . "/plugins/racks/sql/update-1.4.2.sql");
    }
    if ($update) {
        foreach ($DB->request('glpi_plugin_racks_profiles') as $data) {
            $query = "UPDATE `glpi_plugin_racks_profiles`\n                    SET `profiles_id` = '" . $data["id"] . "'\n                    WHERE `id` = '" . $data["id"] . "';";
            $result = $DB->query($query);
        }
        $migration->dropField('glpi_plugin_racks_profiles', 'name');
        Plugin::migrateItemType(array(4450 => 'PluginRacksRack', 4451 => 'PluginRacksOther'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array("glpi_plugin_racks_racks_items", "glpi_plugin_racks_itemspecifications"));
    }
    $notepad_tables = array('glpi_plugin_racks_racks');
    foreach ($notepad_tables as $t) {
        // Migrate data
        if (FieldExists($t, 'notepad')) {
            $query = "SELECT id, notepad\n                      FROM `{$t}`\n                      WHERE notepad IS NOT NULL\n                            AND notepad <>'';";
            foreach ($DB->request($query) as $data) {
                $iq = "INSERT INTO `glpi_notepads`\n                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\n                      VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\n                              '" . addslashes($data['notepad']) . "', NOW(), NOW())";
                $DB->queryOrDie($iq, "0.85 migrate notepad data");
            }
            $query = "ALTER TABLE `glpi_plugin_racks_racks` DROP COLUMN `notepad`;";
            $DB->query($query);
        }
    }
    //Migrate profiles to the system introduced in 0.85
    PluginRacksProfile::initProfile();
    PluginRacksProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
    //Drop old profile table : not used anymore
    $migration->dropTable('glpi_plugin_racks_profiles');
    return true;
}
コード例 #3
0
 function showForm($ID, $options = array())
 {
     global $DB, $CFG_GLPI;
     $obj = $options['obj'];
     //Html::printCleanArray($obj);
     $itemtype = getItemTypeForTable($obj->getTable());
     $list_ip = array();
     $total_ip = 0;
     if ($itemtype == 'NetworkEquipment') {
         $query = "SELECT `ip`\n                   FROM `glpi_networkequipments`\n                   WHERE `id` = '" . $obj->fields['id'] . "'";
         $res = $DB->query($query);
         while ($row = $DB->fetch_array($res)) {
             if ($row['ip'] != '') {
                 $list_ip[$row['ip']] = $row['ip'];
             }
         }
     }
     $tmp = array_values($list_ip);
     if (count($tmp) > 0 && $tmp[0] == '') {
         array_pop($list_ip);
     }
     $query = "SELECT `glpi_networknames`.`name`, `glpi_ipaddresses`.`name` as ip, `glpi_networkports`.`items_id`\n               FROM `glpi_networkports` \n               LEFT JOIN `" . $obj->getTable() . "` ON (`glpi_networkports`.`items_id` = `" . $obj->getTable() . "`.`id`\n                              AND `glpi_networkports`.`itemtype` = '" . $itemtype . "')\n               LEFT JOIN `glpi_networknames` ON (`glpi_networkports`.`id` =  `glpi_networknames`.`items_id`)\n               LEFT JOIN `glpi_ipaddresses` ON (`glpi_ipaddresses`.`items_id` = `glpi_networknames`.`id`)\n                WHERE `" . $obj->getTable() . "`.`id` = '" . $obj->fields['id'] . "'";
     $res = $DB->query($query);
     while ($row = $DB->fetch_array($res)) {
         if ($row['ip'] != '') {
             $port = $row['ip'];
             if ($row['name'] != '') {
                 $port = $row['name'] . " ({$port})";
             }
             $list_ip[$row['ip']] = $port;
         }
     }
     echo "<table class='tab_cadre_fixe'><tr class='tab_bg_2 left'>";
     echo "<tr><th colspan='4'>" . __('IP ping', 'addressing') . "</th></tr>";
     if (count($list_ip) > 0) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . __('IP') . " : </td>";
         echo "<td colspan='3'>";
         echo "<select id='ip'>";
         echo "<option>" . Dropdown::EMPTY_VALUE . "</option>";
         foreach ($list_ip as $ip => $name) {
             echo "<option value='{$ip}'>{$name}</option>";
         }
         echo "</select>";
         echo "&nbsp;<input class='submit' type='button' value='" . __s('Ping', 'addressing') . "' onclick='pingIp();'>";
         echo "</td>";
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . __('Result', 'addressing') . " : </td>";
         echo "<td colspan='3'>";
         echo "<div id='ping_response' class='plugin_addressing_ping_equipment'></div>";
         echo "</td></tr>";
     }
     echo "</table>";
     echo "\n         <script type='text/javascript'>\n            function pingIp() {\n               var ip = Ext.get('ip').dom.options[Ext.get('ip').dom.selectedIndex].value;\n               var ping_response = Ext.get('ping_response');\n\n               Ext.Ajax.request({\n                  url : '" . $CFG_GLPI["root_doc"] . "/plugins/addressing/ajax/ping.php' ,\n                  params : { ip : ip },\n                  method: 'POST',\n                  success: function ( result, request ) {\n                     ping_response.insertHtml('afterBegin', '<hr>'+result.responseText);\n                  }\n               });\n            }\n         </script>\n      ";
     if (count($list_ip) == 0) {
         echo __('No IP for this equipment', 'addressing');
     }
 }
コード例 #4
0
ファイル: hook.php プロジェクト: rambeau/genericobject
function plugin_genericobject_getDropdown()
{
    $dropdowns = array();
    $plugin = new Plugin();
    if ($plugin->isActivated("genericobject")) {
        foreach (getAllDatasFromTable(getTableForItemType('PluginGenericobjectType'), "`is_active`='1'") as $itemtype) {
            foreach (PluginGenericobjectType::getDropdownForItemtype($itemtype['itemtype']) as $table) {
                $dropdown_itemtype = getItemTypeForTable($table);
                $dropdowns[$dropdown_itemtype] = $dropdown_itemtype::getTypeName();
            }
        }
    }
    return $dropdowns;
}
コード例 #5
0
ファイル: hook.php プロジェクト: drTr0jan/genericobject
function plugin_genericobject_getDropdown()
{
    $dropdowns = array();
    $plugin = new Plugin();
    if ($plugin->isActivated("genericobject")) {
        foreach (PluginGenericobjectType::getTypes(true) as $idx => $type) {
            _log($idx, var_export($type, true));
            $itemtype = $type['itemtype'];
            foreach (PluginGenericobjectType::getDropdownForItemtype($itemtype) as $table) {
                $dropdown_itemtype = getItemTypeForTable($table);
                if (class_exists($dropdown_itemtype)) {
                    $dropdowns[$dropdown_itemtype] = $dropdown_itemtype::getTypeName();
                }
            }
        }
    }
    return $dropdowns;
}
コード例 #6
0
ファイル: comments.php プロジェクト: jose-martins/glpi
    // Security
    if (!TableExists($_POST['table'])) {
        exit;
    }
    switch ($_POST["table"]) {
        case "glpi_users":
            if ($_POST['value'] == 0) {
                $tmpname['link'] = $CFG_GLPI['root_doc'] . "/front/user.php";
                $tmpname['comment'] = "";
            } else {
                $tmpname = getUserName($_POST["value"], 2);
            }
            echo $tmpname["comment"];
            if (isset($_POST['withlink'])) {
                echo "<script type='text/javascript' >\n";
                echo Html::jsGetElementbyID($_POST['withlink']) . ".attr('href', '" . $tmpname['link'] . "');";
                echo "</script>\n";
            }
            break;
        default:
            if ($_POST["value"] > 0) {
                $tmpname = Dropdown::getDropdownName($_POST["table"], $_POST["value"], 1);
                echo $tmpname["comment"];
                if (isset($_POST['withlink'])) {
                    echo "<script type='text/javascript' >\n";
                    echo Html::jsGetElementbyID($_POST['withlink']) . ".\n                    attr('href', '" . Toolbox::getItemTypeFormURL(getItemTypeForTable($_POST["table"])) . "?id=" . $_POST["value"] . "');";
                    echo "</script>\n";
                }
            }
    }
}
$submitname = _sx('button', 'Post');
if (isset($_POST['submitname']) && $_POST['submitname']) {
    $submitname = stripslashes($_POST['submitname']);
}
if (isset($_POST["itemtype"]) && isset($_POST["id_field"]) && $_POST["id_field"]) {
    $search = Search::getOptions($_POST["itemtype"]);
    if (!isset($search[$_POST["id_field"]])) {
        exit;
    }
    $search = $search[$_POST["id_field"]];
    $FIELDNAME_PRINTED = false;
    $USE_TABLE = false;
    echo "<table class='tab_glpi' width='100%'><tr><td>";
    $plugdisplay = false;
    // Specific plugin Type case
    if (($plug = isPluginItemType($_POST["itemtype"])) || ($plug = isPluginItemType(getItemTypeForTable($search['table'])))) {
        $plugdisplay = Plugin::doOneHook($plug['plugin'], 'MassiveActionsFieldsDisplay', array('itemtype' => $_POST["itemtype"], 'options' => $search));
    }
    $fieldname = '';
    if (empty($search["linkfield"]) || $search['table'] == 'glpi_infocoms') {
        $fieldname = $search["field"];
    } else {
        $fieldname = $search["linkfield"];
    }
    if (!$plugdisplay) {
        $options = array();
        $values = array();
        // For ticket template or aditional options of massive actions
        if (isset($_POST['options'])) {
            $options = $_POST['options'];
        }
コード例 #8
0
ファイル: hook.php プロジェクト: AssAB/badges
function plugin_badges_install()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/badges/inc/profile.class.php";
    $install = false;
    $update78 = false;
    $update85 = false;
    $update201 = false;
    if (!TableExists("glpi_plugin_badges") && !TableExists("glpi_plugin_badges_badgetypes")) {
        $install = true;
        $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/empty-2.0.1.sql");
    } else {
        if (TableExists("glpi_plugin_badges_users") && !TableExists("glpi_plugin_badges_default")) {
            $update78 = true;
            $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.4.sql");
            $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.5.0.sql");
            plugin_badges_configure15();
            $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.5.1.sql");
            $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.6.0.sql");
        } else {
            if (TableExists("glpi_plugin_badges_profiles") && FieldExists("glpi_plugin_badges_profiles", "interface")) {
                $update78 = true;
                $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.5.0.sql");
                plugin_badges_configure15();
                $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.5.1.sql");
                $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.6.0.sql");
            } else {
                if (TableExists("glpi_plugin_badges") && !FieldExists("glpi_plugin_badges", "date_mod")) {
                    $update78 = true;
                    $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.5.1.sql");
                    $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.6.0.sql");
                } else {
                    if (!TableExists("glpi_plugin_badges_badgetypes")) {
                        $update78 = true;
                        $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-1.6.0.sql");
                    } else {
                        if (TableExists("glpi_plugin_badges_profiles")) {
                            $update85 = true;
                        }
                    }
                }
            }
        }
    }
    if (!TableExists("glpi_plugin_badges_requests")) {
        $update201 = true;
        $DB->runFile(GLPI_ROOT . "/plugins/badges/sql/update-2.0.1.sql");
    }
    if ($install || $update201) {
        // Badge request notification
        $query_id = "SELECT `id` FROM `glpi_notificationtemplates` WHERE `itemtype`='PluginBadgesBadge' AND `name` = 'Access Badges Request'";
        $result = $DB->query($query_id) or die($DB->error());
        $itemtype = $DB->result($result, 0, 'id');
        if (empty($itemtype)) {
            $query_id = "INSERT INTO `glpi_notificationtemplates`(`id`, `name`, `itemtype`, `date_mod`, `comment`, `css`) VALUES ('','Access Badges Request','PluginBadgesBadge', NOW(),'','');";
            $result = $DB->query($query_id) or die($DB->error());
            $query_id = "SELECT `id` FROM `glpi_notificationtemplates` WHERE `itemtype`='PluginBadgesBadge' AND `name` = 'Access Badges Request'";
            $result = $DB->query($query_id) or die($DB->error());
            $itemtype = $DB->result($result, 0, 'id');
        }
        $query = "INSERT INTO `glpi_notificationtemplatetranslations`\r\n                                 VALUES(NULL, '" . $itemtype . "', '','##badge.action## : ##badge.entity##',\r\n                        '##lang.badge.entity## :##badge.entity##\r\n                        ##FOREACHbadgerequest## \r\n                        ##lang.badgerequest.arrivaldate## : ##badgerequest.arrivaldate##\t\r\n                        ##lang.badgerequest.requester## : ##badgerequest.requester##\t\r\n                        ##lang.badgerequest.visitorfirstname## : ##badgerequest.visitorfirstname##\t\r\n                        ##lang.badgerequest.visitorrealname## : ##badgerequest.visitorrealname##\r\n                        ##lang.badgerequest.visitorsociety## : ##badgerequest.visitorsociety##\r\n                        ##ENDFOREACHbadgerequest##',\r\n                        '&lt;p&gt;##lang.badge.entity## :##badge.entity##&lt;br /&gt; &lt;br /&gt;\r\n                        ##FOREACHbadgerequest##&lt;br /&gt;\r\n                        ##lang.badgerequest.arrivaldate## : ##badgerequest.arrivaldate##&lt;br /&gt;\t\r\n                        ##lang.badgerequest.requester## : ##badgerequest.requester##&lt;br /&gt;\r\n                        ##lang.badgerequest.visitorfirstname## : ##badgerequest.visitorfirstname##&lt;br /&gt;\r\n                        ##lang.badgerequest.visitorrealname## : ##badgerequest.visitorrealname##&lt;br /&gt;\r\n                        ##lang.badgerequest.visitorsociety## : ##badgerequest.visitorsociety##&lt;br /&gt;\r\n                        ##ENDFOREACHbadgerequest##&lt;/p&gt;');";
        $result = $DB->query($query);
        $query = "INSERT INTO `glpi_notifications`\r\n                                   VALUES (NULL, 'Access badge request', 0, 'PluginBadgesBadge', 'AccessBadgeRequest',\r\n                                          'mail','" . $itemtype . "',\r\n                                          '', 1, 1, '" . date('Y-m-d H:i:s') . "');";
        $result = $DB->query($query);
    }
    // Badge expiration alert notification
    $query_id = "SELECT `id` FROM `glpi_notificationtemplates` WHERE `itemtype`='PluginBadgesBadge' AND `name` = 'Access Badges Return'";
    $result = $DB->query($query_id) or die($DB->error());
    $itemtype = $DB->result($result, 0, 'id');
    if (empty($itemtype)) {
        $query_id = "INSERT INTO `glpi_notificationtemplates`(`id`, `name`, `itemtype`, `date_mod`, `comment`, `css`) VALUES ('','Access Badges Return','PluginBadgesBadge', NOW(),'','');";
        $result = $DB->query($query_id) or die($DB->error());
        $query_id = "SELECT `id` FROM `glpi_notificationtemplates` WHERE `itemtype`='PluginBadgesBadge' AND `name` = 'Access Badges Return'";
        $result = $DB->query($query_id) or die($DB->error());
        $itemtype = $DB->result($result, 0, 'id');
    }
    $query = "INSERT INTO `glpi_notificationtemplatetranslations`\r\n                              VALUES(NULL, '" . $itemtype . "', '','##badge.action## : ##badge.entity##',\r\n                     '##lang.badge.entity## :##badge.entity##\r\n                     ##FOREACHbadgerequest## \r\n                     ##lang.badgerequest.arrivaldate## : ##badgerequest.arrivaldate##\t\r\n                     ##lang.badgerequest.requester## : ##badgerequest.requester##\t\r\n                     ##lang.badgerequest.visitorfirstname## : ##badgerequest.visitorfirstname##\t\r\n                     ##lang.badgerequest.visitorrealname## : ##badgerequest.visitorrealname##\r\n                     ##lang.badgerequest.visitorsociety## : ##badgerequest.visitorsociety##\r\n                     ##ENDFOREACHbadgerequest##',\r\n                     '&lt;p&gt;##lang.badge.entity## :##badge.entity##&lt;br /&gt; &lt;br /&gt;\r\n                     ##FOREACHbadgerequest##&lt;br /&gt;\r\n                     ##lang.badgerequest.arrivaldate## : ##badgerequest.arrivaldate##&lt;br /&gt;\t\r\n                     ##lang.badgerequest.requester## : ##badgerequest.requester##&lt;br /&gt;\r\n                     ##lang.badgerequest.visitorfirstname## : ##badgerequest.visitorfirstname##&lt;br /&gt;\r\n                     ##lang.badgerequest.visitorrealname## : ##badgerequest.visitorrealname##&lt;br /&gt;\r\n                     ##lang.badgerequest.visitorsociety## : ##badgerequest.visitorsociety##&lt;br /&gt;\r\n                     ##ENDFOREACHbadgerequest##&lt;/p&gt;');";
    $result = $DB->query($query);
    $query = "INSERT INTO `glpi_notifications`\r\n                                VALUES (NULL, 'Access badge return', 0, 'PluginBadgesBadge', 'BadgesReturn',\r\n                                       'mail','" . $itemtype . "',\r\n                                       '', 1, 1, '" . date('Y-m-d H:i:s') . "');";
    $result = $DB->query($query);
    if ($update78) {
        $query_ = "SELECT *\r\n            FROM `glpi_plugin_badges_profiles` ";
        $result_ = $DB->query($query_);
        if ($DB->numrows($result_) > 0) {
            while ($data = $DB->fetch_array($result_)) {
                $query = "UPDATE `glpi_plugin_badges_profiles`\r\n                  SET `profiles_id` = '" . $data["id"] . "'\r\n                  WHERE `id` = '" . $data["id"] . "';";
                $result = $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_plugin_badges_profiles`\r\n               DROP `name` ;";
        $result = $DB->query($query);
        Plugin::migrateItemType(array(1600 => 'PluginBadgesBadge'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_items_tickets"));
    }
    if ($update85) {
        $notepad_tables = array('glpi_plugin_badges_badges');
        foreach ($notepad_tables as $t) {
            // Migrate data
            if (FieldExists($t, 'notepad')) {
                $query = "SELECT id, notepad\r\n                      FROM `{$t}`\r\n                      WHERE notepad IS NOT NULL\r\n                            AND notepad <>'';";
                foreach ($DB->request($query) as $data) {
                    $iq = "INSERT INTO `glpi_notepads`\r\n                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\r\n                      VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\r\n                              '" . addslashes($data['notepad']) . "', NOW(), NOW())";
                    $DB->queryOrDie($iq, "0.85 migrate notepad data");
                }
                $query = "ALTER TABLE `glpi_plugin_badges_badges` DROP COLUMN `notepad`;";
                $DB->query($query);
            }
        }
    }
    CronTask::Register('PluginBadgesBadge', 'BadgesAlert', DAY_TIMESTAMP);
    CronTask::Register('PluginBadgesReturn', 'BadgesReturnAlert', DAY_TIMESTAMP);
    PluginBadgesProfile::initProfile();
    PluginBadgesProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
    $migration = new Migration("2.0.0");
    $migration->dropTable('glpi_plugin_badges_profiles');
    return true;
}
コード例 #9
0
 /**
  * Replay collection rules on an existing DB for model dropdowns
  *
  * @param $offset    offset used to begin (default 0)
  * @param $maxtime   maximum time of process (reload at the end) (default 0)
  *
  * @return -1 on completion else current offset
  **/
 function replayRulesOnExistingDBForModel($offset = 0, $maxtime = 0)
 {
     global $DB;
     if (isCommandLine()) {
         printf(__('Replay rules on existing database started on %s') . "\n", date("r"));
     }
     // Model check : need to check using manufacturer extra data
     if (strpos($this->item_table, 'models') === false) {
         _e('Error replaying rules');
         return false;
     }
     $model_table = getPlural(str_replace('models', '', $this->item_table));
     $model_field = getForeignKeyFieldForTable($this->item_table);
     // Need to give manufacturer from item table
     $Sql = "SELECT DISTINCT `glpi_manufacturers`.`id` AS idmanu,\n                     `glpi_manufacturers`.`name` AS manufacturer,\n                     `" . $this->item_table . "`.`id`,\n                     `" . $this->item_table . "`.`name` AS name,\n                     `" . $this->item_table . "`.`comment`\n              FROM `" . $this->item_table . "`,\n                   `{$model_table}`\n              LEFT JOIN `glpi_manufacturers`\n                  ON (`{$model_table}`.`manufacturers_id` = `glpi_manufacturers`.`id`)\n              WHERE `{$model_table}`.`{$model_field}` = `" . $this->item_table . "`.`id`";
     if ($offset) {
         $Sql .= " LIMIT " . intval($offset) . ",999999999";
     }
     $result = $DB->query($Sql);
     $nb = $DB->numrows($result) + $offset;
     $i = $offset;
     if ($result && $nb > $offset) {
         // Step to refresh progressbar
         $step = $nb > 20 ? floor($nb / 20) : 1;
         $tocheck = array();
         while ($data = $DB->fetch_assoc($result)) {
             if (!($i % $step)) {
                 if (isCommandLine()) {
                     printf(__('Replay rules on existing database: %1$s/%2$s') . "\r", $i, $nb);
                 } else {
                     Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
                 }
             }
             // Model case
             if (isset($data["manufacturer"])) {
                 $data["manufacturer"] = Manufacturer::processName(addslashes($data["manufacturer"]));
             }
             //Replay Type dictionnary
             $ID = Dropdown::importExternal(getItemTypeForTable($this->item_table), addslashes($data["name"]), -1, $data, addslashes($data["comment"]));
             if ($data['id'] != $ID) {
                 $tocheck[$data["id"]][] = $ID;
                 $sql = "UPDATE `{$model_table}`\n                                          SET `{$model_field}` = '{$ID}'\n                                          WHERE `{$model_field}` = '" . $data['id'] . "'";
                 if (empty($data['idmanu'])) {
                     $sql .= " AND (`manufacturers_id` IS NULL\n                                 OR `manufacturers_id` = '0')";
                 } else {
                     $sql .= " AND `manufacturers_id` = '" . $data['idmanu'] . "'";
                 }
                 $DB->query($sql);
             }
             $i++;
             if ($maxtime) {
                 $crt = explode(" ", microtime());
                 if ($crt[0] + $crt[1] > $maxtime) {
                     break;
                 }
             }
         }
         foreach ($tocheck as $ID => $tab) {
             $sql = "SELECT COUNT(*)\n                                 FROM `{$model_table}`\n                                 WHERE `{$model_field}` = '{$ID}'";
             $result = $DB->query($sql);
             $deletecartmodel = false;
             // No item left : delete old item
             if ($result && $DB->result($result, 0, 0) == 0) {
                 $Sql = "DELETE\n                                    FROM `" . $this->item_table . "`\n                                    WHERE `id` = '{$ID}'";
                 $resdel = $DB->query($Sql);
                 $deletecartmodel = true;
             }
             // Manage cartridge assoc Update items
             if ($this->getRuleClassName() == 'RuleDictionnaryPrinterModel') {
                 $sql = "SELECT *\n                       FROM `glpi_cartridgeitems_printermodels`\n                       WHERE `printermodels_id` = '{$ID}'";
                 if ($result = $DB->query($sql)) {
                     if ($DB->numrows($result)) {
                         // Get compatible cartridge type
                         $carttype = array();
                         while ($data = $DB->fetch_assoc($result)) {
                             $carttype[] = $data['cartridgeitems_id'];
                         }
                         // Delete cartrodges_assoc
                         if ($deletecartmodel) {
                             $sql = "DELETE\n                                FROM `glpi_cartridgeitems_printermodels`\n                                WHERE `printermodels_id` = 'id'";
                             $DB->query($sql);
                         }
                         // Add new assoc
                         $ct = new CartridgeItem();
                         foreach ($carttype as $cartID) {
                             foreach ($tab as $model) {
                                 $ct->addCompatibleType($cartID, $model);
                             }
                         }
                     }
                 }
             }
         }
         // each tocheck
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database ended on %s') . "\n", date("r"));
     } else {
         Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
     }
     return $i == $nb ? -1 : $i;
 }
コード例 #10
0
ファイル: object.class.php プロジェクト: geldarr/hack-space
 function transfer($new_entity)
 {
     global $DB;
     if ($this->fields['id'] > 0 && $this->fields['entities_id'] != $new_entity) {
         //Update entity for this object
         $tmp['id'] = $this->fields['id'];
         $tmp['entities_id'] = $new_entity;
         $this->update($tmp);
         $toupdate = array('id' => $this->fields['id']);
         foreach (PluginGenericobjectSingletonObjectField::getInstance(get_called_class()) as $field => $data) {
             $table = getTableNameForForeignKeyField($field);
             //It is a dropdown table !
             if ($field != 'entities_id' && $table != '' && isset($this->fields[$field]) && $this->fields[$field] > 0) {
                 //Instanciate a new dropdown object
                 $dropdown_itemtype = getItemTypeForTable($table);
                 $dropdown = new $dropdown_itemtype();
                 $dropdown->getFromDB($this->fields[$field]);
                 //If dropdown is only accessible in the other entity
                 //do not go further
                 if (!$dropdown->isEntityAssign() || in_array($new_entity, getAncestorsOf('glpi_entities', $dropdown->getEntityID()))) {
                     continue;
                 } else {
                     $tmp = array();
                     $where = "";
                     if ($dropdown instanceof CommonTreeDropdown) {
                         $tmp['completename'] = $dropdown->fields['completename'];
                         $where = "`completename`='" . addslashes_deep($tmp['completename']) . "'";
                     } else {
                         $tmp['name'] = $dropdown->fields['name'];
                         $where = "`name`='" . addslashes_deep($tmp['name']) . "'";
                     }
                     $tmp['entities_id'] = $new_entity;
                     $where .= " AND `entities_id`='" . $tmp['entities_id'] . "'";
                     //There's a dropdown value in the target entity
                     if ($found = $this->find($where)) {
                         $myfound = array_pop($found);
                         if ($myfound['id'] != $this->fields[$field]) {
                             $toupdate[$field] = $myfound['id'];
                         }
                     } else {
                         $clone = $dropdown->fields;
                         if ($dropdown instanceof CommonTreeDropdown) {
                             unset($clone['completename']);
                         }
                         unset($clone['id']);
                         $clone['entities_id'] = $new_entity;
                         $new_id = $dropdown->import($clone);
                         $toupdate[$field] = $new_id;
                     }
                 }
             }
         }
         $this->update($toupdate);
     }
     return true;
 }
コード例 #11
0
 /**
  * Print the network alias form
  *
  * @param $ID        integer ID of the item
  * @param $options   array
  *     - target for the Form
  *     - withtemplate template or basic computer
  *
  * @return Nothing (display)
  **/
 function showForm($ID, $options = array())
 {
     // Show only simple form to add / edit
     $showsimple = false;
     if (isset($options['parent'])) {
         $showsimple = true;
         $options['networknames_id'] = $options['parent']->getID();
     }
     $this->initForm($ID, $options);
     $recursiveItems = $this->recursivelyGetItems();
     if (count($recursiveItems) == 0) {
         return false;
     }
     $lastItem = $recursiveItems[count($recursiveItems) - 1];
     if (!$showsimple) {
         $this->showTabs();
     }
     $options['entities_id'] = $lastItem->getField('entities_id');
     $this->showFormHeader($options);
     echo "<tr class='tab_bg_1'><td>";
     $this->displayRecursiveItems($recursiveItems, 'Type');
     echo "&nbsp;:</td>\n<td>";
     if (!($ID > 0)) {
         echo "<input type='hidden' name='networknames_id' value='" . $this->fields["networknames_id"] . "'>\n";
     }
     $this->displayRecursiveItems($recursiveItems, isset($options['popup']) ? "Name" : "Link");
     echo "</td><td>" . __('Name') . "</td><td>\n";
     Html::autocompletionTextField($this, "name");
     echo "</td></tr>\n";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . FQDN::getTypeName() . "</td><td>";
     Dropdown::show(getItemTypeForTable(getTableNameForForeignKeyField("fqdns_id")), array('value' => $this->fields["fqdns_id"], 'name' => 'fqdns_id', 'entity' => $this->getEntityID(), 'displaywith' => array('view')));
     echo "</td>";
     echo "<td>" . __('Comments') . "</td>";
     echo "<td><textarea cols='45' rows='4' name='comment' >" . $this->fields["comment"];
     echo "</textarea></td>\n";
     echo "</tr>\n";
     $this->showFormButtons($options);
     if (!$showsimple) {
         $this->addDivForTabs();
     }
     return true;
 }
コード例 #12
0
ファイル: networkname.class.php プロジェクト: kipman/glpi
 /**
  * @param $networkPortID
  **/
 static function showFormForNetworkPort($networkPortID)
 {
     global $DB, $CFG_GLPI;
     $name = new self();
     $number_names = 0;
     if ($networkPortID > 0) {
         $query = "SELECT `id`\n                   FROM `" . $name->getTable() . "`\n                   WHERE `itemtype` = 'NetworkPort'\n                   AND `items_id` = '{$networkPortID}'\n                   AND `is_deleted` = '0'";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 1) {
             echo "<tr class='tab_bg_1'><th colspan='4'>" . __("Several network names available! Go to the tab 'Network Name' to manage them.") . "</th></tr>\n";
             return;
         }
         switch ($DB->numrows($result)) {
             case 1:
                 $nameID = $DB->fetch_assoc($result);
                 $name->getFromDB($nameID['id']);
                 break;
             case 0:
                 $name->getEmpty();
                 break;
         }
     } else {
         $name->getEmpty();
     }
     echo "<tr class='tab_bg_1'><th colspan='4'>";
     // If the networkname is defined, we must be able to edit it. So we make a link
     if ($name->getID() > 0) {
         echo "<a href='" . $name->getLinkURL() . "'>" . self::getTypeName(1) . "</a>";
         echo "<input type='hidden' name='NetworkName_id' value='" . $name->getID() . "'>&nbsp;\n";
         Html::showSimpleForm($name->getFormURL(), 'unaffect', _sx('button', 'Dissociate'), array('id' => $name->getID()), $CFG_GLPI["root_doc"] . '/pics/sub_dropdown.png');
     } else {
         echo self::getTypeName(1);
     }
     echo "</th>\n";
     echo "</tr><tr class='tab_bg_1'>";
     echo "<td>" . self::getTypeName(1) . "</td><td>\n";
     Html::autocompletionTextField($name, "name", array('name' => 'NetworkName_name'));
     echo "</td>\n";
     echo "<td>" . FQDN::getTypeName(1) . "</td><td>";
     Dropdown::show(getItemTypeForTable(getTableNameForForeignKeyField("fqdns_id")), array('value' => $name->fields["fqdns_id"], 'name' => 'NetworkName_fqdns_id', 'entity' => $name->getEntityID(), 'displaywith' => array('view')));
     echo "</td>\n";
     echo "</tr><tr class='tab_bg_1'>\n";
     echo "<td>" . IPAddress::getTypeName(Session::getPluralNumber());
     IPAddress::showAddChildButtonForItemForm($name, 'NetworkName__ipaddresses');
     echo "</td>";
     echo "<td>";
     IPAddress::showChildsForItemForm($name, 'NetworkName__ipaddresses');
     echo "</td>";
     // MoYo : really need to display it here ?
     // make confure because not updatable
     //       echo "<td>".IPNetwork::getTypeName(Session::getPluralNumber())."&nbsp;";
     //       Html::showToolTip(__('IP network is not included in the database. However, you can see current available networks.'));
     //       echo "</td><td>";
     //       IPNetwork::showIPNetworkProperties($name->getEntityID());
     //       echo "</td>\n";
     echo "<td colspan='2'>&nbsp;</td>";
     echo "</tr>\n";
 }
コード例 #13
0
 /**
  * Update devices with values get by SNMP
  *
  * @param $ID_Device : ID of device
  * @param $type : type of device (NETWORKING_TYPE, PRINTER_TYPE ...)
  * @param $oidsModel : oid list from model SNMP
  * @param $oidvalues : list of values from agent query
  * @param $Array_Object_TypeNameConstant : array with oid => constant in relation with fields to update
  *
  * @return $oidList : array with ports object name and oid
  *
  **/
 static function updateGLPIDevice($ID_Device, $type, $oidsModel, $oidvalues, $Array_Object_TypeNameConstant)
 {
     global $DB, $LANG, $CFG_GLPI, $FUSIONINVENTORY_MAPPING;
     if ($_SESSION['fusioninventory_logs'] == "1") {
         $logs = new PluginFusioninventoryLogs();
     }
     if ($_SESSION['fusioninventory_logs'] == "1") {
         $logs->write("fusioninventory_fullsync", ">>>>>>>>>> Update devices values <<<<<<<<<<", $type, $ID_Device, 1);
     }
     // Update 'last_fusioninventory_update' field
     $query = "UPDATE ";
     if ($type == NETWORKING_TYPE) {
         $query .= "`glpi_plugin_fusioninventory_networking`\n             SET `last_fusioninventory_update`='" . date("Y-m-d H:i:s") . "',\n                 `last_PID_update`='" . $_SESSION['FK_process'] . "'\n             WHERE `FK_networking`='" . $ID_Device . "';";
     }
     if ($type == PRINTER_TYPE) {
         $query .= "`glpi_plugin_fusioninventory_printers`\n             SET `last_fusioninventory_update`='" . date("Y-m-d H:i:s") . "'\n             WHERE `FK_printers`='" . $ID_Device . "';";
     }
     $DB->query($query);
     foreach ($Array_Object_TypeNameConstant as $oid => $link) {
         if (!preg_match("/\\.\$/", $oid)) {
             // SNMPGet ONLY
             if (isset($oidvalues[$oid][""])) {
                 if (isset($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown']) and !empty($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown'])) {
                     $oidvalues[$oid][""] = PluginFusioninventorySNMP::hex_to_string($oidvalues[$oid][""]);
                     if ($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown'] == "glpi_dropdown_model_networking") {
                         $oidvalues[$oid][""] = Dropdown::importExternal("NetworkEquipmentModel", $oidvalues[$oid][""], 0, array("manufacturer" => $oidvalues[$oid][""]));
                     } else {
                         $oidvalues[$oid][""] = Dropdown::importExternal(getItemTypeForTable($FUSIONINVENTORY_MAPPING[$type][$link]['dropdown']), $oidvalues[$oid][""], 0);
                     }
                 }
                 switch ($type) {
                     case NETWORKING_TYPE:
                         $Field = "FK_networking";
                         if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] == "glpi_networking") {
                             $Field = "ID";
                         }
                         break;
                     case PRINTER_TYPE:
                         $Field = "FK_printers";
                         if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] == "glpi_printers") {
                             $Field = "ID";
                         }
                         break;
                 }
                 if ($_SESSION['fusioninventory_logs'] == "1") {
                     $logs->write("fusioninventory_fullsync", $link . " = " . $oidvalues[$oid][""], $type, $ID_Device, 1);
                 }
                 // * Memory
                 if ($link == "ram" or $link == "memory") {
                     $oidvalues[$oid][""] = ceil($oidvalues[$oid][""] / 1024 / 1024);
                     if ($type == PRINTER_TYPE) {
                         $oidvalues[$oid][""] .= " MB";
                     }
                 }
                 if ($link == 'macaddr') {
                     $MacAddress = PluginFusioninventoryIfmac::ifmacwalk_ifmacaddress($oidvalues[$oid][""]);
                     $oidvalues[$oid][""] = $MacAddress;
                 }
                 // Convert hexa in string
                 $oidvalues[$oid][""] = PluginFusioninventorySNMP::hex_to_string($oidvalues[$oid][""]);
                 if (strstr($oidvalues[$oid][""], "noSuchName")) {
                     // NO Update field in GLPI
                 } else {
                     if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] == "glpi_plugin_fusioninventory_printers_cartridges") {
                         // * Printers cartridges
                         $object_name_clean = str_replace("MAX", "", $link);
                         $object_name_clean = str_replace("REMAIN", "", $object_name_clean);
                         if (strstr($link, "MAX")) {
                             $printer_cartridges_max_remain[$object_name_clean]["MAX"] = $oidvalues[$oid][""];
                         }
                         if (strstr($link, "REMAIN")) {
                             $printer_cartridges_max_remain[$object_name_clean]["REMAIN"] = $oidvalues[$oid][""];
                         }
                         if (isset($printer_cartridges_max_remain[$object_name_clean]["MAX"]) and isset($printer_cartridges_max_remain[$object_name_clean]["REMAIN"])) {
                             $pourcentage = ceil(100 * $printer_cartridges_max_remain[$object_name_clean]["REMAIN"] / $printer_cartridges_max_remain[$object_name_clean]["MAX"]);
                             // Test existance of row in MySQl
                             $query_sel = "SELECT *\n                                FROM " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                WHERE " . $Field . "='" . $ID_Device . "'\n                                      AND `object_name`='" . $object_name_clean . "';";
                             $result_sel = $DB->query($query_sel);
                             if ($DB->numrows($result_sel) == "0") {
                                 $queryInsert = "INSERT INTO " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                                 (" . $Field . ",object_name)\n                                     VALUES('" . $ID_Device . "', '" . $object_name_clean . "');";
                                 $DB->query($queryInsert);
                             }
                             $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $pourcentage . "'\n                                  WHERE " . $Field . "='" . $ID_Device . "'\n                                        AND `object_name`='" . $object_name_clean . "';";
                             $DB->query($queryUpdate);
                             unset($printer_cartridges_max_remain[$object_name_clean]["MAX"]);
                             unset($printer_cartridges_max_remain[$object_name_clean]["REMAIN"]);
                         } else {
                             // Test existance of row in MySQl
                             $query_sel = "SELECT *\n                                FROM " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                WHERE " . $Field . "='" . $ID_Device . "'\n                                      AND `object_name`='" . $link . "';";
                             $result_sel = $DB->query($query_sel);
                             if ($DB->numrows($result_sel) == "0") {
                                 $queryInsert = "INSERT INTO " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                                 (" . $Field . ",object_name)\n                                     VALUES('" . $ID_Device . "', '" . $link . "');";
                                 $DB->query($queryInsert);
                             }
                             $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $oidvalues[$oid][""] . "'\n                                  WHERE " . $Field . "='" . $ID_Device . "'\n                                        AND `object_name`='" . $link . "';";
                             $DB->query($queryUpdate);
                         }
                     } else {
                         if (strstr($link, "pagecounter")) {
                             // Detect if the script has wroten a line for the counter today
                             // (if yes, don't touch, else add line)
                             $today = strftime("%Y-%m-%d", time());
                             $query_line = "SELECT *\n                              FROM `glpi_plugin_fusioninventory_printers_history`\n                              WHERE `date` LIKE '" . $today . "%'\n                                    AND `FK_printers`='" . $ID_Device . "';";
                             $result_line = $DB->query($query_line);
                             if ($DB->numrows($result_line) == "0") {
                                 if (empty($oidvalues[$oid][""])) {
                                     $oidvalues[$oid][""] = 0;
                                 }
                                 $queryInsert = "INSERT INTO " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                              (" . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "," . $Field . ", `date`)\n                                  VALUES('" . $oidvalues[$oid][""] . "','" . $ID_Device . "', '" . $today . "');";
                                 $DB->query($queryInsert);
                             } else {
                                 $data_line = $DB->fetch_assoc($result_line);
                                 if ($data_line[$FUSIONINVENTORY_MAPPING[$type][$link]['field']] == "0") {
                                     if (empty($oidvalues[$oid][""])) {
                                         $oidvalues[$oid][""] = 0;
                                     }
                                     $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                     SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $oidvalues[$oid][""] . "'\n                                     WHERE " . $Field . "='" . $ID_Device . "'\n                                           AND `date` LIKE '" . $today . "%';";
                                     $DB->query($queryUpdate);
                                 }
                             }
                         } else {
                             if ($link == "cpuuser" or $link == "cpusystem") {
                                 if ($object_name == "cpuuser") {
                                     $cpu_values['cpuuser'] = $oidvalues[$oid][""];
                                 }
                                 if ($object_name == "cpusystem") {
                                     $cpu_values['cpusystem'] = $oidvalues[$oid][""];
                                 }
                                 if (isset($cpu_values['cpuuser']) and isset($cpu_values['cpusystem'])) {
                                     $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . ($cpu_values['cpuuser'] + $cpu_values['cpusystem']) . "'\n                                  WHERE " . $Field . "='" . $ID_Device . "';";
                                     $DB->query($queryUpdate);
                                     unset($cpu_values);
                                 }
                             } else {
                                 if ($FUSIONINVENTORY_MAPPING[$type][$link]['table'] != "") {
                                     if ($FUSIONINVENTORY_MAPPING[$type][$link]['field'] == "cpu" and empty($oidvalues[$oid][""])) {
                                         $SNMPValue = 0;
                                     }
                                     if (strstr($FUSIONINVENTORY_MAPPING[$type][$link]['table'], "glpi_plugin_fusioninventory")) {
                                         $queryUpdate = "UPDATE " . $FUSIONINVENTORY_MAPPING[$type][$link]['table'] . "\n                  SET " . $FUSIONINVENTORY_MAPPING[$type][$link]['field'] . "='" . $oidvalues[$oid][""] . "'\n                  WHERE " . $Field . "='" . $ID_Device . "'";
                                         $DB->query($queryUpdate);
                                     } else {
                                         $commonitem = new commonitem();
                                         $commonitem->setType($type, true);
                                         $tableau[$Field] = $ID_Device;
                                         $tableau[$FUSIONINVENTORY_MAPPING[$type][$link]['field']] = $oidvalues[$oid][""];
                                         $commonitem->obj->update($tableau);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
コード例 #14
0
ファイル: hook.php プロジェクト: euqip/glpi-smartcities
function plugin_certificates_install() {
   global $DB;
   
   include_once (GLPI_ROOT."/plugins/certificates/inc/profile.class.php");
   
   $install=false;
   $update78=false;
   $update80=false;
   
   if (!TableExists("glpi_plugin_certificates") && !TableExists("glpi_plugin_certificates_certificatetypes")) {
      
      $install=true;
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/empty-2.0.0.sql");

   } else if (TableExists("glpi_plugin_certificates_mailing") && !FieldExists("glpi_plugin_certificates","recursive")) {
      
      $update78=true;
      $update80=true;
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.4.sql");
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.5.0.sql");
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.5.1.sql");
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.6.0.sql");

   } else if (TableExists("glpi_plugin_certificates_profiles") && FieldExists("glpi_plugin_certificates_profiles","interface")) {
      
      $update78=true;
      $update80=true;
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.5.0.sql");
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.5.1.sql");
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.6.0.sql");

   } else if (TableExists("glpi_plugin_certificates") && !FieldExists("glpi_plugin_certificates","date_mod")) {
      
      $update78=true;
      $update80=true;
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.5.1.sql");
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.6.0.sql");

   } else if (!TableExists("glpi_plugin_certificates_certificatetypes")) {
      
      $update78=true;
      $update80=true;
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.6.0.sql");
      
   }
   //from 1.6 version
   if (TableExists("glpi_plugin_certificates_certificates") 
      && !FieldExists("glpi_plugin_certificates_certificates","users_id_tech")) {
      $DB->runFile(GLPI_ROOT ."/plugins/certificates/sql/update-1.8.0.sql");
   }
   
   if (TableExists("glpi_plugin_certificates_profiles")) {
   
      $notepad_tables = array('glpi_plugin_certificates_certificates');

      foreach ($notepad_tables as $t) {
         // Migrate data
         if (FieldExists($t, 'notepad')) {
            $query = "SELECT id, notepad
                      FROM `$t`
                      WHERE notepad IS NOT NULL
                            AND notepad <>'';";
            foreach ($DB->request($query) as $data) {
               $iq = "INSERT INTO `glpi_notepads`
                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)
                      VALUES ('".getItemTypeForTable($t)."', '".$data['id']."',
                              '".addslashes($data['notepad'])."', NOW(), NOW())";
               $DB->queryOrDie($iq, "0.85 migrate notepad data");
            }
            $query = "ALTER TABLE `glpi_plugin_certificates_certificates` DROP COLUMN `notepad`;";
            $DB->query($query);
         }
      }
   }
   
   if ($install || $update78) {

      //Do One time on 0.78
      $query_id = "SELECT `id` FROM `glpi_notificationtemplates` WHERE `itemtype`='PluginCertificatesCertificate' AND `name` = 'Alert Certificates'";
      $result = $DB->query($query_id) or die ($DB->error());
      $itemtype = $DB->result($result,0,'id');
      
      $query="INSERT INTO `glpi_notificationtemplatetranslations`
                                 VALUES(NULL, ".$itemtype.", '','##certificate.action## : ##certificate.entity##',
                        '##lang.certificate.entity## :##certificate.entity##
   ##FOREACHcertificates##
   ##lang.certificate.name## : ##certificate.name## - ##lang.certificate.dateexpiration## : ##certificate.dateexpiration##
   ##ENDFOREACHcertificates##',
                        '&lt;p&gt;##lang.certificate.entity## :##certificate.entity##&lt;br /&gt; &lt;br /&gt;
                        ##FOREACHcertificates##&lt;br /&gt;
                        ##lang.certificate.name##  : ##certificate.name## - ##lang.certificate.dateexpiration## :  ##certificate.dateexpiration##&lt;br /&gt; 
                        ##ENDFOREACHcertificates##&lt;/p&gt;');";
      $result=$DB->query($query);
      
      $query = "INSERT INTO `glpi_notifications`
                                   VALUES (NULL, 'Alert Expired Certificates', 0, 'PluginCertificatesCertificate', 'ExpiredCertificates',
                                          'mail',".$itemtype.",
                                          '', 1, 1, '2010-02-17 22:36:46');";
      
      $result=$DB->query($query);
      
      $query = "INSERT INTO `glpi_notifications`
                                   VALUES (NULL, 'Alert Certificates Which Expire', 0, 'PluginCertificatesCertificate', 'CertificatesWhichExpire',
                                          'mail',".$itemtype.",
                                          '', 1, 1, '2010-02-17 22:36:46');";
      
      $result=$DB->query($query);
   }
   
   if ($update78) {
      $query_="SELECT *
            FROM `glpi_plugin_certificates_profiles` ";
      $result_=$DB->query($query_);
      if ($DB->numrows($result_)>0) {

         while ($data=$DB->fetch_array($result_)) {
            $query="UPDATE `glpi_plugin_certificates_profiles`
                  SET `profiles_id` = '".$data["id"]."'
                  WHERE `id` = '".$data["id"]."';";
            $result=$DB->query($query);

         }
      }
      
      $query="ALTER TABLE `glpi_plugin_certificates_profiles`
               DROP `name` ;";
      $result=$DB->query($query);
   
      Plugin::migrateItemType(
         array(1700=>'PluginCertificatesCertificate'),
         array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences",
               "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"),
         array("glpi_plugin_certificates_certificates_items"));
      
      Plugin::migrateItemType(
         array(1200 => "PluginAppliancesAppliance",1300 => "PluginWebapplicationsWebapplication"),
         array("glpi_plugin_certificates_certificates_items"));
   }
   
   CronTask::Register('PluginCertificatesCertificate', 'CertificatesAlert', DAY_TIMESTAMP);

   PluginCertificatesProfile::initProfile();
   PluginCertificatesProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
   $migration = new Migration("2.0.0");
   $migration->dropTable('glpi_plugin_certificates_profiles');
   
   return true;
}
コード例 #15
0
ファイル: type.class.php プロジェクト: btry/genericobject
 /**
  *
  * Create or overwrite files for an itemtype
  * @since 2.2.0
  * @param $itemtype the itemtype to check
  * @param $name type's short name
  * @param $overwrite force to overwrite existing files
  * @return nothing
  */
 static function checkClassAndFilesForOneItemType($itemtype, $name, $overwrite = false, $overwrite_locales = true)
 {
     global $DB;
     $table = getTableForItemType($itemtype);
     //If class doesn't exist but table exists, create class
     if (TableExists($table) && ($overwrite || !class_exists($itemtype))) {
         self::addNewObject($name, $itemtype, array('add_table' => false, 'create_default_profile' => false, 'add_injection_file' => false, 'add_language_file' => false, 'overwrite_locales' => $overwrite_locales));
     }
     foreach ($DB->list_fields($table) as $field => $options) {
         if (preg_match("/s_id\$/", $field)) {
             $dropdowntable = getTableNameForForeignKeyField($field);
             $dropdownclass = getItemTypeForTable($dropdowntable);
             if (TableExists($dropdowntable) && !class_exists($dropdownclass)) {
                 $name = str_replace("glpi_plugin_genericobject_", "", $dropdowntable);
                 $name = getSingular($name);
                 $params = PluginGenericobjectField::getFieldOptions($field, $dropdownclass);
                 if (isset($params['dropdown_type']) and $params['dropdown_type'] === 'isolated') {
                     $params['linked_itemtype'] = $itemtype;
                 }
                 self::addNewDropdown($name, 'PluginGenericobject' . ucfirst($name), $params);
             }
         }
     }
 }
コード例 #16
0
 /**
  * List value for a dropdown, with search criterias
  * for an authenticated user
  *
  * @param $params    array of options (dropdown, id, parent, name)
  * @param $protocol        the commonication protocol used
  *
  * @return array of hashtable
  **/
 static function methodListDropdownValues($params, $protocol)
 {
     global $DB, $CFG_GLPI;
     if (isset($params['help'])) {
         return array('dropdown' => 'string,mandatory', 'id' => 'integer,optional', 'parent' => 'integer,optional', 'criteria' => 'string, optional', 'name' => 'string,optional', 'help' => 'bool,optional', 'start' => 'integer,optional', 'limit' => 'integer,optional');
     }
     if (!Session::getLoginUserID()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED);
     }
     if (!isset($params['dropdown'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER);
     }
     $resp = self::listSpecialDropdown($params['dropdown']);
     if (is_array($resp)) {
         return $resp;
     }
     if (class_exists($type = $params['dropdown'])) {
         $table = getTableForItemType($type);
     } else {
         if (TableExists($table = 'glpi_' . $params['dropdown'])) {
             $type = getItemTypeForTable($table);
         }
     }
     if (!($item = getItemForItemtype($type))) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', $params['dropdown']);
     }
     // Right check
     if (!$item instanceof CommonDropdown && !$item->canView()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
     }
     $start = 0;
     $limit = $_SESSION['glpilist_limit'];
     if (isset($params['limit']) && is_numeric($params['limit'])) {
         $limit = $params['limit'];
     }
     if (isset($params['start']) && is_numeric($params['start'])) {
         $start = $params['start'];
     }
     // Minimal visible fields
     $fields = array('name', 'completename', 'comment', 'entities_id', 'is_recursive', 'is_incident', 'is_request', 'is_uploadable', 'ext');
     $fields[] = getForeignKeyFieldForTable($table);
     $query = "SELECT `id`";
     foreach ($fields as $field) {
         if ($item->isField($field)) {
             $query .= ", `{$field}`";
         }
     }
     $query .= "\nFROM `{$table}`";
     if (isset($params['id']) && is_numeric($params['id'])) {
         $query .= " WHERE `id` = '" . $params['id'] . "'";
     } else {
         $query .= " WHERE 1";
     }
     if ($item->isEntityAssign()) {
         $query .= getEntitiesRestrictRequest(" AND ", $table, '', '', $item->maybeRecursive());
     }
     if (isset($params['parent']) && is_numeric($params['parent']) && $item instanceof CommonTreeDropdown) {
         $query .= " AND " . getForeignKeyFieldForTable($table) . "='" . $params['parent'] . "'";
     }
     if (isset($params['helpdesk']) && $params['helpdesk'] && $item->isField('is_helpdeskvisible')) {
         $query .= " AND `is_helpdeskvisible` ";
     }
     if (isset($params['criteria']) && $params['criteria'] && $item->isField('is_' . $params['criteria'])) {
         $query .= " AND `is_" . $params['criteria'] . "` ";
     }
     if (isset($params['name'])) {
         if ($item instanceof CommonTreeDropdown) {
             $query .= " AND `completename` LIKE '" . addslashes($params['name']) . "'";
         } else {
             $query .= " AND `name` LIKE '" . addslashes($params['name']) . "'";
         }
     }
     $query .= " LIMIT {$start},{$limit}";
     $resp = array();
     foreach ($DB->request($query) as $data) {
         $resp[] = $data;
     }
     return $resp;
 }
コード例 #17
0
 /**
  * @see CommonDropdown::displaySpecificTypeField()
  */
 function displaySpecificTypeField($ID, $field = array())
 {
     switch ($field['type']) {
         case "plugin_customfields_dropdowns_id":
             // We have a dropdown.
             if (isset($_REQUEST['plugin_customfields_dropdowns_id'])) {
                 $ID = $_REQUEST['plugin_customfields_dropdowns_id'];
             } elseif (isset($this->fields[$field['name']])) {
                 $ID = $this->fields[$field['name']];
             } else {
                 $ID = -1;
             }
             Dropdown::show(getItemTypeForTable(getTableNameForForeignKeyField($field['name'])), array('value' => $ID, 'name' => $field['name'], 'entity' => $this->getEntityID(), 'auto_submit' => true));
             break;
         case "plugin_customfields_dropdownsitems_id":
             // We have a dropdown item
             $condition = "plugin_customfields_dropdowns_id = -1";
             if (isset($_REQUEST['plugin_customfields_dropdowns_id'])) {
                 $condition = "plugin_customfields_dropdowns_id = '" . $_REQUEST['plugin_customfields_dropdowns_id'] . "'";
             }
             if ($field['name'] == 'entities_id') {
                 $restrict = -1;
             } else {
                 $restrict = $this->getEntityID();
             }
             Dropdown::show(getItemTypeForTable($this->getTable()), array('value' => $this->fields[$field['name']], 'name' => $field['name'], 'comments' => false, 'entity' => $restrict, 'used' => $ID > 0 ? getSonsOf($this->getTable(), $ID) : array(), 'condition' => $condition));
             break;
     }
 }
コード例 #18
0
ファイル: DbFunctionTest.php プロジェクト: glpi-project/glpi
 /**
  * @covers ::getItemTypeForTable
  * @dataProvider dataTableType
  **/
 public function testGetItemTypeForTable($table, $type, $classexists)
 {
     if ($classexists) {
         $this->assertEquals($type, getItemTypeForTable($table));
     } else {
         $this->assertEquals('UNKNOWN', getItemTypeForTable($table));
     }
 }
コード例 #19
0
ファイル: api.class.php プロジェクト: glpi-project/glpi
 /**
  * transform array of fields passed in parameter :
  * change value from  integer id to string name of foreign key
  * You can pass an array of array, this method is recursive.
  *
  * @param $fields     array    to check and transform
  * @param $expand     bool     array of option to enable, could be :
  *                                 - expand_dropdowns (default false)
  *                                 - get_hateoas      (default true)
  *
  * @return     array  altered $fields
  **/
 protected static function parseDropdowns($fields, $params = array())
 {
     // default params
     $default = array('expand_dropdowns' => false, 'get_hateoas' => true);
     $params = array_merge($default, $params);
     // parse fields recursively
     foreach ($fields as $key => &$value) {
         if (is_array($value)) {
             $value = self::parseDropdowns($value);
         }
         if (is_integer($key)) {
             continue;
         }
         if (isForeignKeyField($key)) {
             // specific key transformations
             if ($key == "items_id" && isset($fields['itemtype'])) {
                 $key = getForeignKeyFieldForItemType($fields['itemtype']);
             }
             if ($key == "auths_id" && isset($fields['authtype']) && $fields['authtype'] == Auth::LDAP) {
                 $key = "authldaps_id";
             }
             if ($key == "default_requesttypes_id") {
                 $key = "requesttypes_id";
             }
             if (!empty($value) || $key == 'entities_id' && $value >= 0) {
                 $tablename = getTableNameForForeignKeyField($key);
                 $itemtype = getItemTypeForTable($tablename);
                 // get hateoas
                 if ($params['get_hateoas']) {
                     $fields['links'][] = array('rel' => $itemtype, 'href' => self::$api_url . "/{$itemtype}/" . $value);
                 }
                 // expand dropdown
                 if ($params['expand_dropdowns']) {
                     $value = Dropdown::getDropdownName($tablename, $value);
                     // fix value for inexistent items
                     if ($value == "&nbsp;") {
                         $value = "";
                     }
                 }
             }
         }
     }
     return $fields;
 }
コード例 #20
0
ファイル: massiveaction.class.php プロジェクト: kipman/glpi
 /**
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     global $CFG_GLPI;
     $action = $ma->getAction();
     switch ($action) {
         case 'delete':
             foreach ($ids as $id) {
                 if ($item->can($id, DELETE)) {
                     if ($item->delete(array("id" => $id))) {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                     }
                 } else {
                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             break;
         case 'restore':
             foreach ($ids as $id) {
                 if ($item->can($id, PURGE)) {
                     if ($item->restore(array("id" => $id))) {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                     }
                 } else {
                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             break;
         case 'purge_item_but_devices':
         case 'purge_but_item_linked':
         case 'purge':
             foreach ($ids as $id) {
                 if ($item->can($id, PURGE)) {
                     $force = 1;
                     // Only mark deletion for
                     if ($item->maybeDeleted() && $item->useDeletedToLockIfDynamic() && $item->isDynamic()) {
                         $force = 0;
                     }
                     $delete_array = array('id' => $id);
                     if ($action == 'purge_item_but_devices') {
                         $delete_array['keep_devices'] = true;
                     }
                     if ($item instanceof CommonDropdown) {
                         if ($item->haveChildren()) {
                             if ($action != 'purge_but_item_linked') {
                                 $force = 0;
                                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                                 $ma->addMessage(__("You can't delete that item by massive actions, because it has sub-items"));
                                 $ma->addMessage(__("but you can do it by the form of the item"));
                                 continue;
                             }
                         }
                         if ($item->isUsed()) {
                             if ($action != 'purge_but_item_linked') {
                                 $force = 0;
                                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                                 $ma->addMessage(__("You can't delete that item, because it is used for one or more items"));
                                 $ma->addMessage(__("but you can do it by the form of the item"));
                                 continue;
                             }
                         }
                     }
                     if ($item->delete($delete_array, $force)) {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                     }
                 } else {
                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             break;
         case 'update':
             if (!isset($ma->POST['search_options']) || !isset($ma->POST['search_options'][$item->getType()])) {
                 return false;
             }
             $index = $ma->POST['search_options'][$item->getType()];
             $searchopt = Search::getCleanedOptions($item->getType(), UPDATE);
             $input = $ma->POST;
             if (isset($searchopt[$index])) {
                 /// Infocoms case
                 if (!isPluginItemType($item->getType()) && Search::isInfocomOption($item->getType(), $index)) {
                     $ic = new Infocom();
                     $link_entity_type = -1;
                     /// Specific entity item
                     if ($searchopt[$index]["table"] == "glpi_suppliers") {
                         $ent = new Supplier();
                         if ($ent->getFromDB($input[$input["field"]])) {
                             $link_entity_type = $ent->fields["entities_id"];
                         }
                     }
                     foreach ($ids as $key) {
                         if ($item->getFromDB($key)) {
                             if ($link_entity_type < 0 || $link_entity_type == $item->getEntityID() || $ent->fields["is_recursive"] && in_array($link_entity_type, getAncestorsOf("glpi_entities", $item->getEntityID()))) {
                                 $input2["items_id"] = $key;
                                 $input2["itemtype"] = $item->getType();
                                 if ($ic->can(-1, CREATE, $input2)) {
                                     // Add infocom if not exists
                                     if (!$ic->getFromDBforDevice($item->getType(), $key)) {
                                         $input2["items_id"] = $key;
                                         $input2["itemtype"] = $item->getType();
                                         unset($ic->fields);
                                         $ic->add($input2);
                                         $ic->getFromDBforDevice($item->getType(), $key);
                                     }
                                     $id = $ic->fields["id"];
                                     unset($ic->fields);
                                     if ($ic->update(array('id' => $id, $input["field"] => $input[$input["field"]]))) {
                                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                                     } else {
                                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                         $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                                     }
                                 } else {
                                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_NORIGHT);
                                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                                 }
                             } else {
                                 $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                 $ma->addMessage($item->getErrorMessage(ERROR_COMPAT));
                             }
                         } else {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                             $ma->addMessage($item->getErrorMessage(ERROR_NOT_FOUND));
                         }
                     }
                 } else {
                     /// Not infocoms
                     $link_entity_type = array();
                     /// Specific entity item
                     $itemtable = getTableForItemType($item->getType());
                     $itemtype2 = getItemTypeForTable($searchopt[$index]["table"]);
                     if ($item2 = getItemForItemtype($itemtype2)) {
                         if ($index != 80 && $searchopt[$index]["table"] != $itemtable && $item2->isEntityAssign() && $item->isEntityAssign()) {
                             if ($item2->getFromDB($input[$input["field"]])) {
                                 if (isset($item2->fields["entities_id"]) && $item2->fields["entities_id"] >= 0) {
                                     if (isset($item2->fields["is_recursive"]) && $item2->fields["is_recursive"]) {
                                         $link_entity_type = getSonsOf("glpi_entities", $item2->fields["entities_id"]);
                                     } else {
                                         $link_entity_type[] = $item2->fields["entities_id"];
                                     }
                                 }
                             }
                         }
                     }
                     foreach ($ids as $key) {
                         if ($item->canEdit($key) && $item->canMassiveAction($action, $input['field'], $input[$input["field"]])) {
                             if (count($link_entity_type) == 0 || in_array($item->fields["entities_id"], $link_entity_type)) {
                                 if ($item->update(array('id' => $key, $input["field"] => $input[$input["field"]]))) {
                                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                                 } else {
                                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                     $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                                 }
                             } else {
                                 $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                                 $ma->addMessage($item->getErrorMessage(ERROR_COMPAT));
                             }
                         } else {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_NORIGHT);
                             $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                         }
                     }
                 }
             }
             break;
         case 'add_transfer_list':
             $itemtype = $item->getType();
             if (!isset($_SESSION['glpitransfer_list'])) {
                 $_SESSION['glpitransfer_list'] = array();
             }
             if (!isset($_SESSION['glpitransfer_list'][$itemtype])) {
                 $_SESSION['glpitransfer_list'][$itemtype] = array();
             }
             foreach ($ids as $id) {
                 $_SESSION['glpitransfer_list'][$itemtype][$id] = $id;
                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
             }
             $ma->setRedirect($CFG_GLPI['root_doc'] . '/front/transfer.action.php');
             break;
     }
 }
コード例 #21
0
ファイル: type.class.php プロジェクト: geldarr/hack-space
 static function uninstall()
 {
     global $DB;
     //Delete references to PluginGenericobjectType in the following tables
     $tables = array("glpi_displaypreferences", "glpi_documents_items", "glpi_bookmarks", "glpi_logs");
     foreach ($tables as $table) {
         $itemtype = getItemTypeForTable($table);
         $item = new $itemtype();
         $item->deleteByCriteria(array('itemtype' => __CLASS__));
     }
     //Delete table
     $query = "DROP TABLE IF EXISTS `" . getTableForItemType(__CLASS__) . "`";
     $DB->query($query) or die($DB->error());
     //Dropd files and classes
     self::deleteItemTypeFilesAndClasses($name);
 }
コード例 #22
0
 static function getComputerInformations($ocs_fields = array(), $cfg_ocs, $entities_id, $locations_id = 0)
 {
     $input = array();
     $input["is_dynamic"] = 1;
     if ($cfg_ocs["states_id_default"] > 0) {
         $input["states_id"] = $cfg_ocs["states_id_default"];
     }
     $input["entities_id"] = $entities_id;
     if ($locations_id) {
         $input["locations_id"] = $locations_id;
     }
     $input['ocsid'] = $ocs_fields['ID'];
     foreach (self::getOcsFieldsMatching() as $glpi_field => $ocs_field) {
         if (isset($ocs_fields[$ocs_field])) {
             $table = getTableNameForForeignKeyField($glpi_field);
             $ocs_field = Toolbox::encodeInUtf8($ocs_field);
             //Field a a foreing key
             if ($table != '') {
                 $itemtype = getItemTypeForTable($table);
                 $item = new $itemtype();
                 $external_params = array();
                 foreach ($item->additional_fields_for_dictionnary as $field) {
                     if (isset($ocs_fields[$field])) {
                         $external_params[$field] = $ocs_fields[$field];
                     } else {
                         $external_params[$field] = "";
                     }
                 }
                 $input[$glpi_field] = Dropdown::importExternal($itemtype, $ocs_fields[$ocs_field], $entities_id, $external_params);
             } else {
                 switch ($glpi_field) {
                     default:
                         $input[$glpi_field] = $ocs_fields[$ocs_field];
                         break;
                     case 'contact':
                         if ($users_id = User::getIDByField('name', $ocs_fields[$ocs_field])) {
                             $input[$glpi_field] = $users_id;
                         }
                         break;
                     case 'comment':
                         $input[$glpi_field] = '';
                         if (!empty($ocs_fields["DESCRIPTION"]) && $ocs_fields["DESCRIPTION"] != NOT_AVAILABLE) {
                             $input[$glpi_field] .= $ocs_fields["DESCRIPTION"] . "\r\n";
                         }
                         $input[$glpi_field] .= addslashes(sprintf(__('%1$s %2$s'), $input[$glpi_field], sprintf(__('%1$s: %2$s'), __('Swap', 'ocsinventoryng'), $ocs_fields["SWAP"])));
                         break;
                 }
             }
         }
     }
     return $input;
 }
コード例 #23
0
ファイル: update_084_085.php プロジェクト: remicollet/glpi
/**
 * Update from 0.84 to 0.85
 *
 * @return bool for success (will die for most error)
**/
function update084to085()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    $DELFROMDISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.85'));
    $migration->setVersion('0.85');
    $backup_tables = false;
    $newtables = array('glpi_blacklistedmailcontents', 'glpi_changecosts', 'glpi_changes', 'glpi_changes_groups', 'glpi_changes_items', 'glpi_changes_problems', 'glpi_changes_projects', 'glpi_changes_suppliers', 'glpi_changes_tickets', 'glpi_changes_users', 'glpi_changetasks', 'glpi_changevalidations', 'glpi_dropdowntranslations', 'glpi_knowbaseitemtranslations', 'glpi_notepads', 'glpi_problemcosts', 'glpi_projectcosts', 'glpi_projects', 'glpi_projects_changes', 'glpi_projects_items', 'glpi_projectstates', 'glpi_projecttasks', 'glpi_projecttasks_tickets', 'glpi_projecttaskteams', 'glpi_projecttasktypes', 'glpi_projectteams', 'glpi_projecttypes', 'glpi_queuedmails');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'config table'));
    if (FieldExists('glpi_configs', 'version')) {
        if (!TableExists('origin_glpi_configs')) {
            $migration->copyTable('glpi_configs', 'origin_glpi_configs');
        }
        $query = "SELECT *\n                 FROM `glpi_configs`\n                 WHERE `id` = '1'";
        $result_of_configs = $DB->query($query);
        // Update glpi_configs
        $migration->addField('glpi_configs', 'context', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'core'"));
        $migration->addField('glpi_configs', 'name', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'version'"));
        $migration->addField('glpi_configs', 'value', 'text', array('update' => "'0.85'"));
        $migration->addKey('glpi_configs', array('context', 'name'), 'unicity', 'UNIQUE');
        $migration->migrationOneTable('glpi_configs');
        $fields = array();
        if ($DB->numrows($result_of_configs) == 1) {
            $configs = $DB->fetch_assoc($result_of_configs);
            unset($configs['id']);
            unset($configs['version']);
            // First drop fields not to have constraint on insert
            foreach ($configs as $name => $value) {
                $migration->dropField('glpi_configs', $name);
            }
            $migration->migrationOneTable('glpi_configs');
            // Then insert new values
            foreach ($configs as $name => $value) {
                $query = "INSERT INTO `glpi_configs`\n                             (`context`, `name`, `value`)\n                      VALUES ('core', '{$name}', '" . addslashes($value) . "');";
                $DB->query($query);
            }
        }
        $migration->dropField('glpi_configs', 'version');
        $migration->migrationOneTable('glpi_configs');
        $migration->dropTable('origin_glpi_configs');
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'profile table'));
    if (!TableExists('glpi_profilerights')) {
        if (!TableExists('origin_glpi_profiles')) {
            $migration->copyTable('glpi_profiles', 'origin_glpi_profiles');
        }
        $query = "CREATE TABLE `glpi_profilerights` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `rights` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`profiles_id`, `name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_profilerights");
        $query = "DESCRIBE `origin_glpi_profiles`";
        $rights = array();
        foreach ($DB->request($query) as $field) {
            if ($field['Type'] == 'char(1)') {
                $rights[$field['Field']] = $field['Field'];
                $migration->dropField('glpi_profiles', $field['Field']);
            }
        }
        $query = "SELECT *\n                FROM `origin_glpi_profiles`";
        foreach ($DB->request($query) as $profile) {
            $profiles_id = $profile['id'];
            foreach ($rights as $right) {
                $new_right = 0;
                if ($profile[$right] == 'r' || $profile[$right] == '1') {
                    $new_right = READ;
                } else {
                    if ($profile[$right] == 'w') {
                        $new_right = ALLSTANDARDRIGHT;
                    }
                }
                $query = "INSERT INTO `glpi_profilerights`\n                             (`profiles_id`, `name`, `rights`)\n                      VALUES ('{$profiles_id}', '{$right}', '" . $new_right . "')";
                $DB->query($query);
            }
        }
        $migration->migrationOneTable('glpi_profiles');
        $migration->dropTable('origin_glpi_profiles');
    }
    // New system of profiles
    // delete import_externalauth_users
    foreach ($DB->request("glpi_profilerights", "`name` = 'import_externalauth_users' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::IMPORTEXTAUTHUSERS . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with import_externalauth_users right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'import_externalauth_users'";
    $DB->queryOrDie($query, "0.85 delete import_externalauth_users right");
    // save value of rule_ticket to root_rule_ticket
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'root_rule_ticket'\n              WHERE `name` = 'rule_ticket'";
    $DB->queryOrDie($query, "0.85 rename rule_ticket to root_rule_ticket");
    // rename entity_rule_ticket to rule_ticket
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'rule_ticket'\n              WHERE `name` = 'entity_rule_ticket'";
    $DB->queryOrDie($query, "0.85 rename entity_rule_ticket to rule_ticket");
    // delete root_rule_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'root_rule_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` =  `rights` | " . RuleTicket::PARENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'rule_ticket'";
        $DB->queryOrDie($query, "0.85 update new rule_ticket with old rule_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'root_rule_ticket'";
    $DB->queryOrDie($query, "0.85 delete old rule_ticket right");
    // delete knowbase_admin
    foreach ($DB->request("glpi_profilerights", "`name` = 'knowbase_admin' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::KNOWBASEADMIN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with knowbase_admin right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'knowbase_admin'";
    $DB->queryOrDie($query, "0.85 delete knowbase_admin right");
    // delete faq
    foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::READFAQ . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with read faq right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::READFAQ . " | " . KnowbaseItem::PUBLISHFAQ . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with write faq right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'faq'";
    $DB->queryOrDie($query, "0.85 delete faq right");
    // delete user_authtype
    foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::READAUTHENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with read user_authtype right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::READAUTHENT . " | " . User::UPDATEAUTHENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with write user_authtype right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'user_authtype'";
    $DB->queryOrDie($query, "0.85 delete user_authtype right");
    // delete entity_helpdesk
    foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Entity::READHELPDESK . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'entity'";
        $DB->queryOrDie($query, "0.85 update entity with read entity_helpdesk right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Entity::READHELPDESK . " | " . Entity::UPDATEHELPDESK . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'entity'";
        $DB->queryOrDie($query, "0.85 update user with write entity_helpdesk right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'entity_helpdesk'";
    $DB->queryOrDie($query, "0.85 delete entity_helpdesk right");
    // delete reservation_helpdesk
    foreach ($DB->request("glpi_profilerights", "`name` = 'reservation_helpdesk' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . ReservationItem::RESERVEANITEM . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'reservation_central'";
        $DB->queryOrDie($query, "0.85 update reservation_central with reservation_helpdesk right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'reservation_helpdesk'";
    $DB->queryOrDie($query, "0.85 delete reservation_helpdesk right");
    // rename reservation_central
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'reservation'\n              WHERE `name` = 'reservation_central'";
    $DB->queryOrDie($query, "0.85 delete reservation_central");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'ticket'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'ticket'\n                 WHERE `name` = 'create_ticket'";
        $DB->queryOrDie($query, "0.85 rename create_ticket to ticket");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . (CREATE | Ticket::READMY) . "\n                 WHERE `name` = 'ticket'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update ticket with create_ticket right");
    }
    // delete update_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . UPDATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with update_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_ticket'";
    $DB->queryOrDie($query, "0.85 delete update_ticket right");
    // delete delete_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DELETE . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with delete_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_ticket'";
    $DB->queryOrDie($query, "0.85 delete delete_ticket right");
    // delete show_all_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_all_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_all_ticket right");
    // delete show_group_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READGROUP . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_group_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_group_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_group_ticket right");
    // delete show_assign_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_assign_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READASSIGN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_assign_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_assign_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_assign_ticket right");
    // delete assign_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'assign_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::ASSIGN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with assign_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'assign_ticket'";
    $DB->queryOrDie($query, "0.85 delete assign_ticket right");
    // delete steal_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'steal_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::STEAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with steal_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'steal_ticket'";
    $DB->queryOrDie($query, "0.85 delete steal_ticket right");
    // delete own_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'own_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::OWN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with own_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'own_ticket'";
    $DB->queryOrDie($query, "0.85 delete own_ticket right");
    // delete update_priority
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_priority' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::CHANGEPRIORITY . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with update_priority right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_priority'";
    $DB->queryOrDie($query, "0.85 delete update_priority right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'followup'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'followup'\n                 WHERE `name` = 'global_add_followups'";
        $DB->queryOrDie($query, "0.85 rename global_add_followups to followup");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . TicketFollowup::ADDALLTICKET . "\n                 WHERE `name` = 'followup'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update followup with global_add_followups right");
    }
    // delete add_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'add_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::ADDMYTICKET . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with add_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'add_followups'";
    $DB->queryOrDie($query, "0.85 delete add_followups right");
    // delete group_add_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'group_add_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::ADDGROUPTICKET . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with group_add_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'group_add_followups'";
    $DB->queryOrDie($query, "0.85 delete group_add_followups right");
    // delete observe_ticket for followup
    foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with observe_ticket right");
    }
    // don't delete observe_ticket because already use for task
    // delete show_full_ticket for followup
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . " | " . TicketFollowup::SEEPRIVATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with show_full_ticket right");
    }
    // don't delete show_full_ticket because already use for task
    // delete update_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with update_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_followups'";
    $DB->queryOrDie($query, "0.85 delete update_followups right");
    // delete update_own_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_own_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEMY . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with update_own_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_own_followups'";
    $DB->queryOrDie($query, "0.85 delete update_own_followups right");
    // delete delete_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with delete_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_followups'";
    $DB->queryOrDie($query, "0.85 delete delete_followups right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'task'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'task'\n                 WHERE `name` = 'global_add_tasks'";
        $DB->queryOrDie($query, "0.85 rename global_add_tasks to task");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . TicketTask::ADDALLTICKET . "\n                 WHERE `name` = 'task'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update followup with global_add_tasks right");
    }
    // delete update_tasks
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_tasks' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketTask::UPDATEALL . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with update_tasks right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_tasks'";
    $DB->queryOrDie($query, "0.85 delete update_tasks right");
    // delete observe_ticket for task
    foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with observe_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'observe_ticket'";
    $DB->queryOrDie($query, "0.85 delete observe_ticket right");
    // delete show_full_ticket for task
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . " | " . TicketTask::SEEPRIVATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with show_full_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_full_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_full_ticket right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'ticketvalidation'") == 0) {
        // rename delete_validations
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'ticketvalidation'\n                 WHERE `name` = 'delete_validations'";
        $DB->queryOrDie($query, "0.85 rename delete_validations to ticketvalidation");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . DELETE . "\n                 WHERE `name` = 'ticketvalidation'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with delete_validations right");
    }
    // delete create_request_validation
    foreach ($DB->request("glpi_profilerights", "`name` = 'create_request_validation' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::CREATEREQUEST . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with create_request_validation right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'create_request_validation'";
    $DB->queryOrDie($query, "0.85 delete create_request_validation right");
    // delete create_incident_validation
    foreach ($DB->request("glpi_profilerights", "`name` = 'create_incident_validation' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::CREATEINCIDENT . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with create_incident_validation right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'create_incident_validation'";
    $DB->queryOrDie($query, "0.85 delete create_incident_validation right");
    // delete validate_request
    foreach ($DB->request("glpi_profilerights", "`name` = 'validate_request' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::VALIDATEREQUEST . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_request right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'validate_request'";
    $DB->queryOrDie($query, "0.85 delete validate_request right");
    // delete validate_incident
    foreach ($DB->request("glpi_profilerights", "`name` = 'validate_incident' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::VALIDATEINCIDENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_incident right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'validate_incident'";
    $DB->queryOrDie($query, "0.85 delete validate_incident right");
    // must be done after ticket right
    // pour que la procédure soit ré-entrante
    if (countElementsInTable("glpi_profilerights", "`name` = 'change'") == 0) {
        ProfileRight::addProfileRights(array('change'));
        ProfileRight::updateProfileRightAsOtherRight('change', Change::READMY, "`name` = 'ticket'\n                                                     AND `rights` & " . Ticket::OWN);
        ProfileRight::updateProfileRightAsOtherRight('change', Change::READALL, "`name` = 'ticket'\n                                                     AND `rights` & " . Ticket::READALL);
        ProfileRight::updateProfileRightAsOtherRight('change', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE, "`name` = 'ticket' AND `rights` & " . UPDATE);
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'changevalidation'") == 0) {
        ProfileRight::addProfileRights(array('changevalidation'));
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', CREATE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . TicketValidation::CREATEINCIDENT . "\n                                                     AND `rights` & " . TicketValidation::CREATEREQUEST);
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', ChangeValidation::VALIDATE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . TicketValidation::VALIDATEINCIDENT . "\n                                                     AND `rights` & " . TicketValidation::VALIDATEREQUEST);
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', PURGE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . PURGE);
    }
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'planning'") == 0) {
        // rename show_planning
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'planning'\n                 WHERE `name` = 'show_planning'";
        $DB->queryOrDie($query, "0.85 rename show_planning to planning");
        // READMY = 1 => do update needed
    }
    // delete show_group_planning
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_planning' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Planning::READGROUP . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'planning'";
        $DB->queryOrDie($query, "0.85 update planning with show_group_planning right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_group_planning'";
    $DB->queryOrDie($query, "0.85 delete show_group_planning right");
    // delete show_all_planning
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_planning' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Planning::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'planning'";
        $DB->queryOrDie($query, "0.85 update planning with show_all_planning right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_planning'";
    $DB->queryOrDie($query, "0.85 delete show_all_planning right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'problem'") == 0) {
        // rename show_my_problem
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'problem'\n                 WHERE `name` = 'show_my_problem'";
        $DB->queryOrDie($query, "0.85 rename show_my_problem to problem");
        // READMY = 1 => do update needed
    }
    // delete show_all_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Problem::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with show_all_problem right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_problem'";
    $DB->queryOrDie($query, "0.85 delete show_all_problem right");
    // delete edit_all_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'edit_all_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . CREATE . " | " . UPDATE . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with edit_all_problem right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'edit_all_problem'";
    $DB->queryOrDie($query, "0.85 delete edit_all_problem right");
    // delete delete_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DELETE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with delete_problem");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_problem'";
    $DB->queryOrDie($query, "0.85 delete problem right");
    // update search_config
    foreach ($DB->request("glpi_profilerights", "`name` = 'search_config' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DisplayPreference::PERSONAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'search_config'";
        $DB->queryOrDie($query, "0.85 update search_config with search_config");
    }
    // delete search_config_global
    foreach ($DB->request("glpi_profilerights", "`name` = 'search_config_global' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DisplayPreference::GENERAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'search_config'";
        $DB->queryOrDie($query, "0.85 update search_config with search_config_global");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'search_config_global'";
    $DB->queryOrDie($query, "0.85 delete search_config_global right");
    // delete check_update
    foreach ($DB->request("glpi_profilerights", "`name` = 'check_update' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Backup::CHECKUPDATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'backup'";
        $DB->queryOrDie($query, "0.85 update backup with check_update");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'check_update'";
    $DB->queryOrDie($query, "0.85 delete check_update right");
    // entity_dropdown => right by object
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'domain'") == 0) {
        ProfileRight::addProfileRights(array('domain'));
        ProfileRight::updateProfileRightsAsOtherRights('domain', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'location'") == 0) {
        ProfileRight::addProfileRights(array('location'));
        ProfileRight::updateProfileRightsAsOtherRights('location', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'itilcategory'") == 0) {
        ProfileRight::addProfileRights(array('itilcategory'));
        ProfileRight::updateProfileRightsAsOtherRights('itilcategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'knowbasecategory'") == 0) {
        ProfileRight::addProfileRights(array('knowbasecategory'));
        ProfileRight::updateProfileRightsAsOtherRights('knowbasecategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'netpoint'") == 0) {
        ProfileRight::addProfileRights(array('netpoint'));
        ProfileRight::updateProfileRightsAsOtherRights('netpoint', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'taskcategory'") == 0) {
        ProfileRight::addProfileRights(array('taskcategory'));
        ProfileRight::updateProfileRightsAsOtherRights('taskcategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'state'") == 0) {
        ProfileRight::addProfileRights(array('state'));
        ProfileRight::updateProfileRightsAsOtherRights('state', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'solutiontemplate'") == 0) {
        ProfileRight::addProfileRights(array('solutiontemplate'));
        ProfileRight::updateProfileRightsAsOtherRights('solutiontemplate', 'entity_dropdown');
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'entity_dropdown'";
    $DB->queryOrDie($query, "0.85 delete entity_dropdown right");
    // delete notes
    $tables = array('budget', 'cartridge', 'change', 'computer', 'consumable', 'contact_enterprise', 'contract', 'document', 'entity', 'monitor', 'networking', 'peripheral', 'phone', 'printer', 'problem', 'software');
    foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '1'") as $profrights) {
        foreach ($tables as $table) {
            $query = "UPDATE `glpi_profilerights`\n                    SET `rights` = `rights` | " . READNOTE . "\n                    WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                          AND `name` = '{$table}'";
            $DB->queryOrDie($query, "0.85 update {$table} with read notes right");
        }
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        foreach ($tables as $table) {
            $query = "UPDATE `glpi_profilerights`\n                    SET `rights` = `rights` | " . READNOTE . " | " . UPDATENOTE . "\n                    WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                          AND `name` = '{$table}'";
            $DB->queryOrDie($query, "0.85 update {$table} with update notes right");
        }
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'notes'";
    $DB->queryOrDie($query, "0.85 delete notes right");
    $DELFROMDISPLAYPREF['Profile'] = array(29, 35, 37, 43, 53, 54, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 88, 93, 94, 95, 96, 97, 98, 99, 104, 113, 114, 116, 117, 121, 122, 123);
    $migration->displayMessage('Update for mailqueue');
    if (!TableExists('glpi_queuedmails')) {
        $query = "CREATE TABLE `glpi_queuedmails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `notificationtemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `sent_try` int(11) NOT NULL DEFAULT '0',\n                  `create_time` datetime DEFAULT NULL,\n                  `send_time` datetime DEFAULT NULL,\n                  `sent_time` datetime DEFAULT NULL,\n                  `name` TEXT DEFAULT NULL,\n                  `sender` TEXT DEFAULT NULL,\n                  `sendername` TEXT DEFAULT NULL,\n                  `recipient` TEXT DEFAULT NULL,\n                  `recipientname` TEXT DEFAULT NULL,\n                  `replyto` TEXT DEFAULT NULL,\n                  `replytoname` TEXT DEFAULT NULL,\n                  `headers` TEXT DEFAULT NULL,\n                  `body_html` LONGTEXT DEFAULT NULL,\n                  `body_text` LONGTEXT DEFAULT NULL,\n                  `messageid` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`itemtype`,`items_id`, `notificationtemplates_id`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `sent_try` (`sent_try`),\n                  KEY `create_time` (`create_time`),\n                  KEY `send_time` (`send_time`),\n                  KEY `sent_time` (`sent_time`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add glpi_queuedmails");
        $ADDTODISPLAYPREF['QueueMail'] = array(16, 7, 20, 21, 22, 15);
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmail'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('QueuedMail', 'queuedmail', 60, 50, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmailclean'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('QueuedMail', 'queuedmailclean', 86400, 30, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='temp'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'temp', 3600, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for clean temporary files");
    }
    if ($migration->addField("glpi_entities", "delay_send_emails", "integer", array('value' => -2))) {
        $migration->migrationOneTable('glpi_entities');
        // Set directly to root entity
        $query = 'UPDATE `glpi_entities`
                SET `delay_send_emails` = 0
                WHERE `id` = 0';
        $DB->queryOrDie($query, "0.85 default value for delay_send_emails for root entity");
    }
    // pour que la procédure soit ré-entrante
    if (countElementsInTable("glpi_profilerights", "`name` = 'queuedmail'") == 0) {
        ProfileRight::addProfileRights(array('queuedmail'));
        ProfileRight::updateProfileRightsAsOtherRights('queuedmail', 'notification');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Change'));
    // changes management
    if (!TableExists('glpi_changes')) {
        $query = "CREATE TABLE `glpi_changes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `status` int(11) NOT NULL DEFAULT '1',\n                  `content` longtext DEFAULT NULL,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  `date` DATETIME DEFAULT NULL,\n                  `solvedate` DATETIME DEFAULT NULL,\n                  `closedate` DATETIME DEFAULT NULL,\n                  `due_date` DATETIME DEFAULT NULL,\n                  `users_id_recipient` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `urgency` int(11) NOT NULL DEFAULT '1',\n                  `impact` int(11) NOT NULL DEFAULT '1',\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `itilcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `impactcontent` longtext DEFAULT NULL,\n                  `controlistcontent` longtext DEFAULT NULL,\n                  `rolloutplancontent` longtext DEFAULT NULL,\n                  `backoutplancontent` longtext DEFAULT NULL,\n                  `checklistcontent` longtext DEFAULT NULL,\n                  `global_validation` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'none',\n                  `validation_percent` int(11) NOT NULL DEFAULT '0',\n                  `solutiontypes_id` int(11) NOT NULL DEFAULT '0',\n                  `solution` text COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `begin_waiting_date` datetime DEFAULT NULL,\n                  `waiting_duration` int(11) NOT NULL DEFAULT '0',\n                  `close_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `solve_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `notepad` LONGTEXT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `date` (`date`),\n                  KEY `closedate` (`closedate`),\n                  KEY `status` (`status`),\n                  KEY `priority` (`priority`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `itilcategories_id` (`itilcategories_id`),\n                  KEY `users_id_recipient` (`users_id_recipient`),\n                  KEY `solvedate` (`solvedate`),\n                  KEY `solutiontypes_id` (`solutiontypes_id`),\n                  KEY `urgency` (`urgency`),\n                  KEY `impact` (`impact`),\n                  KEY `due_date` (`due_date`),\n                  KEY `global_validation` (`global_validation`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_changes");
    }
    $migration->addField('glpi_itilcategories', 'is_change', 'bool', array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_change');
    if (!TableExists('glpi_changes_users')) {
        $query = "CREATE TABLE `glpi_changes_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n                  `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`users_id`,`alternative_email`),\n                  KEY `user` (`users_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_users");
    }
    if (!TableExists('glpi_changes_groups')) {
        $query = "CREATE TABLE `glpi_changes_groups` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`groups_id`),\n                  KEY `group` (`groups_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_groups");
    }
    if (!TableExists('glpi_changes_suppliers')) {
        $query = "CREATE TABLE `glpi_changes_suppliers` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `suppliers_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_suppliers");
    }
    if (!TableExists('glpi_changes_items')) {
        $query = "CREATE TABLE `glpi_changes_items` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_items");
    }
    if (!TableExists('glpi_changes_tickets')) {
        $query = "CREATE TABLE `glpi_changes_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`tickets_id`),\n                  KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_tickets");
    }
    if (!TableExists('glpi_changes_problems')) {
        $query = "CREATE TABLE `glpi_changes_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`problems_id`),\n                  KEY `problems_id` (`problems_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_problems");
    }
    if (!TableExists('glpi_changetasks')) {
        $query = "CREATE TABLE `glpi_changetasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `state` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `begin` datetime DEFAULT NULL,\n                  `end` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_tech` int(11) NOT NULL DEFAULT '0',\n                  `content` longtext COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `changes_id` (`changes_id`),\n                  KEY `state` (`state`),\n                  KEY `users_id` (`users_id`),\n                  KEY `users_id_tech` (`users_id_tech`),\n                  KEY `date` (`date`),\n                  KEY `begin` (`begin`),\n                  KEY `end` (`end`),\n                  KEY `taskcategories_id` (taskcategories_id)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changetasks");
    }
    if (!TableExists('glpi_changecosts')) {
        $query = "CREATE TABLE `glpi_changecosts` (\n               `id` int(11) NOT NULL AUTO_INCREMENT,\n               `changes_id` int(11) NOT NULL DEFAULT '0',\n               `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n               `comment` text COLLATE utf8_unicode_ci,\n               `begin_date` date DEFAULT NULL,\n               `end_date` date DEFAULT NULL,\n               `actiontime` int(11) NOT NULL DEFAULT '0',\n               `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `budgets_id` int(11) NOT NULL DEFAULT '0',\n               `entities_id` int(11) NOT NULL DEFAULT '0',\n               `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n               PRIMARY KEY (`id`),\n               KEY `name` (`name`),\n               KEY `changes_id` (`changes_id`),\n               KEY `begin_date` (`begin_date`),\n               KEY `end_date` (`end_date`),\n               KEY `entities_id` (`entities_id`),\n               KEY `is_recursive` (`is_recursive`),\n               KEY `budgets_id` (`budgets_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_changecosts");
    }
    if (!TableExists('glpi_changevalidations')) {
        $query = "CREATE TABLE `glpi_changevalidations` (\n            `id` int(11) NOT NULL AUTO_INCREMENT,\n            `entities_id` int(11) NOT NULL DEFAULT '0',\n            `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n            `users_id` int(11) NOT NULL DEFAULT '0',\n            `changes_id` int(11) NOT NULL DEFAULT '0',\n            `users_id_validate` int(11) NOT NULL DEFAULT '0',\n            `comment_submission` text COLLATE utf8_unicode_ci,\n            `comment_validation` text COLLATE utf8_unicode_ci,\n            `status` int(11) NOT NULL DEFAULT '2',\n            `submission_date` datetime DEFAULT NULL,\n            `validation_date` datetime DEFAULT NULL,\n            PRIMARY KEY (`id`),\n            KEY `entities_id` (`entities_id`),\n            KEY `is_recursive` (`is_recursive`),\n            KEY `users_id` (`users_id`),\n            KEY `users_id_validate` (`users_id_validate`),\n            KEY `changes_id` (`changes_id`),\n            KEY `submission_date` (`submission_date`),\n            KEY `validation_date` (`validation_date`),\n            KEY `status` (`status`)\n            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_changevalidations");
    }
    // Change notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'Change'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Changes', 'Change', NOW())";
            $DB->queryOrDie($query, "0.85 add change notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##change.action## ##change.title##',\n                          '##IFchange.storestatus=5##\n ##lang.change.url## : ##change.urlapprove##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description## ##ENDIFchange.storestatus##\n ##ELSEchange.storestatus## ##lang.change.url## : ##change.url## ##ENDELSEchange.storestatus##\n\n ##lang.change.description##\n\n ##lang.change.title##  :##change.title##\n ##lang.change.authors##  :##IFchange.authors## ##change.authors## ##ENDIFchange.authors## ##ELSEchange.authors##--##ENDELSEchange.authors##\n ##lang.change.creationdate##  :##change.creationdate##\n ##IFchange.assigntousers## ##lang.change.assigntousers##  : ##change.assigntousers## ##ENDIFchange.assigntousers##\n ##lang.change.status##  : ##change.status##\n ##IFchange.assigntogroups## ##lang.change.assigntogroups##  : ##change.assigntogroups## ##ENDIFchange.assigntogroups##\n ##lang.change.urgency##  : ##change.urgency##\n ##lang.change.impact##  : ##change.impact##\n ##lang.change.priority## : ##change.priority##\n##IFchange.category## ##lang.change.category##  :##change.category## ##ENDIFchange.category## ##ELSEchange.category## ##lang.change.nocategoryassigned## ##ENDELSEchange.category##\n ##lang.change.content##  : ##change.content##\n\n##IFchange.storestatus=6##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description##\n##ENDIFchange.storestatus##\n ##lang.change.numberofproblems## : ##change.numberofproblems##\n\n##FOREACHproblems##\n [##problem.date##] ##lang.change.title## : ##problem.title##\n ##lang.change.content## ##problem.content##\n\n##ENDFOREACHproblems##\n ##lang.change.numberoftasks## : ##change.numberoftasks##\n\n##FOREACHtasks##\n [##task.date##]\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##\n',\n                          '&lt;p&gt;##IFchange.storestatus=5##&lt;/p&gt;\n&lt;div&gt;##lang.change.url## : &lt;a href=\"##change.urlapprove##\"&gt;##change.urlapprove##&lt;/a&gt;&lt;/div&gt;\n&lt;div&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.change.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solvedate##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.type##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.description## ##ENDIFchange.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEchange.storestatus## ##lang.change.url## : &lt;a href=\"##change.url##\"&gt;##change.url##&lt;/a&gt; ##ENDELSEchange.storestatus##&lt;/div&gt;\n&lt;p class=\"description b\"&gt;&lt;strong&gt;##lang.change.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.title##&lt;/span&gt;&#160;:##change.title## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.authors##&lt;/span&gt;&#160;:##IFchange.authors## ##change.authors## ##ENDIFchange.authors##    ##ELSEchange.authors##--##ENDELSEchange.authors## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.creationdate##&lt;/span&gt;&#160;:##change.creationdate## &lt;br /&gt; ##IFchange.assigntousers## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.assigntousers##&lt;/span&gt;&#160;: ##change.assigntousers## ##ENDIFchange.assigntousers##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.status## &lt;/span&gt;&#160;: ##change.status##&lt;br /&gt; ##IFchange.assigntogroups## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.assigntogroups##&lt;/span&gt;&#160;: ##change.assigntogroups## ##ENDIFchange.assigntogroups##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.urgency##&lt;/span&gt;&#160;: ##change.urgency##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.impact##&lt;/span&gt;&#160;: ##change.impact##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.priority##&lt;/span&gt; : ##change.priority## &lt;br /&gt;##IFchange.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.category## &lt;/span&gt;&#160;:##change.category##  ##ENDIFchange.category## ##ELSEchange.category##  ##lang.change.nocategoryassigned## ##ENDELSEchange.category##    &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.content##&lt;/span&gt;&#160;: ##change.content##&lt;/p&gt;\n&lt;p&gt;##IFchange.storestatus=6##&lt;br /&gt;&lt;span style=\"text-decoration: underline;\"&gt;&lt;strong&gt;&lt;span style=\"color: #888888;\"&gt;##lang.change.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solvedate##&lt;br /&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.change.solution.type##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.description##&lt;br /&gt;##ENDIFchange.storestatus##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.change.numberofproblems##&#160;: ##change.numberofproblems##&lt;/div&gt;\n&lt;p&gt;##FOREACHproblems##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt; [##problem.date##] &lt;em&gt;##lang.change.title## : &lt;a href=\"##problem.url##\"&gt;##problem.title## &lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; &lt;/span&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.content## &lt;/span&gt; ##problem.content##\n&lt;p&gt;##ENDFOREACHproblems##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.change.numberoftasks##&#160;: ##change.numberoftasks##&lt;/div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;&lt;strong&gt;[##task.date##] &lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.author##&lt;/span&gt; ##task.author##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.description##&lt;/span&gt; ##task.description##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.time##&lt;/span&gt; ##task.time##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.category##&lt;/span&gt; ##task.category##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add change notification translation");
            $notifications = array('new' => array(), 'update' => array(Notification::ASSIGN_TECH, Notification::OLD_TECH_IN_CHARGE), 'solved' => array(), 'add_task' => array(), 'update_task' => array(), 'delete_task' => array(), 'closed' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Change', 'update' => 'Update Change', 'solved' => 'Resolve Change', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Change', 'delete' => 'Delete Change');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::AUTHOR;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::OBSERVER;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Change', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add change {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add change {$type} notification target");
                }
            }
        }
    }
    $ADDTODISPLAYPREF['Change'] = array(12, 19, 15, 7, 18);
    $migration->addField('glpi_profiles', 'change_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    // Add problem costs
    if (!TableExists('glpi_problemcosts')) {
        $query = "CREATE TABLE `glpi_problemcosts` (\n               `id` int(11) NOT NULL AUTO_INCREMENT,\n               `problems_id` int(11) NOT NULL DEFAULT '0',\n               `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n               `comment` text COLLATE utf8_unicode_ci,\n               `begin_date` date DEFAULT NULL,\n               `end_date` date DEFAULT NULL,\n               `actiontime` int(11) NOT NULL DEFAULT '0',\n               `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `budgets_id` int(11) NOT NULL DEFAULT '0',\n               `entities_id` int(11) NOT NULL DEFAULT '0',\n               PRIMARY KEY (`id`),\n               KEY `name` (`name`),\n               KEY `problems_id` (`problems_id`),\n               KEY `begin_date` (`begin_date`),\n               KEY `end_date` (`end_date`),\n               KEY `entities_id` (`entities_id`),\n               KEY `budgets_id` (`budgets_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_problemcosts");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'drop rules cache'));
    $migration->dropTable('glpi_rulecachecomputermodels');
    $migration->dropTable('glpi_rulecachecomputertypes');
    $migration->dropTable('glpi_rulecachemanufacturers');
    $migration->dropTable('glpi_rulecachemonitormodels');
    $migration->dropTable('glpi_rulecachemonitortypes');
    $migration->dropTable('glpi_rulecachenetworkequipmentmodels');
    $migration->dropTable('glpi_rulecachenetworkequipmenttypes');
    $migration->dropTable('glpi_rulecacheoperatingsystems');
    $migration->dropTable('glpi_rulecacheoperatingsystemservicepacks');
    $migration->dropTable('glpi_rulecacheoperatingsystemversions');
    $migration->dropTable('glpi_rulecacheperipheralmodels');
    $migration->dropTable('glpi_rulecacheperipheraltypes');
    $migration->dropTable('glpi_rulecachephonemodels');
    $migration->dropTable('glpi_rulecachephonetypes');
    $migration->dropTable('glpi_rulecacheprintermodels');
    $migration->dropTable('glpi_rulecacheprinters');
    $migration->dropTable('glpi_rulecacheprintertypes');
    $migration->dropTable('glpi_rulecachesoftwares');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_rules'));
    $migration->addField("glpi_rules", 'uuid', "string");
    $migration->addField("glpi_slalevels", 'uuid', "string");
    $migration->migrationOneTable('glpi_rules');
    $migration->migrationOneTable('glpi_slalevels');
    // Dropdown translations
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_knowbaseitemtranslations'));
    Config::setConfigurationValues('core', array('translate_kb' => 0));
    if (!TableExists("glpi_knowbaseitemtranslations")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_knowbaseitemtranslations` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `name` text COLLATE utf8_unicode_ci,\n                  `answer` longtext COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`knowbaseitems_id`, `language`),\n                  FULLTEXT KEY `fulltext` (`name`,`answer`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_knowbaseitemtranslations");
    }
    // kb translations
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_dropdowntranslations'));
    Config::setConfigurationValues('core', array('translate_dropdowns' => 0));
    if (!TableExists("glpi_dropdowntranslations")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_dropdowntranslations` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `field` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `value` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`itemtype`,`items_id`,`language`,`field`),\n                  KEY `typeid` (`itemtype`,`items_id`),\n                  KEY `language` (`language`),\n                  KEY `field` (`field`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_dropdowntranslations");
    }
    //generate uuid for the basic rules of glpi
    // we use a complete sql where for cover all migration case (0.78 -> 0.85)
    $rules = array(array('sub_type' => 'RuleImportEntity', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleRight', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply X-Auto-Response-Suppress', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using X-Auto-Response-Suppress header'), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply Auto-Submitted', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using Auto-Submitted header'), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from item', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from user', 'match' => 'AND', 'description' => ''));
    $i = 0;
    foreach ($rules as $rule) {
        $query = "UPDATE `glpi_rules`\n                 SET `uuid` = 'STATIC-UUID-{$i}'\n                 WHERE `entities_id` = 0\n                       AND `is_recursive` = 0\n                       AND `sub_type` = '" . $rule['sub_type'] . "'\n                       AND `name` = '" . $rule['name'] . "'\n                       AND `description` = '" . $rule['description'] . "'\n                       AND `match` = '" . $rule['match'] . "'\n                 ORDER BY id ASC\n                 LIMIT 1";
        $DB->queryOrDie($query, "0.85 add uuid to basic rules (STATIC-UUID-{$i})");
        $i++;
    }
    //generate uuid for the rules of user
    foreach ($DB->request('glpi_rules', array('uuid' => NULL)) as $data) {
        $uuid = Rule::getUuid();
        $query = "UPDATE `glpi_rules`\n                SET `uuid` = '{$uuid}'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->queryOrDie($query, "0.85 add uuid to existing rules");
    }
    foreach ($DB->request('glpi_slalevels', array('uuid' => NULL)) as $data) {
        $uuid = Rule::getUuid();
        $query = "UPDATE `glpi_slalevels`\n                SET `uuid` = '{$uuid}'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->queryOrDie($query, "0.85 add uuid to existing slalevels");
    }
    $migration->addField('glpi_users', 'is_deleted_ldap', 'bool');
    $migration->addKey('glpi_users', 'is_deleted_ldap');
    Config::deleteConfigurationValues('core', array('use_ajax'));
    Config::deleteConfigurationValues('core', array('ajax_min_textsearch_load'));
    Config::deleteConfigurationValues('core', array('ajax_buffertime_load'));
    Config::deleteConfigurationValues('core', array('is_categorized_soft_expanded'));
    Config::deleteConfigurationValues('core', array('is_not_categorized_soft_expanded'));
    $migration->dropField("glpi_users", 'is_categorized_soft_expanded');
    $migration->dropField("glpi_users", 'is_not_categorized_soft_expanded');
    // Config::setConfigurationValues('core', array('use_unicodefont' => 0));
    // $migration->addField("glpi_users", 'use_unicodefont', "int(11) DEFAULT NULL");
    Config::deleteConfigurationValues('core', array('use_unicodefont'));
    $migration->dropField("glpi_users", 'use_unicodefont');
    Config::setConfigurationValues('core', array('pdffont' => 'helvetica'));
    $migration->addField("glpi_users", 'pdffont', "string");
    $migration->addField("glpi_users", 'picture', "string");
    $migration->addField("glpi_authldaps", 'picture_field', 'string');
    $migration->addField('glpi_links', 'open_window', 'bool', array('value' => 1));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_states'));
    foreach (array('is_visible_computer', 'is_visible_monitor', 'is_visible_networkequipment', 'is_visible_peripheral', 'is_visible_phone', 'is_visible_printer', 'is_visible_softwareversion') as $field) {
        $migration->addField('glpi_states', $field, 'bool', array('value' => '1'));
        $migration->addKey('glpi_states', $field);
    }
    // glpi_domains by entity
    $migration->addField('glpi_domains', 'entities_id', 'integer', array('after' => 'name'));
    $migration->addField('glpi_domains', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // glpi_states by entity
    $migration->addField('glpi_states', 'entities_id', 'integer', array('after' => 'name'));
    $migration->addField('glpi_states', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // add validity date for a user
    $migration->addField('glpi_users', 'begin_date', 'datetime');
    $migration->addField('glpi_users', 'end_date', 'datetime');
    // add validity date for a knowbaseitem
    $migration->addField('glpi_knowbaseitems', 'begin_date', 'datetime');
    $migration->addField('glpi_knowbaseitems', 'end_date', 'datetime');
    // Add validation percent for tickets
    $migration->addField('glpi_tickets', 'validation_percent', 'integer', array('value' => 0));
    // Add missing key
    $migration->addKey('glpi_tickettasks', 'state');
    $migration->addKey('glpi_tickettasks', 'users_id_tech');
    $migration->addKey('glpi_tickettasks', 'begin');
    $migration->addKey('glpi_tickettasks', 'end');
    // Create notification for reply to satisfaction survey based on satisfaction notif
    // Check if notifications already exists
    if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n                              AND `event` = 'replysatisfaction'") == 0) {
        // No notifications duplicate all
        $query = "SELECT *\n                FROM `glpi_notifications`\n                WHERE `itemtype` = 'Ticket'\n                      AND `event` = 'satisfaction'";
        foreach ($DB->request($query) as $notif) {
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                          `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                          `date_mod`)\n                   VALUES ('" . addslashes($notif['name']) . " Answer',\n                           '" . $notif['entities_id'] . "', 'Ticket',\n                           'replysatisfaction', '" . $notif['mode'] . "',\n                           '" . $notif['notificationtemplates_id'] . "',\n                           '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                           '" . $notif['is_active'] . "', NOW());";
            $DB->queryOrDie($query, "0.85 insert replysatisfaction notification");
            $newID = $DB->insert_id();
            $query2 = "SELECT *\n                    FROM `glpi_notificationtargets`\n                    WHERE `notifications_id` = '" . $notif['id'] . "'";
            // Add same recipent of satisfaction
            foreach ($DB->request($query2) as $target) {
                $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')";
                $DB->queryOrDie($query, "0.85 insert targets for replysatisfaction notification");
            }
            // Add Tech in charge
            $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . Notification::USER_TYPE . "', '" . Notification::ASSIGN_TECH . "')";
            $DB->queryOrDie($query, "0.85 insert tech in charge target for replysatisfaction notification");
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_slas'));
    // * Convert SLA resolution time to new system (ticket #4346)
    if (!FieldExists("glpi_slas", "definition_time")) {
        $migration->addField("glpi_slas", 'definition_time', "string");
        $migration->addField("glpi_slas", 'end_of_working_day', "bool");
        $migration->migrationOneTable('glpi_slas');
        // Minutes
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` <= '3000'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'minute',\n                            `resolution_time` = `resolution_time`/60\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
        // Hours
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` > '3000'\n                      AND `resolution_time` <= '82800'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'hour',\n                            `resolution_time` = `resolution_time`/3600\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
        // Days
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` > '82800'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'day',\n                            `resolution_time` = `resolution_time`/86400\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
    }
    Config::setConfigurationValues('core', array('keep_devices_when_purging_item' => 0));
    $migration->addField("glpi_users", "keep_devices_when_purging_item", "int(11) DEFAULT NULL");
    Config::setConfigurationValues('core', array('maintenance_mode' => 0));
    Config::setConfigurationValues('core', array('maintenance_text' => ''));
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'MailCollector'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Receiver errors', 'MailCollector', NOW())";
            $DB->queryOrDie($query, "0.85 add mail collector notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##mailcollector.action##',\n                           '##FOREACHmailcollectors##\n##lang.mailcollector.name## : ##mailcollector.name##\n##lang.mailcollector.errors## : ##mailcollector.errors##\n##mailcollector.url##\n##ENDFOREACHmailcollectors##',\n'&lt;p&gt;##FOREACHmailcollectors##&lt;br /&gt;##lang.mailcollector.name## : ##mailcollector.name##&lt;br /&gt; ##lang.mailcollector.errors## : ##mailcollector.errors##&lt;br /&gt;&lt;a href=\"##mailcollector.url##\"&gt;##mailcollector.url##&lt;/a&gt;&lt;br /&gt; ##ENDFOREACHmailcollectors##&lt;/p&gt;\n&lt;p&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.85 add mail collector notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                           `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                           `date_mod`)\n                   VALUES ('Receiver errors', 0, 'MailCollector', 'error', 'mail',\n                             {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "0.85 add mail collector notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                   VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::GLOBAL_ADMINISTRATOR . ");";
            $DB->queryOrDie($query, "0.85 add mail collector notification target");
        }
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='MailCollector' AND `name`='mailgateerror'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('MailCollector', 'mailgateerror', " . DAY_TIMESTAMP . ", NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for mailgateerror");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='circularlogs'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'circularlogs', " . DAY_TIMESTAMP . ", 4, " . CronTask::STATE_DISABLE . ", 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for circularlogs");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_documents'));
    $migration->addField('glpi_documents', 'is_blacklisted', 'bool');
    if (!TableExists("glpi_blacklistedmailcontents")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_blacklistedmailcontents` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `content` text COLLATE utf8_unicode_ci,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_blacklistedmailcontents");
    }
    $migration->addField('glpi_documents', 'tag', 'string');
    $migration->addField('glpi_queuedmails', 'documents', 'text');
    $migration->addKey('glpi_documents', 'tag');
    Config::setConfigurationValues('core', array('use_rich_text' => 0));
    Config::setConfigurationValues('core', array('attach_ticket_documents_to_mail' => 0));
    $migration->migrationOneTable('glpi_documents');
    $query = "UPDATE `glpi_documents`\n             SET `tag` = `id`";
    $DB->queryOrDie($query, "0.85 set tag to all documents");
    // increase password length
    $migration->changeField('glpi_users', 'password', 'password', 'string');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_softwarecategories'));
    // Hierarchical software category
    $migration->addField('glpi_softwarecategories', 'softwarecategories_id', 'integer');
    $migration->addField("glpi_softwarecategories", 'completename', "text");
    $migration->addField("glpi_softwarecategories", 'level', "integer");
    $migration->addField("glpi_softwarecategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_softwarecategories", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_softwarecategories');
    $migration->addKey('glpi_softwarecategories', 'softwarecategories_id');
    regenerateTreeCompleteName("glpi_softwarecategories");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various'));
    // glpi_cartridgeitems  glpi_consumableitems by entity
    $migration->addField('glpi_consumableitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    $migration->addField('glpi_cartridgeitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // Fix events
    $query = "UPDATE `glpi_events`\n             SET `type` = 'consumableitems'\n             WHERE `type` = 'consumables'";
    $DB->queryOrDie($query, "0.85 fix events for consumables");
    $query = "UPDATE `glpi_events`\n             SET `type` = 'cartridgeitems'\n             WHERE `type` = 'cartridges';";
    $DB->queryOrDie($query, "0.85 fix events for cartridges");
    // Bookmark order :
    $migration->addField('glpi_users', 'privatebookmarkorder', 'longtext');
    // Pref to comme back ticket created
    if ($migration->addField('glpi_users', 'backcreated', 'TINYINT(1) DEFAULT NULL')) {
        $query = "INSERT INTO `glpi_configs`\n                       (`context`, `name`, `value`)\n                VALUES ('core', 'backcreated', 0)";
        $DB->queryOrDie($query, "update glpi_configs with backcreated");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_projects'));
    if (!TableExists("glpi_projects")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `projectstates_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttypes_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `plan_start_date` datetime DEFAULT NULL,\n                  `plan_end_date` datetime DEFAULT NULL,\n                  `real_start_date` datetime DEFAULT NULL,\n                  `real_end_date` datetime DEFAULT NULL,\n                  `percent_done` int(11) NOT NULL DEFAULT '0',\n                  `show_on_global_gantt` tinyint(1) NOT NULL DEFAULT '0',\n                  `content` longtext DEFAULT NULL,\n                  `comment` longtext DEFAULT NULL,\n                  `notepad` longtext DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `code` (`code`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `projectstates_id` (`projectstates_id`),\n                  KEY `projecttypes_id` (`projecttypes_id`),\n                  KEY `priority` (`priority`),\n                  KEY `date` (`date`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `users_id` (`users_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `plan_start_date` (`plan_start_date`),\n                  KEY `plan_end_date` (`plan_end_date`),\n                  KEY `real_start_date` (`real_start_date`),\n                  KEY `real_end_date` (`real_end_date`),\n                  KEY `percent_done` (`percent_done`),\n                  KEY `show_on_global_gantt` (`show_on_global_gantt`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_projects");
        $ADDTODISPLAYPREF['Project'] = array(3, 4, 12, 5, 15, 21);
    }
    $migration->addField("glpi_projects", 'is_deleted', "bool");
    if (countElementsInTable("glpi_profilerights", "`name` = 'project'") == 0) {
        ProfileRight::addProfileRights(array('project'));
        ProfileRight::updateProfileRightAsOtherRight('project', Project::READMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
        ProfileRight::updateProfileRightAsOtherRight('project', Project::READALL, "`name` = 'change'\n                                                     AND `rights` & " . Change::READALL);
        ProfileRight::updateProfileRightAsOtherRight('project', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . " | " . READNOTE . " | " . UPDATENOTE, "`name` = 'change'\n                                                      AND `rights` & (" . CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . ')');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'projecttask'") == 0) {
        ProfileRight::addProfileRights(array('projecttask'));
        ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::READMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
        ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::UPDATEMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
    }
    if (!TableExists('glpi_projectcosts')) {
        $query = "CREATE TABLE `glpi_projectcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `begin_date` date DEFAULT NULL,\n                  `end_date` date DEFAULT NULL,\n                  `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `budgets_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `end_date` (`end_date`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `budgets_id` (`budgets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projectcosts");
    }
    if (!TableExists('glpi_projectstates')) {
        $query = "CREATE TABLE `glpi_projectstates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `color` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `is_finished` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `is_finished` (`is_finished`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projectstates");
        $ADDTODISPLAYPREF['ProjectState'] = array(12, 11);
        $states = array('new' => array('name' => _x('ticket', 'New'), 'color' => '#06ff00', 'is_finished' => 0), 'do' => array('name' => __('Processing'), 'color' => '#ffb800', 'is_finished' => 0), 'end' => array('name' => __('Closed'), 'color' => '#ff0000', 'is_finished' => 1));
        foreach ($states as $key => $val) {
            $query = "INSERT INTO `glpi_projectstates`\n                          (`name`,`color`,`is_finished`)\n                   VALUES ('" . addslashes($val['name']) . "','" . addslashes($val['color']) . "',\n                           '" . addslashes($val['is_finished']) . "')";
            $DB->queryOrDie($query, "0.85 insert default project state {$key}");
        }
    }
    if (!TableExists('glpi_projecttypes')) {
        $query = "CREATE TABLE `glpi_projecttypes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projecttypes");
    }
    $migration->addField("glpi_groups", 'is_manager', "bool", array('update' => "`is_assign`", 'value' => 1));
    $migration->addKey('glpi_groups', 'is_manager');
    if (!TableExists('glpi_changes_projects')) {
        $query = "CREATE TABLE `glpi_changes_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`projects_id`),\n                  KEY `projects_id` (`projects_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_projects");
    }
    if (!TableExists('glpi_projectteams')) {
        $query = "CREATE TABLE `glpi_projectteams` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projectteams");
    }
    if (!TableExists('glpi_items_projects')) {
        $query = "CREATE TABLE `glpi_items_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_items_projects");
    }
    if (!TableExists("glpi_projecttasks")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_projecttasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `content` longtext DEFAULT NULL,\n                  `comment` longtext DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `plan_start_date` datetime DEFAULT NULL,\n                  `plan_end_date` datetime DEFAULT NULL,\n                  `real_start_date` datetime DEFAULT NULL,\n                  `real_end_date` datetime DEFAULT NULL,\n                  `planned_duration` int(11) NOT NULL DEFAULT '0',\n                  `effective_duration` int(11) NOT NULL DEFAULT '0',\n                  `projectstates_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasktypes_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `percent_done` int(11) NOT NULL DEFAULT '0',\n                  `notepad` longtext DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `projecttasks_id` (`projecttasks_id`),\n                  KEY `date` (`date`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `users_id` (`users_id`),\n                  KEY `plan_start_date` (`plan_start_date`),\n                  KEY `plan_end_date` (`plan_end_date`),\n                  KEY `real_start_date` (`real_start_date`),\n                  KEY `real_end_date` (`real_end_date`),\n                  KEY `percent_done` (`percent_done`),\n                  KEY `projectstates_id` (`projectstates_id`),\n                  KEY `projecttasktypes_id` (`projecttasktypes_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttasks");
        $ADDTODISPLAYPREF['ProjectTask'] = array(2, 12, 14, 5, 7, 8, 13);
    }
    if (!TableExists('glpi_projecttasktypes')) {
        $query = "CREATE TABLE `glpi_projecttasktypes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projecttasktypes");
    }
    if (!TableExists('glpi_projecttaskteams')) {
        $query = "CREATE TABLE `glpi_projecttaskteams` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projecttasks_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttaskteams");
    }
    if (!TableExists('glpi_projecttasks_tickets')) {
        $query = "CREATE TABLE `glpi_projecttasks_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`tickets_id`,`projecttasks_id`),\n                  KEY `projects_id` (`projecttasks_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttasks_tickets");
    }
    // Project notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'Project'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Projects', 'Project', NOW())";
            $DB->queryOrDie($query, "0.85 add project notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##project.action## ##project.name## ##project.code##',\n                          '##lang.project.url## : ##project.url##\n\n##lang.project.description##\n\n##lang.project.name## : ##project.name##\n##lang.project.code## : ##project.code##\n##lang.project.manager## : ##project.manager##\n##lang.project.managergroup## : ##project.managergroup##\n##lang.project.creationdate## : ##project.creationdate##\n##lang.project.priority## : ##project.priority##\n##lang.project.state## : ##project.state##\n##lang.project.type## : ##project.type##\n##lang.project.description## : ##project.description##\n\n##lang.project.numberoftasks## : ##project.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n                          '&lt;p&gt;##lang.project.url## : &lt;a href=\"##project.url##\"&gt;##project.url##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;##lang.project.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.project.name## : ##project.name##&lt;br /&gt;##lang.project.code## : ##project.code##&lt;br /&gt; ##lang.project.manager## : ##project.manager##&lt;br /&gt;##lang.project.managergroup## : ##project.managergroup##&lt;br /&gt; ##lang.project.creationdate## : ##project.creationdate##&lt;br /&gt;##lang.project.priority## : ##project.priority## &lt;br /&gt;##lang.project.state## : ##project.state##&lt;br /&gt;##lang.project.type## : ##project.type##&lt;br /&gt;##lang.project.description## : ##project.description##&lt;/p&gt;\n&lt;p&gt;##lang.project.numberoftasks## : ##project.numberoftasks##&lt;/p&gt;\n&lt;div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt;[##task.creationdate##] &lt;/strong&gt;&lt;br /&gt; ##lang.task.name## : ##task.name##&lt;br /&gt;##lang.task.state## : ##task.state##&lt;br /&gt;##lang.task.type## : ##task.type##&lt;br /&gt;##lang.task.percent## : ##task.percent##&lt;br /&gt;##lang.task.description## : ##task.description##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add project notification translation");
            $notifications = array('new' => array(), 'update' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Project', 'update' => 'Update Project', 'delete' => 'Delete Project');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::MANAGER_USER;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::MANAGER_GROUP;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Project', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add project {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add project {$type} notification target");
                }
            }
        }
    }
    // Project Task notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'ProjectTask'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Project Tasks', 'ProjectTask', NOW())";
            $DB->queryOrDie($query, "0.85 add project task notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##projecttask.action## ##projecttask.name##',\n                          '##lang.projecttask.url## : ##projecttask.url##\n\n##lang.projecttask.description##\n\n##lang.projecttask.name## : ##projecttask.name##\n##lang.projecttask.project## : ##projecttask.name##\n##lang.projecttask.creationdate## : ##projecttask.creationdate##\n##lang.projecttask.state## : ##projecttask.state##\n##lang.projecttask.type## : ##projecttask.type##\n##lang.projecttask.description## : ##projecttask.description##\n\n##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n                          '&lt;p&gt;##lang.projecttask.url## : &lt;a href=\"##projecttask.url##\"&gt;##projecttask.url##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;##lang.projecttask.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.projecttask.name## : ##projecttask.name##&lt;br /&gt;##lang.projecttask.project## : &lt;a href=\"##projecttask.projecturl##\"&gt;##projecttask.name##&lt;/a&gt;&lt;br /&gt;##lang.projecttask.creationdate## : ##projecttask.creationdate##&lt;br /&gt;##lang.projecttask.state## : ##projecttask.state##&lt;br /&gt;##lang.projecttask.type## : ##projecttask.type##&lt;br /&gt;##lang.projecttask.description## : ##projecttask.description##&lt;/p&gt\n&lt;p&gt;##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##&lt;/p&gt;\n&lt;div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt;[##task.creationdate##] &lt;/strong&gt;&lt;br /&gt;##lang.task.name## : ##task.name##&lt;br /&gt;##lang.task.state## : ##task.state##&lt;br /&gt;##lang.task.type## : ##task.type##&lt;br /&gt;##lang.task.percent## : ##task.percent##&lt;br /&gt;##lang.task.description## : ##task.description##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add project task notification translation");
            $notifications = array('new' => array(), 'update' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Project Task', 'update' => 'Update Project Task', 'delete' => 'Delete Project Task');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::TEAM_USER;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::TEAM_GROUP;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'ProjectTask', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add project task  {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add project task {$type} notification target");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'notepad'));
    // Create new notepad table
    if (!TableExists('glpi_notepads')) {
        $query = "CREATE TABLE `glpi_notepads` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `content` LONGTEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`itemtype`,`items_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `date` (`date`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_notepads");
        $notepad_tables = array('glpi_budgets', 'glpi_cartridgeitems', 'glpi_changes', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_entities', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_problems', 'glpi_projects', 'glpi_projecttasks', 'glpi_softwares', 'glpi_suppliers');
        foreach ($notepad_tables as $t) {
            // Migrate data
            if (FieldExists($t, 'notepad')) {
                $query = "SELECT id, notepad\n                      FROM `{$t}`\n                      WHERE notepad IS NOT NULL\n                            AND notepad <>'';";
                foreach ($DB->request($query) as $data) {
                    $iq = "INSERT INTO `glpi_notepads`\n                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\n                      VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\n                              '" . addslashes($data['notepad']) . "', NOW(), NOW())";
                    $DB->queryOrDie($iq, "0.85 migrate notepad data");
                }
                $migration->dropField($t, 'notepad');
            }
        }
    }
    $migration->addField('glpi_deviceprocessors', 'nbcores_default', 'int');
    $migration->addField('glpi_deviceprocessors', 'nbthreads_default', 'int');
    $migration->addField('glpi_items_deviceprocessors', 'nbcores', 'int');
    $migration->addField('glpi_items_deviceprocessors', 'nbthreads', 'int');
    $migration->addKey('glpi_items_deviceprocessors', 'nbcores');
    $migration->addKey('glpi_items_deviceprocessors', 'nbthreads');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticketvalidations status'));
    $status = array('none' => CommonITILValidation::NONE, 'waiting' => CommonITILValidation::WAITING, 'accepted' => CommonITILValidation::ACCEPTED, 'rejected' => CommonITILValidation::REFUSED);
    // Migrate datas
    foreach ($status as $old => $new) {
        $query = "UPDATE `glpi_ticketvalidations`\n                SET `status` = '{$new}'\n                WHERE `status` = '{$old}'";
        $DB->queryOrDie($query, "0.85 status in glpi_ticketvalidations {$old} to {$new}");
    }
    $migration->changeField('glpi_ticketvalidations', 'status', 'status', 'integer', array('value' => CommonITILValidation::WAITING));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and changes global_validation'));
    $tables = array('glpi_tickets', 'glpi_changes');
    foreach ($tables as $table) {
        foreach ($status as $old => $new) {
            $query = "UPDATE `" . $table . "`\n                   SET `global_validation` = '{$new}'\n                   WHERE `global_validation` = '{$old}'";
            $DB->queryOrDie($query, "0.85 global_validation in {$table} {$old} to {$new}");
        }
        $migration->changeField($table, 'global_validation', 'global_validation', 'integer', array('value' => CommonITILValidation::NONE));
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickettemplatepredefinedfields value'));
    foreach ($status as $old => $new) {
        $query = "UPDATE `glpi_tickettemplatepredefinedfields`\n                SET `value` = '{$new}'\n                WHERE `num` = '52'\n                      AND `value` = '{$old}'";
        $DB->queryOrDie($query, "0.85 value in glpi_tickettemplatepredefinedfields {$old} to {$new}");
    }
    // Migrate templates
    $query = "SELECT `glpi_notificationtemplatetranslations`.*\n             FROM `glpi_notificationtemplatetranslations`\n             INNER JOIN `glpi_notificationtemplates`\n                  ON (`glpi_notificationtemplates`.`id`\n                        = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n             WHERE `glpi_notificationtemplatetranslations`.`content_text` LIKE '%validation.storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%validation.storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%validation.storestatus=%'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result)) {
            while ($data = $DB->fetch_assoc($result)) {
                $subject = $data['subject'];
                $text = $data['content_text'];
                $html = $data['content_html'];
                foreach ($status as $old => $new) {
                    $subject = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $subject);
                    $text = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $text);
                    $html = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $html);
                }
                $query = "UPDATE `glpi_notificationtemplatetranslations`\n                      SET `subject` = '" . addslashes($subject) . "',\n                         `content_text` = '" . addslashes($text) . "',\n                         `content_html` = '" . addslashes($html) . "'\n                      WHERE `id` = " . $data['id'] . "";
                $DB->queryOrDie($query, "0.85 fix tags usage for storestatus");
            }
        }
    }
    // Upgrade ticket bookmarks
    $query = "SELECT *\n             FROM `glpi_bookmarks`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                if (isset($options['field'])) {
                    // update ticket statuses
                    if (($data['itemtype'] = 'Ticket') && $data['type'] == Bookmark::SEARCH) {
                        foreach ($options['field'] as $key => $val) {
                            if (($val == 55 || $val == 52) && isset($options['contains'][$key])) {
                                if (isset($status[$options['contains'][$key]])) {
                                    $options['contains'][$key] = $status[$options['contains'][$key]];
                                }
                            }
                        }
                    }
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                       SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.85 update bookmarks");
            }
        }
    }
    //////////////////////////////////////////////////
    // Device update
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Devices'));
    foreach (array_merge(CommonDevice::getDeviceTypes(), Item_Devices::getDeviceTypes()) as $itemtype) {
        $table = $itemtype::getTable();
        if (!FieldExists($table, 'entities_id')) {
            $migration->addField($table, 'entities_id', 'integer');
            $migration->addKey($table, array('entities_id'), 'entities_id');
        }
        if (!FieldExists($table, 'is_recursive')) {
            $migration->addField($table, 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
            $migration->addKey($table, array('is_recursive'), 'is_recursive');
        }
    }
    // Adding the Registered ID class that contains PCI IDs and USB IDs for vendors
    // as well devices
    if (!TableExists('glpi_registeredids')) {
        $query = "CREATE TABLE `glpi_registeredids` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `name` varchar(255) DEFAULT NULL,\n                 `items_id` int(11) NOT NULL DEFAULT '0',\n                 `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                 `device_type` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'USB, PCI ...',\n                 PRIMARY KEY (`id`),\n                 KEY `name` (`name`),\n                 KEY `item` (`items_id`, `itemtype`),\n                 KEY `device_type` (`device_type`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_registeredids");
    }
    // Complete the item_devices
    foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_devicesoundcards') as $table) {
        if (!FieldExists($table, 'serial')) {
            $migration->addField($table, 'serial', 'string');
            $migration->addKey($table, 'serial');
        }
    }
    foreach (array('glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) {
        if (!FieldExists($table, 'busID')) {
            $migration->addField($table, 'busID', 'string');
            $migration->addKey($table, 'busID');
        }
    }
    // Add key
    foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) {
        $migration->dropKey($table, 'item');
        $migration->migrationOneTable($table);
        $migration->addKey($table, array('itemtype', 'items_id'), 'item');
    }
    if (!FieldExists('glpi_devicegraphiccards', 'chipset')) {
        $migration->addField('glpi_devicegraphiccards', 'chipset', 'string');
        $migration->addKey('glpi_devicegraphiccards', 'chipset');
    }
    $migration->addField("glpi_suppliers_tickets", "use_notification", "bool");
    $migration->addField("glpi_suppliers_tickets", "alternative_email", "string");
    $migration->addField("glpi_problems_suppliers", "use_notification", "bool");
    $migration->addField("glpi_problems_suppliers", "alternative_email", "string");
    $migration->addField("glpi_changes_suppliers", "use_notification", "bool");
    $migration->addField("glpi_changes_suppliers", "alternative_email", "string");
    // Add field for locations
    $migration->addField("glpi_locations", "latitude", "string");
    $migration->addField("glpi_locations", "longitude", "string");
    $migration->addField("glpi_locations", "altitude", "string");
    // Add fixed columns as variables :
    $ADDTODISPLAYPREF['CartridgeItem'] = array(9);
    $ADDTODISPLAYPREF['ConsumableItem'] = array(9);
    $ADDTODISPLAYPREF['ReservationItem'] = array(9);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'License validity'));
    // for licence validity
    if ($migration->addField("glpi_softwarelicenses", "is_valid", "bool", array("value" => 1))) {
        $migration->migrationOneTable("glpi_softwarelicenses");
        // Force all entities
        if (!isset($_SESSION['glpishowallentities'])) {
            $_SESSION['glpishowallentities'] = 0;
        }
        $savesession = $_SESSION['glpishowallentities'];
        $_SESSION['glpishowallentities'] = 1;
        $queryl = "SELECT `id`, `number`\n                 FROM `glpi_softwarelicenses`";
        foreach ($DB->request($queryl) as $datal) {
            if ($datal['number'] >= 0 && $datal['number'] < Computer_SoftwareLicense::countForLicense($datal['id'], -1)) {
                $queryl2 = "UPDATE `glpi_softwarelicenses`\n                        SET `is_valid` = 0\n                        WHERE `id` = '" . $datal['id'] . "'";
                $DB->queryOrDie($queryl2, "0.85 update softwarelicense");
            }
        }
        $_SESSION['glpishowallentities'] = $savesession;
    }
    if ($migration->addField("glpi_softwares", "is_valid", "bool", array("value" => 1))) {
        $migration->migrationOneTable("glpi_softwares");
        $querys = "SELECT `glpi_softwares`.`id`\n                 FROM `glpi_softwares`\n                 LEFT JOIN `glpi_softwarelicenses`\n                     ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n                 WHERE `glpi_softwarelicenses`.`is_valid` = 0";
        foreach ($DB->request($querys) as $datas) {
            $querys2 = "UPDATE `glpi_softwares`\n                     SET `is_valid` = 0\n                     WHERE `id` = '" . $datas['id'] . "'";
            $DB->queryOrDie($querys2, "0.85 update software");
        }
    }
    // Add condition to rules
    $migration->addField('glpi_rules', 'condition', 'integer');
    $migration->addKey('glpi_rules', 'condition');
    $migration->migrationOneTable('glpi_rules');
    // Update condition for RuleTicket : only on add
    $query = "UPDATE `glpi_rules`\n             SET `condition` = 1\n             WHERE `sub_type` = 'RuleTicket'";
    $DB->queryOrDie($query, "0.85 update condition for RuleTicket");
    // Update ticket_status for helpdeks profiles
    $newcycle = array(1 => array(2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 2 => array(1 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 3 => array(1 => 0, 2 => 0, 4 => 0, 5 => 0, 6 => 0), 4 => array(1 => 0, 2 => 0, 3 => 0, 5 => 0, 6 => 0), 5 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0), 6 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0));
    $query = "UPDATE `glpi_profiles`\n             SET `ticket_status` = '" . exportArrayToDB($newcycle) . "'\n             WHERE `interface` = 'helpdesk'";
    $DB->queryOrDie($query, "0.85 update default life cycle for helpdesk");
    //Add comment field to a virtualmachine
    $migration->addField('glpi_computervirtualmachines', 'comment', 'text');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'IP improvment'));
    // Ip search improve
    $migration->addField('glpi_ipaddresses', 'mainitems_id', 'integer');
    $migration->addField('glpi_ipaddresses', 'mainitemtype', 'string', array('after' => 'mainitems_id'));
    $migration->migrationOneTable('glpi_ipaddresses');
    $migration->addKey('glpi_ipaddresses', array('mainitemtype', 'mainitems_id', 'is_deleted'), 'mainitem');
    $query_doc_i = "UPDATE `glpi_ipaddresses` as `ip`\n                   INNER JOIN `glpi_networknames` as `netname`\n                     ON  (`ip`.`items_id` = `netname`.`id`\n                            AND `ip`.`itemtype` = 'NetworkName')\n                   INNER JOIN `glpi_networkports` as `netport`\n                     ON  (`netname`.`items_id` = `netport`.`id`\n                            AND `netname`.`itemtype` = 'NetworkPort')\n                   SET `ip`.`mainitemtype` = `netport`.`itemtype`,\n                       `ip`.`mainitems_id` = `netport`.`items_id`";
    $DB->queryOrDie($query_doc_i, "0.85 update mainitems fields of ipaddresses");
    // Upgrade ticket bookmarks
    $query = "SELECT *\n             FROM `glpi_bookmarks`\n             WHERE `type` = '" . Bookmark::SEARCH . "'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                // Copy itemtype if not set
                if (!isset($options['itemtype'])) {
                    $options['itemtype'] = $data['itemtype'];
                }
                // Move criteria
                if (isset($options['field']) && is_array($options['field'])) {
                    $newkey = 0;
                    foreach ($options['field'] as $key => $val) {
                        $options['criteria'][$newkey]['field'] = $val;
                        //  other field
                        if (isset($options['link'][$key])) {
                            $options['criteria'][$newkey]['link'] = $options['link'][$key];
                        }
                        if (isset($options['searchtype'][$key])) {
                            $options['criteria'][$newkey]['searchtype'] = $options['searchtype'][$key];
                        } else {
                            $options['criteria'][$newkey]['searchtype'] = 'contains';
                        }
                        if (isset($options['contains'][$key])) {
                            $options['criteria'][$newkey]['value'] = $options['contains'][$key];
                        } else {
                            $options['criteria'][$newkey]['value'] = '';
                        }
                        $newkey++;
                    }
                    unset($options['field']);
                    unset($options['contains']);
                    unset($options['searchtype']);
                    unset($options['link']);
                }
                if (isset($options['glpisearchcount'])) {
                    unset($options['glpisearchcount']);
                }
                if (isset($options['field2']) && is_array($options['field2'])) {
                    $newkey = 0;
                    foreach ($options['field2'] as $key => $val) {
                        $options['metacriteria'][$newkey]['field'] = $val;
                        //  other field
                        if (isset($options['itemtype2'][$key])) {
                            $options['metacriteria'][$newkey]['itemtype'] = $options['itemtype2'][$key];
                        }
                        if (isset($options['link2'][$newkey])) {
                            $options['metacriteria'][$newkey]['link'] = $options['link2'][$key];
                        }
                        if (isset($options['searchtype2'][$key])) {
                            $options['metacriteria'][$newkey]['searchtype'] = $options['searchtype2'][$key];
                        } else {
                            $options['metacriteria'][$newkey]['searchtype'] = 'contains';
                        }
                        if (isset($options['contains2'][$key])) {
                            $options['metacriteria'][$newkey]['value'] = $options['contains2'][$key];
                        } else {
                            $options['metacriteria'][$newkey]['value'] = '';
                        }
                        $newkey++;
                    }
                    unset($options['field2']);
                    unset($options['contains2']);
                    unset($options['searchtype2']);
                    unset($options['link2']);
                    unset($options['itemtype2']);
                }
                if (isset($options['glpisearchcount2'])) {
                    unset($options['glpisearchcount2']);
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                       SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.85 update bookmarks for reorg search");
            }
        }
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Clean display prefs
    // Notepad
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 90\n             WHERE `itemtype` = 'Entity'\n                   AND `num` = 28";
    $DB->query($query);
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 200\n             WHERE `num` = 90";
    $DB->query($query);
    $migration->updateDisplayPrefs($ADDTODISPLAYPREF, $DELFROMDISPLAYPREF);
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
コード例 #24
0
ファイル: ruleaction.class.php プロジェクト: stweil/glpi
 /**
  * @param $options   array
  **/
 function displayActionSelectPattern($options = array())
 {
     $display = false;
     $param['value'] = '';
     if (isset($options['value'])) {
         $param['value'] = $options['value'];
     }
     switch ($options["action_type"]) {
         //If a regex value is used, then always display an autocompletiontextfield
         case "regex_result":
         case "append_regex_result":
             Html::autocompletionTextField($this, "value", $param);
             break;
         case 'fromuser':
         case 'fromitem':
             Dropdown::showYesNo("value", $param['value'], 0);
             $display = true;
             break;
         default:
             $actions = Rule::getActionsByType($options["sub_type"]);
             if (isset($actions[$options["field"]]['type'])) {
                 switch ($actions[$options["field"]]['type']) {
                     case "dropdown":
                         $table = $actions[$options["field"]]['table'];
                         $param['name'] = "value";
                         if (isset($actions[$options["field"]]['condition'])) {
                             $param['condition'] = $actions[$options["field"]]['condition'];
                         }
                         Dropdown::show(getItemTypeForTable($table), $param);
                         $display = true;
                         break;
                     case "dropdown_tickettype":
                         Ticket::dropdownType('value', $param);
                         $display = true;
                         break;
                     case "dropdown_assign":
                         $param['name'] = 'value';
                         $param['right'] = 'own_ticket';
                         User::dropdown($param);
                         $display = true;
                         break;
                     case "dropdown_users":
                         $param['name'] = 'value';
                         $param['right'] = 'all';
                         User::dropdown($param);
                         $display = true;
                         break;
                     case "dropdown_urgency":
                         $param['name'] = 'value';
                         Ticket::dropdownUrgency($param);
                         $display = true;
                         break;
                     case "dropdown_impact":
                         $param['name'] = 'value';
                         Ticket::dropdownImpact($param);
                         $display = true;
                         break;
                     case "dropdown_priority":
                         if ($_POST["action_type"] != 'compute') {
                             $param['name'] = 'value';
                             Ticket::dropdownPriority($param);
                         }
                         $display = true;
                         break;
                     case "dropdown_status":
                         $param['name'] = 'value';
                         Ticket::dropdownStatus($param);
                         $display = true;
                         break;
                     case "yesonly":
                         Dropdown::showYesNo("value", $param['value'], 0);
                         $display = true;
                         break;
                     case "yesno":
                         Dropdown::showYesNo("value", $param['value']);
                         $display = true;
                         break;
                     case "dropdown_management":
                         $param['name'] = 'value';
                         $param['management_restrict'] = 2;
                         $param['withtemplate'] = false;
                         Dropdown::showGlobalSwitch(0, $param);
                         $display = true;
                         break;
                     case "dropdown_users_validate":
                         $used = array();
                         if ($item = getItemForItemtype($options["sub_type"])) {
                             $rule_data = getAllDatasFromTable('glpi_ruleactions', "`action_type` = 'add_validation'\n                                                           AND `field` = 'users_id_validate'\n                                                           AND `" . $item->getRuleIdField() . "`\n                                                            = '" . $options[$item->getRuleIdField()] . "'");
                             foreach ($rule_data as $data) {
                                 $used[] = $data['value'];
                             }
                         }
                         $param['name'] = 'value';
                         $param['right'] = array('validate_incident', 'validate_request');
                         $param['used'] = $used;
                         User::dropdown($param);
                         $display = true;
                         break;
                     case "dropdown_groups_validate":
                         $used = array();
                         if ($item = getItemForItemtype($options["sub_type"])) {
                             $rule_data = getAllDatasFromTable('glpi_ruleactions', "`action_type` = 'add_validation'\n                                                           AND `field` = 'groups_id_validate'\n                                                           AND `" . $item->getRuleIdField() . "`\n                                                            = '" . $options[$item->getRuleIdField()] . "'");
                             foreach ($rule_data as $data) {
                                 $used[] = $data['value'];
                             }
                         }
                         $condition = "(SELECT count(`users_id`)\n                                    FROM `glpi_groups_users`\n                                    WHERE `groups_id` = `glpi_groups`.`id`)";
                         $param['name'] = 'value';
                         $param['condition'] = $condition;
                         $param['right'] = array('validate_incident', 'validate_request');
                         $param['used'] = $used;
                         Group::dropdown($param);
                         $display = true;
                         break;
                     case "dropdown_validation_percent":
                         $ticket = new Ticket();
                         echo $ticket->getValueToSelect('validation_percent', 'value', $param['value']);
                         $display = true;
                         break;
                     default:
                         if ($rule = getItemForItemtype($options["sub_type"])) {
                             $display = $rule->displayAdditionalRuleAction($actions[$options["field"]], $param['value']);
                         }
                         break;
                 }
             }
             if (!$display) {
                 Html::autocompletionTextField($this, "value", $param);
             }
     }
 }
コード例 #25
0
ファイル: search.class.php プロジェクト: jose-martins/glpi
 /**
  * @param $itemtype
  * @param $field_num
  **/
 static function getActionsFor($itemtype, $field_num)
 {
     $searchopt =& self::getOptions($itemtype);
     $actions = array('contains' => __('contains'), 'searchopt' => array());
     if (isset($searchopt[$field_num])) {
         $actions['searchopt'] = $searchopt[$field_num];
         // Force search type
         if (isset($actions['searchopt']['searchtype'])) {
             // Reset search option
             $actions = array();
             $actions['searchopt'] = $searchopt[$field_num];
             if (!is_array($actions['searchopt']['searchtype'])) {
                 $actions['searchopt']['searchtype'] = array($actions['searchopt']['searchtype']);
             }
             foreach ($actions['searchopt']['searchtype'] as $searchtype) {
                 switch ($searchtype) {
                     case "equals":
                         $actions['equals'] = __('is');
                         break;
                     case "notequals":
                         $actions['notequals'] = __('is not');
                         break;
                     case "contains":
                         $actions['contains'] = __('contains');
                         break;
                     case "under":
                         $actions['under'] = __('under');
                         break;
                     case "notunder":
                         $actions['notunder'] = __('not under');
                         break;
                     case "lessthan":
                         $actions['lessthan'] = __('before');
                         break;
                     case "morethan":
                         $actions['morethan'] = __('after');
                         break;
                 }
             }
             return $actions;
         }
         if (isset($searchopt[$field_num]['datatype'])) {
             switch ($searchopt[$field_num]['datatype']) {
                 case 'count':
                 case 'number':
                     $opt = array('contains' => __('contains'), 'equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                     // No is / isnot if no limits defined
                     if (!isset($searchopt[$field_num]['min']) && !isset($searchopt[$field_num]['max'])) {
                         unset($opt['equals']);
                         unset($opt['notequals']);
                     }
                     return $opt;
                 case 'bool':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'contains' => __('contains'), 'searchopt' => $searchopt[$field_num]);
                 case 'right':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                 case 'itemtypename':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                 case 'date':
                 case 'datetime':
                 case 'date_delay':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'lessthan' => __('before'), 'morethan' => __('after'), 'contains' => __('contains'), 'searchopt' => $searchopt[$field_num]);
             }
         }
         //          switch ($searchopt[$field_num]['table']) {
         //             case 'glpi_users_validation' :
         //                return array('equals'    => __('is'),
         //                             'notequals' => __('is not'),
         //                             'searchopt' => $searchopt[$field_num]);
         //          }
         switch ($searchopt[$field_num]['field']) {
             case 'id':
                 return array('equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
             case 'name':
             case 'completename':
                 $actions = array('contains' => __('contains'), 'equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                 // Specific case of TreeDropdown : add under
                 $itemtype_linked = getItemTypeForTable($searchopt[$field_num]['table']);
                 if ($itemlinked = getItemForItemtype($itemtype_linked)) {
                     if ($itemlinked instanceof CommonTreeDropdown) {
                         $actions['under'] = __('under');
                         $actions['notunder'] = __('not under');
                     }
                     return $actions;
                 }
         }
     }
     return $actions;
 }
コード例 #26
0
ファイル: rule.class.php プロジェクト: pvasener/glpi
 /**
  * Display item used to select a pattern for a criteria
  *
  * @param $name      criteria name
  * @param $ID        the given criteria
  * @param $condition condition used
  * @param $value     the pattern (default '')
  * @param $test      Is to test rule ? (false by default)
  **/
 function displayCriteriaSelectPattern($name, $ID, $condition, $value = "", $test = false)
 {
     $crit = $this->getCriteria($ID);
     $display = false;
     $tested = false;
     if (isset($crit['type']) && ($test || in_array($condition, array(self::PATTERN_IS, self::PATTERN_IS_NOT, self::PATTERN_NOT_UNDER, self::PATTERN_UNDER)))) {
         switch ($crit['type']) {
             case "yesonly":
                 Dropdown::showYesNo($name, $crit['table'], 0);
                 $display = true;
                 break;
             case "yesno":
                 Dropdown::showYesNo($name, $crit['table']);
                 $display = true;
                 break;
             case "dropdown":
                 $param = array('name' => $name, 'value' => $value);
                 if (isset($crit['condition'])) {
                     $param['condition'] = $crit['condition'];
                 }
                 Dropdown::show(getItemTypeForTable($crit['table']), $param);
                 $display = true;
                 break;
             case "dropdown_users":
                 User::dropdown(array('value' => $value, 'name' => $name, 'right' => 'all'));
                 $display = true;
                 break;
             case "dropdown_tracking_itemtype":
                 Dropdown::showItemTypes($name, array_keys(Ticket::getAllTypesForHelpdesk()));
                 $display = true;
                 break;
             case "dropdown_urgency":
                 Ticket::dropdownUrgency(array('name' => $name, 'value' => $value));
                 $display = true;
                 break;
             case "dropdown_impact":
                 Ticket::dropdownImpact(array('name' => $name, 'value' => $value));
                 $display = true;
                 break;
             case "dropdown_priority":
                 Ticket::dropdownPriority(array('name' => $name, 'value' => $value));
                 $display = true;
                 break;
             case "dropdown_status":
                 Ticket::dropdownStatus(array('name' => $name, 'value' => $value));
                 $display = true;
                 break;
             case "dropdown_tickettype":
                 Ticket::dropdownType($name, array('value' => $value));
                 $display = true;
                 break;
         }
         $tested = true;
     }
     //Not a standard condition
     if (!$tested) {
         $display = $this->displayAdditionalRuleCondition($condition, $crit, $name, $value, $test);
     }
     if ($condition == self::PATTERN_EXISTS || $condition == self::PATTERN_DOES_NOT_EXISTS) {
         echo "<input type='hidden' name='{$name}' value='1'>";
         $display = true;
     }
     if (!$display && ($rc = getItemForItemtype($this->rulecriteriaclass))) {
         Html::autocompletionTextField($rc, "pattern", array('name' => $name, 'value' => $value, 'size' => 70));
     }
 }
コード例 #27
0
function plugin_databases_install()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/databases/inc/profile.class.php";
    $update = false;
    if (!TableExists("glpi_plugin_sgbd") && !TableExists("glpi_plugin_databases_databases")) {
        $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/empty-1.7.0.sql");
    } else {
        if (TableExists("glpi_plugin_sgbd") && !TableExists("glpi_plugin_sgbd_instances")) {
            $update = true;
            $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.1.sql");
            $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.2.0.sql");
            $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.2.1.sql");
            $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.3.0.sql");
        } else {
            if (TableExists("glpi_plugin_sgbd") && !TableExists("glpi_dropdown_plugin_sgbd_category")) {
                $update = true;
                $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.2.0.sql");
                $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.2.1.sql");
                $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.3.0.sql");
            } else {
                if (TableExists("glpi_plugin_sgbd") && !FieldExists("glpi_plugin_sgbd", "helpdesk_visible")) {
                    $update = true;
                    $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.2.1.sql");
                    $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.3.0.sql");
                } else {
                    if (!TableExists("glpi_plugin_databases_databases")) {
                        $update = true;
                        $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.3.0.sql");
                    }
                }
            }
        }
    }
    //from 1.3 version
    if (TableExists("glpi_plugin_databases_databases") && !FieldExists("glpi_plugin_databases_databases", "users_id_tech")) {
        $DB->runFile(GLPI_ROOT . "/plugins/databases/sql/update-1.5.0.sql");
    }
    if (TableExists("glpi_plugin_databases_profiles")) {
        $notepad_tables = array('glpi_plugin_databases_databases');
        foreach ($notepad_tables as $t) {
            // Migrate data
            if (FieldExists($t, 'notepad')) {
                $query = "SELECT id, notepad\n                      FROM `{$t}`\n                      WHERE notepad IS NOT NULL\n                            AND notepad <>'';";
                foreach ($DB->request($query) as $data) {
                    $iq = "INSERT INTO `glpi_notepads`\n                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\n                      VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\n                              '" . addslashes($data['notepad']) . "', NOW(), NOW())";
                    $DB->queryOrDie($iq, "0.85 migrate notepad data");
                }
                $query = "ALTER TABLE `glpi_plugin_databases_databases` DROP COLUMN `notepad`;";
                $DB->query($query);
            }
        }
    }
    if ($update) {
        $query_ = "SELECT *\n            FROM `glpi_plugin_databases_profiles` ";
        $result_ = $DB->query($query_);
        if ($DB->numrows($result_) > 0) {
            while ($data = $DB->fetch_array($result_)) {
                $query = "UPDATE `glpi_plugin_databases_profiles`\n                  SET `profiles_id` = '" . $data["id"] . "'\n                  WHERE `id` = '" . $data["id"] . "';";
                $result = $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_plugin_databases_profiles`\n               DROP `name` ;";
        $result = $DB->query($query);
        $query = "SELECT `entities_id`,`is_recursive`,`id` FROM `glpi_plugin_databases_databases` ";
        $result = $DB->query($query);
        $number = $DB->numrows($result);
        if ($number) {
            while ($data = $DB->fetch_array($result)) {
                $query = "UPDATE `glpi_plugin_databases_instances`\n                  SET `entities_id` = '" . $data["entities_id"] . "'\n                  AND `is_recursive` = '" . $data["is_recursive"] . "'\n                  WHERE `plugin_databases_databases_id` = '" . $data["id"] . "' ";
                $DB->query($query) or die($DB->error());
                $query = "UPDATE `glpi_plugin_databases_scripts`\n                  SET `entities_id` = '" . $data["entities_id"] . "'\n                  AND `is_recursive` = '" . $data["is_recursive"] . "'\n                  WHERE `plugin_databases_databases_id` = '" . $data["id"] . "' ";
                $DB->query($query) or die($DB->error());
            }
        }
        Plugin::migrateItemType(array(2400 => 'PluginDatabasesDatabase'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_items_tickets"), array("glpi_plugin_databases_databases_items"));
        Plugin::migrateItemType(array(1200 => "PluginAppliancesAppliance", 1300 => "PluginWebapplicationsWebapplication"), array("glpi_plugin_databases_databases_items"));
    }
    PluginDatabasesProfile::initProfile();
    PluginDatabasesProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
    $migration = new Migration("1.7.0");
    $migration->dropTable('glpi_plugin_databases_profiles');
    return true;
}
コード例 #28
0
 /**
  * Get criteria's related table
  **/
 public function getItemType()
 {
     return getItemTypeForTable($this->table);
 }
コード例 #29
0
                // Standard datatype usage
                if (!$display && isset($searchopt['datatype'])) {
                    switch ($searchopt['datatype']) {
                        case "date":
                        case "date_delay":
                        case "datetime":
                            $options2['relative_dates'] = true;
                            break;
                    }
                }
                $out = $item->getValueToSelect($searchopt, $inputname, $_POST['value'], $options2);
                if (strlen($out)) {
                    echo $out;
                    $display = true;
                }
                //Could display be handled by a plugin ?
                if (!$display && ($plug = isPluginItemType(getItemTypeForTable($searchopt['table'])))) {
                    $function = 'plugin_' . $plug['plugin'] . '_searchOptionsValues';
                    if (function_exists($function)) {
                        $params = array('name' => $inputname, 'searchtype' => $_POST['searchtype'], 'searchoption' => $searchopt, 'value' => $_POST['value']);
                        $display = $function($params);
                    }
                }
            }
            break;
    }
    // Default case : text field
    if (!$display) {
        echo "<input type='text' size='13' name='{$inputname}' value=\"" . Html::cleanInputText($_POST['value']) . "\">";
    }
}
コード例 #30
0
ファイル: info.class.php プロジェクト: JULIO8/respaldo_glpi
 /**
  * Display command additional informations
  *
  * @param info
  * @param option
  * @param injectionClass
  *
  * @return nothing
  **/
 static function showAdditionalInformation(PluginDatainjectionInfo $info, $option = array(), $injectionClass, $values = array())
 {
     $name = "info[" . $option['linkfield'] . "]";
     if (isset($_SESSION['datainjection']['infos'][$option['linkfield']])) {
         $value = $_SESSION['datainjection']['infos'][$option['linkfield']];
     } else {
         $value = '';
     }
     switch ($option['displaytype']) {
         case 'text':
         case 'decimal':
             if (empty($value)) {
                 $value = isset($option['default']) ? $option['default'] : '';
             }
             echo "<input type='text' name='{$name}' value='{$value}'";
             if (isset($option['size'])) {
                 echo " size='" . $option['size'] . "'";
             }
             echo ">";
             break;
         case 'dropdown':
             if ($value == '') {
                 $value = 0;
             }
             Dropdown::show(getItemTypeForTable($option['table']), array('name' => $name, 'value' => $value));
             break;
         case 'bool':
             if ($value == '') {
                 $value = 0;
             }
             Dropdown::showYesNo($name, $value);
             break;
         case 'user':
             if ($value == '') {
                 $value = 0;
             }
             User::dropdown(array('name' => $name, 'value' => $value));
             break;
         case 'date':
             Html::showDateField($name, array('value' => $value));
             break;
         case 'multiline_text':
             echo "<textarea cols='45' rows='5' name='{$name}'>{$value}</textarea>";
             break;
         case 'dropdown_integer':
             $minvalue = isset($option['minvalue']) ? $option['minvalue'] : 0;
             $maxvalue = isset($option['maxvalue']) ? $option['maxvalue'] : 0;
             $step = isset($option['step']) ? $option['step'] : 1;
             $default = isset($option['-1']) ? array(-1 => $option['-1']) : array();
             Dropdown::showNumber($name, array('value' => $value, 'min' => $minvalue, 'max' => $maxvalue, 'step' => $step, 'toadd' => $default));
             break;
         case 'template':
             self::dropdownTemplates($name, $option['table']);
             break;
         case 'password':
             echo "<input type='password' name='{$name}' value='' size='20' autocomplete='off'>";
             break;
         default:
             if (method_exists($injectionClass, 'showAdditionalInformation')) {
                 //If type is not a standard type, must be treated by specific injection class
                 $injectionClass->showAdditionalInformation($info, $option);
             }
     }
     if ($info->isMandatory()) {
         echo "&nbsp;*";
     }
 }