append_params() static public method

Converts an array of parameters into a query string to be appended to a URL.
static public append_params ( $array, $separator = '&', $parent = '' ) : string
$array array parameters to append to the query string.
$separator separator may be defined as & to display purpose (default '&')
$parent This should be left blank (it is used internally by the function). (default '')
return string : Query string to append to a URL.
 /**
  * Display list of hosts
  */
 function showHostsBoard($params, $width = '', $limit = '')
 {
     global $DB, $CFG_GLPI;
     if (!isset($_SESSION['plugin_monitoring_reduced_interface'])) {
         $_SESSION['plugin_monitoring_reduced_interface'] = false;
     }
     $col_to_display = array(0, 10, 1, 2, 3, 6, 7, 8, 9, 11);
     $data = Search::prepareDatasForSearch('PluginMonitoringHost', $params, $col_to_display);
     $data['tocompute'] = $data['toview'];
     Search::constructSQL($data);
     //echo "<pre>";      print_r($data['sql']['search']);
     Search::constructDatas($data);
     //      if (! isset($_GET['order'])) {
     //         $_GET['order'] = "ASC";
     //      }
     //      if (! isset($_GET['sort'])) {
     //         $_GET['sort'] = "";
     //      }
     //
     //      $order = "ASC";
     //      if (isset($_GET['order'])) {
     //         $order = $_GET['order'];
     //      }
     //      $where = '';
     //      if (isset($_GET['field'])) {
     //         foreach ($_GET['field'] as $key=>$value) {
     //            $wheretmp = '';
     //            if (isset($_GET['link'][$key])) {
     //               $wheretmp.= " ".$_GET['link'][$key]." ";
     //            }
     //            $wheretmp .= Search::addWhere(
     //                                   "",
     //                                   0,
     //                                   "PluginMonitoringHost",
     //                                   $_GET['field'][$key],
     //                                   $_GET['searchtype'][$key],
     //                                   $_GET['contains'][$key]);
     //            if (!strstr($wheretmp, "``.``")) {
     //               if ($where != ''
     //                       AND !isset($_GET['link'][$key])) {
     //                  $where .= " AND ";
     //               }
     //               $where .= $wheretmp;
     //            }
     //         }
     //      }
     //      if ($where != '') {
     //         $where = "(".$where;
     //         $where .= ") AND ";
     //      }
     //      $where .= " CONCAT_WS('', `glpi_computers`.`entities_id`, `glpi_printers`.`entities_id`, `glpi_networkequipments`.`entities_id`) IN (".$_SESSION['glpiactiveentities_string'].")";
     //
     //      if ($where != '') {
     //         $where = " WHERE ".$where;
     //         $where = str_replace("`".getTableForItemType("PluginMonitoringDisplay")."`.",
     //                 "", $where);
     //
     //      }
     //
     //      $leftjoin = "
     //         LEFT JOIN `glpi_computers`
     //            ON `glpi_plugin_monitoring_hosts`.`items_id` = `glpi_computers`.`id`
     //               AND `glpi_plugin_monitoring_hosts`.`itemtype`='Computer'
     //         LEFT JOIN `glpi_printers`
     //            ON `glpi_plugin_monitoring_hosts`.`items_id` = `glpi_printers`.`id`
     //               AND `glpi_plugin_monitoring_hosts`.`itemtype`='Printer'
     //         LEFT JOIN `glpi_networkequipments`
     //            ON `glpi_plugin_monitoring_hosts`.`items_id` = `glpi_networkequipments`.`id`
     //               AND `glpi_plugin_monitoring_hosts`.`itemtype`='NetworkEquipment'
     //         LEFT JOIN `glpi_entities`
     //            ON CONCAT_WS('', `glpi_computers`.`entities_id`, `glpi_printers`.`entities_id`, `glpi_networkequipments`.`entities_id`) = `glpi_entities`.`id`
     //
     //      ";
     //
     //      // * ORDER
     //      $ORDERQUERY = "ORDER BY entity_name ASC, host_name ASC";
     //      $toview = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
     //      $toviewComplete = array(
     //          'ITEM_0' => 'entity_name',
     //          'ITEM_1' => 'host_name',
     //          'ITEM_2' => 'host_state',
     //          'ITEM_3' => 'service_state',
     //          'ITEM_4' => 'last_check',
     //          'ITEM_5' => 'event',
     //          'ITEM_6' => 'perf_data',
     //          'ITEM_7' => 'is_acknowledged'
     //      );
     //      foreach ($toview as $key => $val) {
     //         if ($_GET['sort']==$val) {
     //            $ORDERQUERY = Search::addOrderBy("PluginMonitoringHost", $_GET['sort'],
     //                                             $_GET['order'], $key);
     //            foreach ($toviewComplete as $keyi=>$vali) {
     //               $ORDERQUERY= str_replace($keyi, $vali, $ORDERQUERY);
     //            }
     //         }
     //      }
     //
     ////            `glpi_computers`.*
     //
     //      $query = "SELECT
     //            `glpi_entities`.`name` AS entity_name,
     //            CONCAT_WS('', `glpi_computers`.`id`, `glpi_printers`.`id`, `glpi_networkequipments`.`id`) AS idComputer,
     //            CONCAT_WS('', `glpi_computers`.`name`, `glpi_printers`.`name`, `glpi_networkequipments`.`name`) AS host_name,
     //            `glpi_plugin_monitoring_hosts`.*,
     //            `glpi_plugin_monitoring_hosts`.`state` AS host_state,
     //            `glpi_plugin_monitoring_hosts`.`is_acknowledged` AS host_acknowledged
     //         FROM `glpi_plugin_monitoring_hosts`
     //         ".$leftjoin."
     //         ".$where."
     //         ".$ORDERQUERY;
     //      // Toolbox::logInFile("pm", "Query hosts - $query\n");
     //
     //      $result = $DB->query($query);
     //
     //      if (! isset($_GET["start"])) {
     //         $_GET["start"]=0;
     //      }
     //      $start=$_GET['start'];
     //      if (! isset($_GET["order"])) {
     //         $_GET["order"]="ASC";
     //      }
     $rand = mt_rand();
     if (!isset($data['data']) || !isset($data['data']['totalcount'])) {
         return false;
     }
     // Contruct Pager parameters
     $globallinkto = Toolbox::append_params(array('criteria' => Toolbox::stripslashes_deep($data['search']['criteria']), 'metacriteria' => Toolbox::stripslashes_deep($data['search']['metacriteria'])), '&amp;');
     $parameters = "sort=" . $data['search']['sort'] . "&amp;order=" . $data['search']['order'] . '&amp;' . $globallinkto;
     if (isset($_GET['_in_modal'])) {
         $parameters .= "&amp;_in_modal=1";
     }
     // If the begin of the view is before the number of items
     if ($data['data']['count'] > 0) {
         // Display pager only for HTML
         if ($data['display_type'] == Search::HTML_OUTPUT) {
             $search_config_top = "";
             $search_config_bottom = "";
             Html::printPager($data['search']['start'], $data['data']['totalcount'], $data['search']['target'], $parameters, $data['itemtype'], 0, $search_config_top);
         }
         // Define begin and end var for loop
         // Search case
         $begin_display = $data['data']['begin'];
         $end_display = $data['data']['end'];
     }
     echo '<div id="custom_date" style="display:none"></div>';
     echo '<div id="custom_time" style="display:none"></div>';
     if ($width == '') {
         echo "<table class='tab_cadrehov' style='width:100%;'>";
     } else {
         echo "<table class='tab_cadrehov' style='width:" . $width . "px;'>";
     }
     $num = 0;
     if (Session::haveRight("plugin_monitoring_hostcommand", CREATE)) {
         // Host test command ...
         $pmCommand = new PluginMonitoringCommand();
         $a_commands = array();
         $a_list = $pmCommand->find("command_name LIKE 'host_action'");
         foreach ($a_list as $dt) {
             $host_command_name = $dt['name'];
             $host_command_command = $dt['command_line'];
         }
     }
     echo "<tr class='tab_bg_1'>";
     $this->showHeaderItem(__('Entity'), 0, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Type'), 0, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Host', 'monitoring'), 1, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Host state'), 2, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     if (isset($host_command_name)) {
         echo '<th>' . __('Host action', 'monitoring') . '</th>';
     }
     echo '<th>' . __('Host resources state', 'monitoring') . '</th>';
     echo '<th>' . __('IP address', 'monitoring') . '</th>';
     $this->showHeaderItem(__('Last check', 'monitoring'), 4, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Result details', 'monitoring'), 5, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     $this->showHeaderItem(__('Performance data', 'monitoring'), 6, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     if (Session::haveRight("plugin_monitoring_acknowledge", READ) || Session::haveRight("plugin_monitoring_downtime", READ)) {
         $this->showHeaderItem(__('Maintenance', 'monitoring'), 7, $num, $begin_display, $globallinkto, 'host.php', 'PluginMonitoringHost');
     }
     echo "</tr>";
     foreach ($data['data']['rows'] as $row) {
         // Reduced array or not ?
         if ($_SESSION['plugin_monitoring_reduced_interface'] && $row[3]['displayname'] == 'UP') {
             continue;
         }
         if (isset($host_command_name)) {
             $row['host_command_name'] = $host_command_name;
             $row['host_command_command'] = $host_command_command;
         }
         // Get all host services except if state is ok or is already acknowledged ...
         $a_ret = PluginMonitoringHost::getServicesState($row['id'], "`glpi_plugin_monitoring_services`.`state` != 'OK'\n                                                         AND `glpi_plugin_monitoring_services`.`is_acknowledged` = '0'");
         $row['host_services_state'] = $a_ret[0];
         $row['host_services_state_list'] = $a_ret[1];
         // Get host first IP address
         $row['ip'] = __('Unknown IP address', 'monitoring');
         $ip = PluginMonitoringHostaddress::getIp($row[9]['displayname'], $row[1]['displayname'], '');
         if ($ip != '') {
             $row['ip'] = $ip;
         }
         echo "<tr class='tab_bg_3'>";
         $this->displayHostLine($row);
         echo "</tr>";
     }
     echo "</table>";
     echo "<br/>";
     Html::printPager($data['search']['start'], $data['data']['totalcount'], $data['search']['target'], $parameters, '', 0, $search_config_bottom);
 }
Esempio n. 2
0
 /**
  * Create modal window
  * After display it using $name.show()
  * May be constraint to a predefined html item setting renderTo options
  *
  * @since version 0.84
  *
  * @param $name            name of the js object
  * @param $url             URL to display in modal
  * @param $options array   of possible options:
  *          - width (default 800)
  *          - height (default 400)
  *          - modal : is a modal window ? (default true)
  *          - container : specify a html element to render (default empty to html.body)
  *          - title : window title (default empty)
  **/
 static function createModalWindow($name, $url, $options = array())
 {
     $param = array('width' => 800, 'height' => 400, 'modal' => true, 'container' => '', 'title' => '', 'extraparams' => array());
     if (count($options)) {
         foreach ($options as $key => $val) {
             if (isset($param[$key])) {
                 $param[$key] = $val;
             }
         }
     }
     echo "<script type='text/javascript'>";
     echo "var {$name}=new Ext.Window({\n         layout:'fit',\n         width:" . $param['width'] . ",\n         height:" . $param['height'] . ",\n         closeAction:'hide',\n         modal: " . ($param['modal'] ? 'true' : 'false') . ",\n         " . (!empty($param['container']) ? "renderTo: '" . $param['container'] . "'," : '') . "\n         autoScroll: true,\n         title: \"" . addslashes($param['title']) . "\",\n         autoLoad: {url: '{$url}',\n                    scripts: true,\n                    nocache: true";
     if (is_array($param['extraparams']) && count($param['extraparams'])) {
         echo ", params: '" . Toolbox::append_params($param['extraparams']) . "'";
     }
     echo "}";
     echo " }); ";
     echo "</script>";
 }
 /**
  * show user add div on creation
  *
  * @param $type      integer  actor type
  * @param $options   array    options for default values ($options of showForm)
  *
  * @return nothing display
  **/
 function showActorAddFormOnCreate($type, array $options)
 {
     global $CFG_GLPI;
     $typename = self::getActorFieldNameType($type);
     $itemtype = $this->getType();
     echo self::getActorIcon('user', $type);
     // For ticket templates : mandatories
     if ($itemtype == 'Ticket' && isset($options['_tickettemplate'])) {
         echo $options['_tickettemplate']->getMandatoryMark("_users_id_" . $typename);
     }
     echo "&nbsp;";
     if (!isset($options["_right"])) {
         $right = $this->getDefaultActorRightSearch($type);
     } else {
         $right = $options["_right"];
     }
     if ($options["_users_id_" . $typename] == 0) {
         $options["_users_id_" . $typename] = $this->getDefaultActor($type);
     }
     $rand = mt_rand();
     $params = array('name' => '_users_id_' . $typename, 'value' => $options["_users_id_" . $typename], 'right' => $right, 'rand' => $rand, 'ldap_import' => true);
     if ($this->userentity_oncreate && $type == CommonITILActor::REQUESTER) {
         $params['on_change'] = 'this.form.submit()';
     } else {
         // Force entity search if needed
         $params['entity'] = $options['entities_id'];
     }
     if ($CFG_GLPI['use_mailing']) {
         $paramscomment = array('value' => '__VALUE__', 'field' => "_users_id_" . $typename . "_notif", 'allow_email' => $type == CommonITILActor::REQUESTER || $type == CommonITILActor::OBSERVER, 'use_notification' => $options["_users_id_" . $typename . "_notif"]['use_notification']);
         if (isset($options["_users_id_" . $typename . "_notif"]['alternative_email'])) {
             $paramscomment['alternative_email'] = $options["_users_id_" . $typename . "_notif"]['alternative_email'];
         }
         $params['toupdate'] = array('value_fieldname' => 'value', 'to_update' => "notif_" . $typename . "_{$rand}", 'url' => $CFG_GLPI["root_doc"] . "/ajax/uemailUpdate.php", 'moreparams' => $paramscomment);
     }
     if ($itemtype == 'Ticket' && $type == CommonITILActor::ASSIGN) {
         $toupdate = array();
         if (isset($params['toupdate']) && is_array($params['toupdate'])) {
             $toupdate[] = $params['toupdate'];
         }
         $toupdate[] = array('value_fieldname' => 'value', 'to_update' => "countassign_{$rand}", 'url' => $CFG_GLPI["root_doc"] . "/ajax/ticketassigninformation.php", 'moreparams' => array('users_id_assign' => '__VALUE__'));
         $params['toupdate'] = $toupdate;
     }
     // List all users in the active entities
     User::dropdown($params);
     if ($itemtype == 'Ticket') {
         // display opened tickets for user
         if ($type == CommonITILActor::REQUESTER && $options["_users_id_" . $typename] > 0 && $_SESSION["glpiactiveprofile"]["interface"] != "helpdesk") {
             $options2['criteria'][0]['field'] = 4;
             // users_id
             $options2['criteria'][0]['searchtype'] = 'equals';
             $options2['criteria'][0]['value'] = $options["_users_id_" . $typename];
             $options2['criteria'][0]['link'] = 'AND';
             $options2['criteria'][1]['field'] = 12;
             // status
             $options2['criteria'][1]['searchtype'] = 'equals';
             $options2['criteria'][1]['value'] = 'notold';
             $options2['criteria'][1]['link'] = 'AND';
             $options2['reset'] = 'reset';
             $url = $this->getSearchURL() . "?" . Toolbox::append_params($options2, '&amp;');
             echo "&nbsp;<a href='{$url}' title=\"" . __s('Processing') . "\" target='_blank'>(";
             printf(__('%1$s: %2$s'), __('Processing'), $this->countActiveObjectsForUser($options["_users_id_" . $typename]));
             echo ")</a>";
         }
         // Display active tickets for a tech
         // Need to update information on dropdown changes
         if ($type == CommonITILActor::ASSIGN) {
             echo "<span id='countassign_{$rand}'>";
             echo "</span>";
             echo "<script type='text/javascript'>";
             Ajax::updateItemJsCode("countassign_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/ticketassigninformation.php", array('users_id_assign' => '__VALUE__'), "dropdown__users_id_" . $typename . $rand);
             echo "</script>";
         }
     }
     if ($CFG_GLPI['use_mailing']) {
         echo "<div id='notif_" . $typename . "_{$rand}'>";
         echo "</div>";
         echo "<script type='text/javascript'>";
         Ajax::updateItemJsCode("notif_" . $typename . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/uemailUpdate.php", $paramscomment, "dropdown__users_id_" . $typename . $rand);
         echo "</script>";
     }
 }
Esempio n. 4
0
 /**
  * Display tickets for an item
  *
  * Will also display tickets of linked items
  *
  * @param $item CommonDBTM object
  *
  * @return nothing (display a table)
  **/
 static function showListForItem(CommonDBTM $item)
 {
     global $DB, $CFG_GLPI;
     if (!Session::haveRightsOr(self::$rightname, array(self::READALL, self::READMY, self::READASSIGN, CREATE))) {
         return false;
     }
     if ($item->isNewID($item->getID())) {
         return false;
     }
     $restrict = '';
     $order = '';
     $options['reset'] = 'reset';
     switch ($item->getType()) {
         case 'User':
             $restrict = "(`glpi_tickets_users`.`users_id` = '" . $item->getID() . "' " . " AND `glpi_tickets_users`.`type` = " . CommonITILActor::REQUESTER . ")";
             $order = '`glpi_tickets`.`date_mod` DESC';
             $options['reset'] = 'reset';
             $options['criteria'][0]['field'] = 4;
             // status
             $options['criteria'][0]['searchtype'] = 'equals';
             $options['criteria'][0]['value'] = $item->getID();
             $options['criteria'][0]['link'] = 'AND';
             break;
         case 'SLT':
             $restrict = "`slts_tto_id` = '" . $item->getID() . "'\n                           OR `slts_ttr_id` = '" . $item->getID() . "'";
             $order = '`glpi_tickets`.`due_date` DESC';
             $options['criteria'][0]['field'] = 30;
             $options['criteria'][0]['searchtype'] = 'equals';
             $options['criteria'][0]['value'] = $item->getID();
             $options['criteria'][0]['link'] = 'AND';
             break;
         case 'Supplier':
             $restrict = "(`glpi_suppliers_tickets`.`suppliers_id` = '" . $item->getID() . "' " . "  AND `glpi_suppliers_tickets`.`type` = " . CommonITILActor::ASSIGN . ")";
             $order = '`glpi_tickets`.`date_mod` DESC';
             $options['criteria'][0]['field'] = 6;
             $options['criteria'][0]['searchtype'] = 'equals';
             $options['criteria'][0]['value'] = $item->getID();
             $options['criteria'][0]['link'] = 'AND';
             break;
         case 'Group':
             // Mini search engine
             if ($item->haveChildren()) {
                 $tree = Session::getSavedOption(__CLASS__, 'tree', 0);
                 echo "<table class='tab_cadre_fixe'>";
                 echo "<tr class='tab_bg_1'><th>" . __('Last tickets') . "</th></tr>";
                 echo "<tr class='tab_bg_1'><td class='center'>";
                 echo __('Child groups') . "&nbsp;";
                 Dropdown::showYesNo('tree', $tree, -1, array('on_change' => 'reloadTab("start=0&tree="+this.value)'));
             } else {
                 $tree = 0;
             }
             echo "</td></tr></table>";
             if ($tree) {
                 $restrict = "IN (" . implode(',', getSonsOf('glpi_groups', $item->getID())) . ")";
             } else {
                 $restrict = "='" . $item->getID() . "'";
             }
             $restrict = "(`glpi_groups_tickets`.`groups_id` {$restrict}" . " AND `glpi_groups_tickets`.`type` = " . CommonITILActor::REQUESTER . ")";
             $order = '`glpi_tickets`.`date_mod` DESC';
             $options['criteria'][0]['field'] = 71;
             $options['criteria'][0]['searchtype'] = $tree ? 'under' : 'equals';
             $options['criteria'][0]['value'] = $item->getID();
             $options['criteria'][0]['link'] = 'AND';
             break;
         default:
             $restrict = "(`glpi_items_tickets`.`items_id` = '" . $item->getID() . "' " . " AND `glpi_items_tickets`.`itemtype` = '" . $item->getType() . "')";
             // you can only see your tickets
             if (!Session::haveRight(self::$rightname, self::READALL)) {
                 $restrict .= " AND (`glpi_tickets`.`users_id_recipient` = '" . Session::getLoginUserID() . "'\n                                   OR (`glpi_tickets_users`.`tickets_id` = '" . $item->getID() . "'\n                                       AND `glpi_tickets_users`.`users_id`\n                                            = '" . Session::getLoginUserID() . "'))";
             }
             $order = '`glpi_tickets`.`date_mod` DESC';
             $options['criteria'][0]['field'] = 12;
             $options['criteria'][0]['searchtype'] = 'equals';
             $options['criteria'][0]['value'] = 'all';
             $options['criteria'][0]['link'] = 'AND';
             $options['metacriteria'][0]['itemtype'] = $item->getType();
             $options['metacriteria'][0]['field'] = Search::getOptionNumber($item->getType(), 'id');
             $options['metacriteria'][0]['searchtype'] = 'equals';
             $options['metacriteria'][0]['value'] = $item->getID();
             $options['metacriteria'][0]['link'] = 'AND';
             break;
     }
     $query = "SELECT " . self::getCommonSelect() . "\n                FROM `glpi_tickets` " . self::getCommonLeftJoin() . "\n                WHERE {$restrict} " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n                ORDER BY {$order}\n                LIMIT " . intval($_SESSION['glpilist_limit']);
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     $colspan = 11;
     if (count($_SESSION["glpiactiveentities"]) > 1) {
         $colspan++;
     }
     // Ticket for the item
     echo "<div class='firstbloc'>";
     // Link to open a new ticket
     if ($item->getID() && Ticket::isPossibleToAssignType($item->getType()) && self::canCreate()) {
         Html::showSimpleForm($CFG_GLPI["root_doc"] . "/front/ticket.form.php", '_add_fromitem', __('New ticket for this item...'), array('itemtype' => $item->getType(), 'items_id' => $item->getID()));
     }
     echo "</div><div>";
     if ($number > 0) {
         echo "<table class='tab_cadre_fixehov'>";
         if (Session::haveRight(self::$rightname, self::READALL)) {
             Session::initNavigateListItems('Ticket', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName()));
             echo "<tr class='noHover'><th colspan='{$colspan}'>";
             $title = sprintf(_n('Last %d ticket', 'Last %d tickets', $number), $number);
             $link = "<a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "'>" . __('Show all') . "</a>";
             $title = printf(__('%1$s (%2$s)'), $title, $link);
             echo "</th></tr>";
         } else {
             echo "<tr><th colspan='{$colspan}'>" . __("You don't have right to see all tickets") . "</th></tr>";
         }
     } else {
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr><th>" . __('No ticket found.') . "</th></tr>";
     }
     if ($item->getID() && $item->getType() == 'User' && self::canCreate()) {
         echo "<tr><td class='tab_bg_2 center b' colspan='{$colspan}'>";
         Html::showSimpleForm($CFG_GLPI["root_doc"] . "/front/ticket.form.php", '_add_fromitem', __('New ticket for this item...'), array('_users_id_requester' => $item->getID()));
         echo "</td></tr>";
     }
     // Ticket list
     if ($number > 0) {
         self::commonListHeader(Search::HTML_OUTPUT);
         while ($data = $DB->fetch_assoc($result)) {
             Session::addToNavigateListItems('Ticket', $data["id"]);
             self::showShort($data["id"]);
         }
         self::commonListHeader(Search::HTML_OUTPUT);
     }
     echo "</table></div>";
     // Tickets for linked items
     $linkeditems = $item->getLinkedItems();
     $restrict = array();
     if (count($linkeditems)) {
         foreach ($linkeditems as $ltype => $tab) {
             foreach ($tab as $lID) {
                 $restrict[] = "(`glpi_items_tickets`.`itemtype` = '{$ltype}' AND `glpi_items_tickets`.`items_id` = '{$lID}')";
             }
         }
     }
     if (count($restrict) && Session::haveRight(self::$rightname, self::READALL)) {
         $query = "SELECT " . self::getCommonSelect() . "\n                   FROM `glpi_tickets` " . self::getCommonLeftJoin() . "\n                   WHERE " . implode(' OR ', $restrict) . getEntitiesRestrictRequest(' AND ', 'glpi_tickets') . "\n                   ORDER BY `glpi_tickets`.`date_mod` DESC\n                   LIMIT " . intval($_SESSION['glpilist_limit']);
         $result = $DB->query($query);
         $number = $DB->numrows($result);
         echo "<div class='spaced'><table class='tab_cadre_fixe'>";
         echo "<tr><th colspan='12'>";
         echo _n('Ticket on linked items', 'Tickets on linked items', $number);
         echo "</th></tr>";
         if ($number > 0) {
             self::commonListHeader(Search::HTML_OUTPUT);
             while ($data = $DB->fetch_assoc($result)) {
                 // Session::addToNavigateListItems(TRACKING_TYPE,$data["id"]);
                 self::showShort($data["id"]);
             }
             self::commonListHeader(Search::HTML_OUTPUT);
         } else {
             echo "<tr><th>" . __('No ticket found.') . "</th></tr>";
         }
         echo "</table></div>";
     }
     // Subquery for linked item
 }
 /**
  * Print the HTML array of Items on a budget
  *
  * @return Nothing (display)
  **/
 function showItems()
 {
     global $DB;
     $budgets_id = $this->fields['id'];
     if (!$this->can($budgets_id, READ)) {
         return false;
     }
     $query = "SELECT DISTINCT `itemtype`\n                FROM `glpi_infocoms`\n                WHERE `budgets_id` = '{$budgets_id}'\n                      AND itemtype NOT IN ('ConsumableItem', 'CartridgeItem', 'Software')\n               ORDER BY `itemtype`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     echo "<div class='spaced'><table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='2'>";
     Html::printPagerForm();
     echo "</th><th colspan='4'>";
     if ($DB->numrows($result) == 0) {
         _e('No associated item');
     } else {
         echo _n('Associated item', 'Associated items', $DB->numrows($result));
     }
     echo "</th></tr>";
     echo "<tr><th>" . __('Type') . "</th>";
     echo "<th>" . __('Entity') . "</th>";
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Serial number') . "</th>";
     echo "<th>" . __('Inventory number') . "</th>";
     echo "<th>" . _x('price', 'Value') . "</th>";
     echo "</tr>";
     $num = 0;
     $itemtypes = array();
     for ($i = 0; $i < $number; $i++) {
         $itemtypes[] = $DB->result($result, $i, "itemtype");
     }
     $itemtypes[] = 'Contract';
     $itemtypes[] = 'Ticket';
     $itemtypes[] = 'Problem';
     $itemtypes[] = 'Change';
     $itemtypes[] = 'Project';
     foreach ($itemtypes as $itemtype) {
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         if ($item->canView()) {
             switch ($itemtype) {
                 case 'Contract':
                     $query = "SELECT `" . $item->getTable() . "`.`id`,\n                                   `" . $item->getTable() . "`.`entities_id`,\n                                    SUM(`glpi_contractcosts`.`cost`) as value\n                            FROM `glpi_contractcosts`\n                            INNER JOIN `" . $item->getTable() . "`\n                                 ON (`" . $item->getTable() . "`.`id` = `glpi_contractcosts`.`contracts_id`)\n                            WHERE `glpi_contractcosts`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $item->getTable()) . "\n                                  AND NOT `" . $item->getTable() . "`.`is_template`\n                            GROUP BY `" . $item->getTable() . "`.`id`, `" . $item->getTable() . "`.`entities_id`\n                            ORDER BY `" . $item->getTable() . "`.`entities_id`,\n                                     `" . $item->getTable() . "`.`name`";
                     break;
                 case 'Ticket':
                 case 'Problem':
                 case 'Change':
                     $costtable = getTableForItemType($item->getType() . 'Cost');
                     $query = "SELECT `" . $item->getTable() . "`.`id`,\n                                   `" . $item->getTable() . "`.`entities_id`,\n                                    SUM(`{$costtable}`.`actiontime`*`{$costtable}`.`cost_time`/" . HOUR_TIMESTAMP . "\n                                          + `{$costtable}`.`cost_fixed`\n                                          + `{$costtable}`.`cost_material`) as value\n                            FROM `{$costtable}`\n                            INNER JOIN `" . $item->getTable() . "`\n                                 ON (`" . $item->getTable() . "`.`id` = `{$costtable}`.`" . $item->getForeignKeyField() . "`)\n                            WHERE `{$costtable}`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $item->getTable()) . "\n                            GROUP BY `" . $item->getTable() . "`.`id`, `" . $item->getTable() . "`.`entities_id`\n                            ORDER BY `" . $item->getTable() . "`.`entities_id`,\n                                     `" . $item->getTable() . "`.`name`";
                     break;
                 case 'Project':
                     $query = "SELECT `" . $item->getTable() . "`.`id`,\n                                   `" . $item->getTable() . "`.`entities_id`,\n                                    SUM(`glpi_projectcosts`.`cost`) as value\n                            FROM `glpi_projectcosts`\n                            INNER JOIN `" . $item->getTable() . "`\n                                 ON (`" . $item->getTable() . "`.`id` = `glpi_projectcosts`.`projects_id`)\n                            WHERE `glpi_projectcosts`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $item->getTable()) . "\n                            GROUP BY `" . $item->getTable() . "`.`id`, `" . $item->getTable() . "`.`entities_id`\n                            ORDER BY `" . $item->getTable() . "`.`entities_id`,\n                                     `" . $item->getTable() . "`.`name`";
                     break;
                 case 'Cartridge':
                     $query = "SELECT `" . $item->getTable() . "`.*,\n                                   `glpi_cartridgeitems`.`name`,\n                                   `glpi_infocoms`.`value`\n                            FROM `glpi_infocoms`\n                            INNER JOIN `" . $item->getTable() . "`\n                                 ON (`" . $item->getTable() . "`.`id` = `glpi_infocoms`.`items_id`)\n                            INNER JOIN `glpi_cartridgeitems`\n                                 ON (`" . $item->getTable() . "`.`cartridgeitems_id`\n                                       = `glpi_cartridgeitems`.`id`)\n                            WHERE `glpi_infocoms`.`itemtype`='{$itemtype}'\n                                  AND `glpi_infocoms`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $item->getTable()) . "\n                            ORDER BY `entities_id`,\n                                     `glpi_cartridgeitems`.`name`";
                     break;
                 case 'Consumable':
                     $query = "SELECT `" . $item->getTable() . "`.*,\n                                   `glpi_consumableitems`.`name`,\n                                   `glpi_infocoms`.`value`\n                            FROM `glpi_infocoms`\n                            INNER JOIN `" . $item->getTable() . "`\n                                 ON (`" . $item->getTable() . "`.`id` = `glpi_infocoms`.`items_id`)\n                            INNER JOIN `glpi_consumableitems`\n                                 ON (`" . $item->getTable() . "`.`consumableitems_id`\n                                       = `glpi_consumableitems`.`id`)\n                            WHERE `glpi_infocoms`.`itemtype` = '{$itemtype}'\n                                  AND `glpi_infocoms`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $item->getTable()) . "\n                            ORDER BY `entities_id`,\n                                     `glpi_consumableitems`.`name`";
                     break;
                 default:
                     $query = "SELECT `" . $item->getTable() . "`.*,\n                                   `glpi_infocoms`.`value`\n                            FROM `glpi_infocoms`\n                            INNER JOIN `" . $item->getTable() . "`\n                                 ON (`" . $item->getTable() . "`.`id` = `glpi_infocoms`.`items_id`)\n                            WHERE `glpi_infocoms`.`itemtype` = '{$itemtype}'\n                                  AND `glpi_infocoms`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $item->getTable()) . "\n                                  " . ($item->maybeTemplate() ? " AND NOT `" . $item->getTable() . "`.`is_template`" : '') . "\n                            ORDER BY `" . $item->getTable() . "`.`entities_id`,";
                     if ($item instanceof Item_Devices) {
                         $query .= " `" . $item->getTable() . "`.`itemtype`";
                     } else {
                         $query .= " `" . $item->getTable() . "`.`name`";
                     }
                     break;
             }
             if ($result_linked = $DB->query($query)) {
                 $nb = $DB->numrows($result_linked);
                 if ($nb > $_SESSION['glpilist_limit']) {
                     echo "<tr class='tab_bg_1'>";
                     $name = $item->getTypeName($nb);
                     //TRANS: %1$s is a name, %2$s is a number
                     echo "<td class='center'>" . sprintf(__('%1$s: %2$s'), $name, $nb) . "</td>";
                     echo "<td class='center' colspan='2'>";
                     $opt = array('order' => 'ASC', 'is_deleted' => 0, 'reset' => 'reset', 'start' => 0, 'sort' => 80, 'criteria' => array(0 => array('value' => '$$$$' . $budgets_id, 'searchtype' => 'contains', 'field' => 50)));
                     echo "<a href='" . $item->getSearchURL() . "?" . Toolbox::append_params($opt) . "'>" . __('Device list') . "</a></td>";
                     echo "<td class='center'>-</td><td class='center'>-</td><td class='center'>-" . "</td></tr>";
                 } else {
                     if ($nb) {
                         for ($prem = true; $data = $DB->fetch_assoc($result_linked); $prem = false) {
                             $name = NOT_AVAILABLE;
                             if ($item->getFromDB($data["id"])) {
                                 if ($item instanceof Item_Devices) {
                                     $tmpitem = new $item::$itemtype_2();
                                     if ($tmpitem->getFromDB($data[$item::$items_id_2])) {
                                         $name = $tmpitem->getLink(array('additional' => true));
                                     }
                                 } else {
                                     $name = $item->getLink(array('additional' => true));
                                 }
                             }
                             echo "<tr class='tab_bg_1'>";
                             if ($prem) {
                                 $typename = $item->getTypeName($nb);
                                 echo "<td class='center top' rowspan='{$nb}'>" . ($nb > 1 ? sprintf(__('%1$s: %2$s'), $typename, $nb) : $typename) . "</td>";
                             }
                             echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data["entities_id"]);
                             echo "</td><td class='center";
                             echo isset($data['is_deleted']) && $data['is_deleted'] ? " tab_bg_2_2'" : "'";
                             echo ">" . $name . "</td>";
                             echo "<td class='center'>" . (isset($data["serial"]) ? "" . $data["serial"] . "" : "-");
                             echo "</td>";
                             echo "<td class='center'>" . (isset($data["otherserial"]) ? "" . $data["otherserial"] . "" : "-") . "</td>";
                             echo "<td class='center'>" . (isset($data["value"]) ? "" . Html::formatNumber($data["value"], true) . "" : "-");
                             echo "</td></tr>";
                         }
                     }
                 }
                 $num += $nb;
             }
         }
     }
     if ($num > 0) {
         echo "<tr class='tab_bg_2'>";
         echo "<td class='center b'>" . sprintf(__('%1$s = %2$s'), __('Total'), $num) . "</td>";
         echo "<td colspan='5'>&nbsp;</td></tr> ";
     }
     echo "</table></div>";
 }
Esempio n. 6
0
 /**
  * clone of function Ticket::showFormHelpdesk()
  */
 static function getHelpdesk($ID = 0, $ticket_template = false)
 {
     global $DB, $CFG_GLPI;
     // * Added by plugin survey ticket
     $ticket = new Ticket();
     // * End of adding
     if (!Session::haveRight("create_ticket", "1")) {
         return false;
     }
     if (!$ticket_template && (Session::haveRight('validate_incident', 1) || Session::haveRight('validate_request', 1))) {
         $opt = array();
         $opt['reset'] = 'reset';
         $opt['field'][0] = 55;
         // validation status
         $opt['searchtype'][0] = 'equals';
         $opt['contains'][0] = 'waiting';
         $opt['link'][0] = 'AND';
         $opt['field'][1] = 59;
         // validation aprobator
         $opt['searchtype'][1] = 'equals';
         $opt['contains'][1] = Session::getLoginUserID();
         $opt['link'][1] = 'AND';
         $url_validate = $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($opt, '&amp;');
         if (TicketValidation::getNumberTicketsToValidate(Session::getLoginUserID()) > 0) {
             echo "<a href='{$url_validate}' title=\"" . __s('Ticket waiting for your approval') . "\"\n                   alt=\"" . __s('Ticket waiting for your approval') . "\">" . __('Tickets awaiting approval') . "</a><br><br>";
         }
     }
     $query = "SELECT `realname`, `firstname`, `name`\n                FROM `glpi_users`\n                WHERE `id` = '{$ID}'";
     $result = $DB->query($query);
     $email = UserEmail::getDefaultForUser($ID);
     // Set default values...
     $default_values = array('_users_id_requester_notif' => array('use_notification' => $email == "" ? 0 : 1), 'nodelegate' => 1, '_users_id_requester' => 0, 'name' => '', 'content' => '', 'itilcategories_id' => 0, 'locations_id' => 0, 'urgency' => 3, 'itemtype' => '', 'items_id' => 0, 'entities_id' => $_SESSION['glpiactive_entity'], 'plan' => array(), 'global_validation' => 'none', 'due_date' => 'NULL', 'slas_id' => 0, '_add_validation' => 0, 'type' => Entity::getUsedConfig('tickettype', $_SESSION['glpiactive_entity'], '', Ticket::INCIDENT_TYPE), '_right' => "id");
     // Get default values from posted values on reload form
     if (!$ticket_template) {
         if (isset($_POST)) {
             $values = $_POST;
         }
     }
     // Restore saved value or override with page parameter
     $saved = $ticket->restoreInput();
     foreach ($default_values as $name => $value) {
         if (!isset($values[$name])) {
             if (isset($saved[$name])) {
                 $values[$name] = $saved[$name];
             } else {
                 $values[$name] = $value;
             }
         }
     }
     if (!$ticket_template) {
         echo "<form method='post' name='helpdeskform' action='" . $CFG_GLPI["root_doc"] . "/front/tracking.injector.php' enctype='multipart/form-data'>";
     }
     $delegating = User::getDelegateGroupsForUser($values['entities_id']);
     if (count($delegating)) {
         echo "<div class='center'><table class='tab_cadre_fixe'>";
         echo "<tr><th colspan='2'>" . __('This ticket concerns me') . " ";
         $rand = Dropdown::showYesNo("nodelegate", $values['nodelegate']);
         $params = array('nodelegate' => '__VALUE__', 'rand' => $rand, 'right' => "delegate", '_users_id_requester' => $values['_users_id_requester'], '_users_id_requester_notif' => $values['_users_id_requester_notif'], 'use_notification' => $values['_users_id_requester_notif']['use_notification'], 'entity_restrict' => $_SESSION["glpiactive_entity"]);
         Ajax::UpdateItemOnSelectEvent("dropdown_nodelegate" . $rand, "show_result" . $rand, $CFG_GLPI["root_doc"] . "/ajax/dropdownDelegationUsers.php", $params);
         if ($CFG_GLPI['use_check_pref'] && $values['nodelegate']) {
             echo "</th><th>" . __('Check your personnal information');
         }
         echo "</th></tr>";
         echo "<tr class='tab_bg_1'><td colspan='2' class='center'>";
         echo "<div id='show_result{$rand}'>";
         $self = new Ticket();
         if ($values["_users_id_requester"] == 0) {
             $values['_users_id_requester'] = Session::getLoginUserID();
         } else {
             $values['_right'] = "delegate";
         }
         $self->showActorAddFormOnCreate(CommonITILActor::REQUESTER, $values);
         echo "</div>";
         if ($CFG_GLPI['use_check_pref'] && $values['nodelegate']) {
             echo "</td><td class='center'>";
             User::showPersonalInformation(Session::getLoginUserID());
         }
         echo "</td></tr>";
         echo "</table></div>";
         echo "<input type='hidden' name='_users_id_recipient' value='" . Session::getLoginUserID() . "'>";
     } else {
         // User as requester
         $values['_users_id_requester'] = Session::getLoginUserID();
         if ($CFG_GLPI['use_check_pref']) {
             echo "<div class='center'><table class='tab_cadre_fixe'>";
             echo "<tr><th>" . __('Check your personnal information') . "</th></tr>";
             echo "<tr class='tab_bg_1'><td class='center'>";
             User::showPersonalInformation(Session::getLoginUserID());
             echo "</td></tr>";
             echo "</table></div>";
         }
     }
     echo "<input type='hidden' name='_from_helpdesk' value='1'>";
     echo "<input type='hidden' name='requesttypes_id' value='" . RequestType::getDefault('helpdesk') . "'>";
     // Load ticket template if available :
     $tt = $ticket->getTicketTemplateToUse($ticket_template, $values['type'], $values['itilcategories_id'], $_SESSION["glpiactive_entity"]);
     // Predefined fields from template : reset them
     if (isset($values['_predefined_fields'])) {
         $values['_predefined_fields'] = Toolbox::decodeArrayFromInput($values['_predefined_fields']);
     } else {
         $values['_predefined_fields'] = array();
     }
     // Store predefined fields to be able not to take into account on change template
     $predefined_fields = array();
     if (isset($tt->predefined) && count($tt->predefined)) {
         foreach ($tt->predefined as $predeffield => $predefvalue) {
             if (isset($values[$predeffield]) && isset($default_values[$predeffield])) {
                 // Is always default value : not set
                 // Set if already predefined field
                 // Set if ticket template change
                 if ($values[$predeffield] == $default_values[$predeffield] || isset($values['_predefined_fields'][$predeffield]) && $values[$predeffield] == $values['_predefined_fields'][$predeffield] || isset($values['_tickettemplates_id']) && $values['_tickettemplates_id'] != $tt->getID()) {
                     $values[$predeffield] = $predefvalue;
                     $predefined_fields[$predeffield] = $predefvalue;
                 }
             } else {
                 // Not defined options set as hidden field
                 echo "<input type='hidden' name='{$predeffield}' value='{$predefvalue}'>";
             }
         }
     } else {
         // No template load : reset predefined values
         if (count($values['_predefined_fields'])) {
             foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) {
                 if ($values[$predeffield] == $predefvalue) {
                     $values[$predeffield] = $default_values[$predeffield];
                 }
             }
         }
     }
     if ($CFG_GLPI['urgency_mask'] == 1 << 3 || $tt->isHiddenField('urgency')) {
         // Dont show dropdown if only 1 value enabled or field is hidden
         echo "<input type='hidden' name='urgency' value='" . $values['urgency'] . "'>";
     }
     // Display predefined fields if hidden
     if ($tt->isHiddenField('itemtype')) {
         echo "<input type='hidden' name='itemtype' value='" . $values['itemtype'] . "'>";
         echo "<input type='hidden' name='items_id' value='" . $values['items_id'] . "'>";
     }
     if ($tt->isHiddenField('locations_id')) {
         echo "<input type='hidden' name='locations_id' value='" . $values['locations_id'] . "'>";
     }
     echo "<input type='hidden' name='entities_id' value='" . $_SESSION["glpiactive_entity"] . "'>";
     echo "<div class='center'><table class='tab_cadre_fixe'>";
     echo "<tr><th>" . __('Describe the incident or request') . "</th><th>";
     if (Session::isMultiEntitiesMode()) {
         echo "(" . Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]) . ")";
     }
     echo "</th></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . sprintf(__('%1$s%2$s'), __('Type'), $tt->getMandatoryMark('type')) . "</td>";
     echo "<td>";
     Ticket::dropdownType('type', array('value' => $values['type'], 'on_change' => 'submit()'));
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . sprintf(__('%1$s%2$s'), __('Category'), $tt->getMandatoryMark('itilcategories_id')) . "</td>";
     echo "<td>";
     $condition = "`is_helpdeskvisible`='1'";
     switch ($values['type']) {
         case Ticket::DEMAND_TYPE:
             $condition .= " AND `is_request`='1'";
             break;
         default:
             // Ticket::INCIDENT_TYPE :
             $condition .= " AND `is_incident`='1'";
     }
     $opt = array('value' => $values['itilcategories_id'], 'condition' => $condition, 'on_change' => 'submit()');
     if ($values['itilcategories_id'] && $tt->isMandatoryField("itilcategories_id")) {
         $opt['display_emptychoice'] = false;
     }
     ITILCategory::dropdown($opt);
     echo "</td></tr>";
     if ($CFG_GLPI['urgency_mask'] != 1 << 3) {
         if (!$tt->isHiddenField('urgency')) {
             echo "<tr class='tab_bg_1'>";
             echo "<td>" . sprintf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency')) . "</td>";
             echo "<td>";
             Ticket::dropdownUrgency(array('value' => $values["urgency"]));
             echo "</td></tr>";
         }
     }
     if (empty($delegating) && NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . __('Inform me about the actions taken') . "</td>";
         echo "<td>";
         if ($values["_users_id_requester"] == 0) {
             $values['_users_id_requester'] = Session::getLoginUserID();
         }
         $_POST['value'] = $values['_users_id_requester'];
         $_POST['field'] = '_users_id_requester_notif';
         $_POST['use_notification'] = $values['_users_id_requester_notif']['use_notification'];
         include GLPI_ROOT . "/ajax/uemailUpdate.php";
         echo "</td></tr>";
     }
     if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) {
         if (!$tt->isHiddenField('itemtype')) {
             echo "<tr class='tab_bg_1'>";
             echo "<td>" . sprintf(__('%1$s%2$s'), __('Hardware type'), $tt->getMandatoryMark('itemtype')) . "</td>";
             echo "<td>";
             Ticket::dropdownMyDevices($values['_users_id_requester'], $_SESSION["glpiactive_entity"], $values['itemtype'], $values['items_id']);
             Ticket::dropdownAllDevices("itemtype", $values['itemtype'], $values['items_id'], 0, $values['_users_id_requester'], $_SESSION["glpiactive_entity"]);
             echo "<span id='item_ticket_selection_information'></span>";
             echo "</td></tr>";
         }
     }
     if (!$tt->isHiddenField('locations_id')) {
         echo "<tr class='tab_bg_1'><td>";
         printf(__('%1$s%2$s'), __('Location'), $tt->getMandatoryMark('locations_id'));
         echo "</td><td>";
         Location::dropdown(array('value' => $values["locations_id"]));
         echo "</td></tr>";
     }
     if (!$tt->isHiddenField('name') || $tt->isPredefinedField('name')) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . sprintf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name')) . "</td>";
         echo "<td><input type='text' maxlength='250' size='80' name='name'\n                    value=\"" . $values['name'] . "\"></td></tr>";
     }
     if (!$tt->isHiddenField('content') || $tt->isPredefinedField('content')) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . sprintf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content')) . "</td>";
         // * Changed by plugin surveyticket
         // * Added by plugin surveyticket
         $psTicketTemplate = new PluginSurveyticketTicketTemplate();
         $psSurvey = new PluginSurveyticketSurvey();
         $plugin_surveyticket_surveys_id = 0;
         $a_tickettemplates = current($psTicketTemplate->find("`tickettemplates_id`='" . $tt->fields['id'] . "'\n                                                      AND `type`='" . $values['type'] . "'\n                                                      AND `is_helpdesk`='1'"));
         if (isset($a_tickettemplates['plugin_surveyticket_surveys_id'])) {
             echo "<td>";
             $psSurvey = new PluginSurveyticketSurvey();
             $psSurvey->getFromDB($a_tickettemplates['plugin_surveyticket_surveys_id']);
             if ($psSurvey->fields['is_active'] == 1) {
                 $plugin_surveyticket_surveys_id = $a_tickettemplates['plugin_surveyticket_surveys_id'];
                 $psSurvey = new PluginSurveyticketSurvey();
                 $psSurvey->startSurvey($plugin_surveyticket_surveys_id);
             }
         } else {
             echo "<td><textarea name='content' cols='80' rows='14'>" . $values['content'] . "</textarea>";
         }
         // * End of change
         echo "</td></tr>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . sprintf(__('%1$s (%2$s)'), __('File'), Document::getMaxUploadSize());
     echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/aide.png' class='pointer' alt='" . __s('Help') . "' onclick=\"window.open('" . $CFG_GLPI["root_doc"] . "/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,height=800')\">";
     echo "&nbsp;";
     Ticket::showDocumentAddButton(60);
     echo "</td>";
     echo "<td><div id='uploadfiles'><input type='file' name='filename[]' value='' size='60'></div>";
     echo "</td></tr>";
     if (!$ticket_template) {
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='2' class='center'>";
         if ($tt->isField('id') && $tt->fields['id'] > 0) {
             echo "<input type='hidden' name='_tickettemplates_id' value='" . $tt->fields['id'] . "'>";
             echo "<input type='hidden' name='_predefined_fields'\n                   value=\"" . Toolbox::prepareArrayForInput($predefined_fields) . "\">";
         }
         echo "<input type='submit' name='add' value=\"" . __s('Submit message') . "\" class='submit'>";
         echo "</td></tr>";
     }
     echo "</table></div>";
     if (!$ticket_template) {
         Html::closeForm();
     }
 }
Esempio n. 7
0
 /**
  * Get problems count
  *
  * @since version 0.84
  *
  * @param $foruser boolean : only for current login user as requester (false by default)
  **/
 static function showCentralCount($foruser = false)
 {
     global $DB, $CFG_GLPI;
     // show a tab with count of jobs in the central and give link
     if (!Session::haveRight("show_all_problem", "1") && !Session::haveRight("show_my_problem", 1)) {
         return false;
     }
     if (!Session::haveRight("show_all_problem", "1")) {
         $foruser = true;
     }
     $query = "SELECT `status`,\n                       COUNT(*) AS COUNT\n                FROM `glpi_problems` ";
     if ($foruser) {
         $query .= " LEFT JOIN `glpi_problems_users`\n                        ON (`glpi_problems`.`id` = `glpi_problems_users`.`problems_id`\n                            AND `glpi_problems_users`.`type` = '" . CommonITILActor::REQUESTER . "')";
         if (isset($_SESSION["glpigroups"]) && count($_SESSION["glpigroups"])) {
             $query .= " LEFT JOIN `glpi_groups_problems`\n                           ON (`glpi_problems`.`id` = `glpi_groups_problems`.`problems_id`\n                               AND `glpi_groups_problems`.`type` = '" . CommonITILActor::REQUESTER . "')";
         }
     }
     $query .= getEntitiesRestrictRequest("WHERE", "glpi_problems");
     if ($foruser) {
         $query .= " AND (`glpi_problems_users`.`users_id` = '" . Session::getLoginUserID() . "' ";
         if (isset($_SESSION["glpigroups"]) && count($_SESSION["glpigroups"])) {
             $groups = implode("','", $_SESSION['glpigroups']);
             $query .= " OR `glpi_groups_problems`.`groups_id` IN ('{$groups}') ";
         }
         $query .= ")";
     }
     $query_deleted = $query;
     $query .= " AND NOT `glpi_problems`.`is_deleted`\n                         GROUP BY `status`";
     $query_deleted .= " AND `glpi_problems`.`is_deleted`\n                         GROUP BY `status`";
     $result = $DB->query($query);
     $result_deleted = $DB->query($query_deleted);
     $status = array();
     foreach (self::getAllStatusArray() as $key => $val) {
         $status[$key] = 0;
     }
     if ($DB->numrows($result) > 0) {
         while ($data = $DB->fetch_assoc($result)) {
             $status[$data["status"]] = $data["COUNT"];
         }
     }
     $number_deleted = 0;
     if ($DB->numrows($result_deleted) > 0) {
         while ($data = $DB->fetch_assoc($result_deleted)) {
             $number_deleted += $data["COUNT"];
         }
     }
     $options['field'][0] = 12;
     $options['searchtype'][0] = 'equals';
     $options['contains'][0] = 'process';
     $options['link'][0] = 'AND';
     $options['reset'] = 'reset';
     echo "<table class='tab_cadrehov' >";
     echo "<tr><th colspan='2'>";
     echo "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Problem followup') . "</a>";
     echo "</th></tr>";
     echo "<tr><th>" . _n('Problem', 'Problems', 2) . "</th><th>" . _x('quantity', 'Number') . "</th></tr>";
     foreach ($status as $key => $val) {
         $options['contains'][0] = $key;
         echo "<tr class='tab_bg_2'>";
         echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">" . self::getStatus($key) . "</a></td>";
         echo "<td class='numeric'>{$val}</td></tr>";
     }
     $options['contains'][0] = 'all';
     $options['is_deleted'] = 1;
     echo "<tr class='tab_bg_2'>";
     echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Deleted') . "</a></td>";
     echo "<td class='numeric'>" . $number_deleted . "</td></tr>";
     echo "</table><br>";
 }
Esempio n. 8
0
 /**
  * Show central contract resume
  * HTML array
  *
  * @return Nothing (display)
  **/
 static function showCentral()
 {
     global $DB, $CFG_GLPI;
     if (!Contract::canView()) {
         return false;
     }
     // No recursive contract, not in local management
     // contrats echus depuis moins de 30j
     $query = "SELECT COUNT(*)\n                FROM `glpi_contracts`\n                WHERE `glpi_contracts`.`is_deleted`='0' " . getEntitiesRestrictRequest("AND", "glpi_contracts") . "\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           `glpi_contracts`.`duration` MONTH),CURDATE() )>-30\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           `glpi_contracts`.`duration` MONTH),CURDATE() )<'0'";
     $result = $DB->query($query);
     $contract0 = $DB->result($result, 0, 0);
     // contrats  echeance j-7
     $query = "SELECT COUNT(*)\n                FROM `glpi_contracts`\n                WHERE `glpi_contracts`.`is_deleted`='0' " . getEntitiesRestrictRequest("AND", "glpi_contracts") . "\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           `glpi_contracts`.`duration` MONTH),CURDATE() )>'0'\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           `glpi_contracts`.`duration` MONTH),CURDATE() )<='7'";
     $result = $DB->query($query);
     $contract7 = $DB->result($result, 0, 0);
     // contrats echeance j -30
     $query = "SELECT COUNT(*)\n                FROM `glpi_contracts`\n                WHERE `glpi_contracts`.`is_deleted`='0' " . getEntitiesRestrictRequest("AND", "glpi_contracts") . "\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           `glpi_contracts`.`duration` MONTH),CURDATE() )>'7'\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           `glpi_contracts`.`duration` MONTH),CURDATE() )<'30'";
     $result = $DB->query($query);
     $contract30 = $DB->result($result, 0, 0);
     // contrats avec préavis echeance j-7
     $query = "SELECT COUNT(*)\n                FROM `glpi_contracts`\n                WHERE `glpi_contracts`.`is_deleted`='0' " . getEntitiesRestrictRequest("AND", "glpi_contracts") . "\n                      AND `glpi_contracts`.`notice`<>'0'\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           (`glpi_contracts`.`duration`-`glpi_contracts`.`notice`)\n                                           MONTH),CURDATE() )>'0'\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           (`glpi_contracts`.`duration`-`glpi_contracts`.`notice`)\n                                           MONTH),CURDATE() )<='7'";
     $result = $DB->query($query);
     $contractpre7 = $DB->result($result, 0, 0);
     // contrats avec préavis echeance j -30
     $query = "SELECT COUNT(*)\n                FROM `glpi_contracts`\n                WHERE `glpi_contracts`.`is_deleted`='0'" . getEntitiesRestrictRequest("AND", "glpi_contracts") . "\n                      AND `glpi_contracts`.`notice`<>'0'\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           (`glpi_contracts`.`duration`-`glpi_contracts`.`notice`)\n                                           MONTH),CURDATE() )>'7'\n                      AND DATEDIFF(ADDDATE(`glpi_contracts`.`begin_date`, INTERVAL\n                                           (`glpi_contracts`.`duration`-`glpi_contracts`.`notice`)\n                                           MONTH),CURDATE() )<'30'";
     $result = $DB->query($query);
     $contractpre30 = $DB->result($result, 0, 0);
     echo "<table class='tab_cadrehov'>";
     echo "<tr class='noHover'><th colspan='2'>";
     echo "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/contract.php?reset=reset\">" . self::getTypeName(1) . "</a></th></tr>";
     echo "<tr class='tab_bg_2'>";
     $options['reset'] = 'reset';
     $options['sort'] = 12;
     $options['order'] = 'DESC';
     $options['start'] = 0;
     $options['criteria'][0] = array('field' => 12, 'value' => '<0', 'searchtype' => 'contains');
     $options['criteria'][1] = array('field' => 12, 'link' => 'AND', 'value' => '>-30', 'searchtype' => 'contains');
     echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/contract.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Contracts expired in the last 30 days') . "</a> </td>";
     echo "<td class='numeric'>" . $contract0 . "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     $options['criteria'][0]['value'] = 0;
     $options['criteria'][1]['value'] = '<7';
     echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/contract.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Contracts expiring in less than 7 days') . "</a></td>";
     echo "<td class='numeric'>" . $contract7 . "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     $options['criteria'][0]['value'] = '>6';
     $options['criteria'][1]['value'] = '<30';
     echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/contract.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Contracts expiring in less than 30 days') . "</a></td>";
     echo "<td class='numeric'>" . $contract30 . "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     $options['criteria'][0]['field'] = 13;
     $options['criteria'][0]['value'] = '>0';
     $options['criteria'][1]['field'] = 13;
     $options['criteria'][1]['value'] = '<7';
     echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/contract.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Contracts where notice begins in less than 7 days') . "</a></td>";
     echo "<td class='numeric'>" . $contractpre7 . "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     $options['criteria'][0]['value'] = '>6';
     $options['criteria'][1]['value'] = '<30';
     echo "<td><a href=\"" . $CFG_GLPI["root_doc"] . "/front/contract.php?" . Toolbox::append_params($options, '&amp;') . "\">" . __('Contracts where notice begins in less than 30 days') . "</a></td>";
     echo "<td class='numeric'>" . $contractpre30 . "</td></tr>";
     echo "</table>";
 }
Esempio n. 9
0
 /**
  * Show onglets
  *
  * @param $options array of parameters to add to URLs and ajax
  *     - withtemplate is a template view ?
  *
  * @return Nothing ()
  **/
 function showTabs($options = array())
 {
     global $CFG_GLPI;
     // for objects not in table like central
     if (isset($this->fields['id'])) {
         $ID = $this->fields['id'];
     } else {
         $ID = 0;
     }
     $target = $_SERVER['PHP_SELF'];
     $extraparamhtml = "";
     $extraparam = "";
     $withtemplate = "";
     if (is_array($options) && count($options)) {
         if (isset($options['withtemplate'])) {
             $withtemplate = $options['withtemplate'];
         }
         $extraparamhtml = "&amp;" . Toolbox::append_params($options, '&amp;');
         $extraparam = "&" . Toolbox::append_params($options);
         //          foreach ($options as $key => $val) {
         //             // Do not include id options
         //             if (($key[0] != '_') && ($key != 'id')) {
         //                $extraparamhtml .= "&amp;$key=$val";
         //                $extraparam     .= "&$key=$val";
         //             }
         //          }
     }
     if (empty($withtemplate) && !$this->isNewID($ID) && $this->getType() && $this->displaylist) {
         $glpilistitems =& $_SESSION['glpilistitems'][$this->getType()];
         $glpilisttitle =& $_SESSION['glpilisttitle'][$this->getType()];
         $glpilisturl =& $_SESSION['glpilisturl'][$this->getType()];
         if (empty($glpilisturl)) {
             $glpilisturl = $this->getSearchURL();
         }
         echo "<div id='menu_navigate'>";
         $next = $prev = $first = $last = -1;
         $current = false;
         if (is_array($glpilistitems)) {
             $current = array_search($ID, $glpilistitems);
             if ($current !== false) {
                 if (isset($glpilistitems[$current + 1])) {
                     $next = $glpilistitems[$current + 1];
                 }
                 if (isset($glpilistitems[$current - 1])) {
                     $prev = $glpilistitems[$current - 1];
                 }
                 $first = $glpilistitems[0];
                 if ($first == $ID) {
                     $first = -1;
                 }
                 $last = $glpilistitems[count($glpilistitems) - 1];
                 if ($last == $ID) {
                     $last = -1;
                 }
             }
         }
         $cleantarget = HTML::cleanParametersURL($target);
         echo "<ul>";
         //          echo "<li><a href=\"javascript:showHideDiv('tabsbody','tabsbodyimg','".$CFG_GLPI["root_doc"].
         //                     "/pics/deplier_down.png','".$CFG_GLPI["root_doc"]."/pics/deplier_up.png')\">";
         //          echo "<img alt='' name='tabsbodyimg' src=\"".$CFG_GLPI["root_doc"]."/pics/deplier_up.png\">";
         //          echo "</a></li>";
         echo "<li><a href=\"javascript:toggleTableDisplay('mainformtable','tabsbodyimg','" . $CFG_GLPI["root_doc"] . "/pics/deplier_down.png','" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png')\">";
         echo "<img alt='' name='tabsbodyimg' src=\"" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png\">";
         echo "</a></li>";
         echo "<li><a href=\"" . $glpilisturl . "\">";
         if ($glpilisttitle) {
             if (Toolbox::strlen($glpilisttitle) > $_SESSION['glpidropdown_chars_limit']) {
                 $glpilisttitle = Toolbox::substr($glpilisttitle, 0, $_SESSION['glpidropdown_chars_limit']) . "&hellip;";
             }
             echo $glpilisttitle;
         } else {
             _e('List');
         }
         echo "</a></li>";
         if ($first >= 0) {
             echo "<li><a href='{$cleantarget}?id={$first}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/first.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/first_off.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\"></li>";
         }
         if ($prev >= 0) {
             echo "<li><a href='{$cleantarget}?id={$prev}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/left.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/left_off.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\"></li>";
         }
         if ($current !== false) {
             echo "<li>" . ($current + 1) . "/" . count($glpilistitems) . "</li>";
         }
         if ($next >= 0) {
             echo "<li><a href='{$cleantarget}?id={$next}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/right.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/right_off.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\"></li>";
         }
         if ($last >= 0) {
             echo "<li><a href='{$cleantarget}?id={$last}{$extraparamhtml}'><img src=\"" . $CFG_GLPI["root_doc"] . "/pics/last.png\" alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/last_off.png' alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\"></li>";
         }
         echo "</ul></div>";
         echo "<div class='sep'></div>";
     }
     echo "<div id='tabspanel' class='center-h'></div>";
     $onglets = $this->defineAllTabs($options);
     $display_all = true;
     if (isset($onglets['no_all_tab'])) {
         $display_all = false;
         unset($onglets['no_all_tab']);
     }
     $class = $this->getType();
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && ($ID > 0 || $this->showdebug) && (method_exists($class, 'showDebug') || in_array($class, $CFG_GLPI["infocom_types"]) || in_array($class, $CFG_GLPI["reservation_types"]))) {
         $onglets[-2] = __('Debug');
     }
     if (count($onglets)) {
         $tabpage = $this->getTabsURL();
         $tabs = array();
         foreach ($onglets as $key => $val) {
             $tabs[$key] = array('title' => $val, 'url' => $tabpage, 'params' => "target={$target}&itemtype=" . $this->getType() . "&glpi_tab={$key}&id={$ID}{$extraparam}");
         }
         // Not all tab for templates and if only 1 tab
         if ($display_all && empty($withtemplate) && count($tabs) > 1) {
             $tabs[-1] = array('title' => __('All'), 'url' => $tabpage, 'params' => "target={$target}&itemtype=" . $this->getType() . "&glpi_tab=-1&id={$ID}{$extraparam}");
         }
         Ajax::createTabs('tabspanel', 'tabcontent', $tabs, $this->getType());
     }
 }
Esempio n. 10
0
 static function showCentralSpecificList($type)
 {
     global $CFG_GLPI, $DB;
     if (!Session::haveRight("show_all_ticket", "1") && !Session::haveRight("show_assign_ticket", "1") && !Session::haveRight("create_ticket", "1") && !Session::haveRight("validate_ticket", "1")) {
         return false;
     }
     $groups = implode("','", $_SESSION['glpigroups']);
     $numrows = 0;
     $is_deleted = " `glpi_tickets`.`is_deleted` = 0 ";
     if ($type == "notold") {
         $title = __("Tickets to follow (climbed)", "escalade");
         $status = CommonITILObject::INCOMING . ", " . CommonITILObject::PLANNED . ", " . CommonITILObject::ASSIGNED . ", " . CommonITILObject::WAITING;
         $search_assign = " `glpi_plugin_escalade_histories`.`groups_id` IN ('{$groups}')\n            AND (`glpi_groups_tickets`.`groups_id` NOT IN ('{$groups}')\n            OR `glpi_groups_tickets`.`groups_id` IS NULL)";
         $query_join = "LEFT JOIN `glpi_plugin_escalade_histories`\n            ON (`glpi_tickets`.`id` = `glpi_plugin_escalade_histories`.`tickets_id`)\n         LEFT JOIN `glpi_groups_tickets`\n            ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id` \n               AND `glpi_groups_tickets`.`type`=2)";
     } else {
         $title = __("Tickets to close (climbed)", "escalade");
         $status = CommonITILObject::SOLVED;
         $search_assign = " (`glpi_groups_tickets`.`groups_id` IN ('{$groups}'))";
         $query_join = "LEFT JOIN `glpi_groups_tickets`\n            ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id` \n               AND `glpi_groups_tickets`.`type`=2)";
     }
     $query = "SELECT DISTINCT `glpi_tickets`.`id`\n      FROM `glpi_tickets`\n      LEFT JOIN `glpi_tickets_users`\n         ON (`glpi_tickets`.`id` = `glpi_tickets_users`.`tickets_id`)";
     $query .= $query_join;
     $query .= "WHERE {$is_deleted} AND ( {$search_assign} )\n                            AND (`status` IN ({$status}))" . getEntitiesRestrictRequest("AND", "glpi_tickets");
     $query .= " ORDER BY glpi_tickets.date_mod DESC";
     $result = $DB->query($query);
     $numrows = $DB->numrows($result);
     if (!$numrows) {
         return;
     }
     $query .= " LIMIT 0, 5";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     //show central list
     if ($numrows > 0) {
         //construct link to ticket list
         $options['reset'] = 'reset';
         $num = 0;
         foreach ($_SESSION['glpigroups'] as $gID) {
             $options['field'][$num] = 8;
             if ($type == "notold") {
                 $options['searchtype'][$num] = 'notequals';
                 $options['contains'][$num] = $gID;
                 $options['link'][$num] = $num == 0 ? 'AND' : 'OR';
                 $num++;
                 $options['field'][$num] = 1881;
                 //see hook.php, function ..._getAddSearchOptions
             }
             $options['searchtype'][$num] = 'equals';
             $options['contains'][$num] = $gID;
             if ($type == "notold") {
                 $options['link'][$num] = 'AND';
             } else {
                 $options['link'][$num] = $num == 0 ? 'AND' : 'OR';
             }
             $num++;
             $options['field'][$num] = 12;
             // status
             $options['searchtype'][$num] = 'equals';
             $options['contains'][$num] = $type;
             $options['link'][$num] = 'AND';
             $num++;
         }
         echo "<table><tr><td class='top' width='450px'>";
         echo "<table class='tab_cadrehov' id='pluginEscaladeCentralList' style='width:420px'>";
         echo "<tr><th colspan='5'>";
         echo "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">" . Html::makeTitle($title, $number, $numrows) . "</a>";
         echo "</a>";
         echo "</th></tr>";
         if ($number) {
             echo "<tr><th></th>";
             echo "<th>" . __('Requester') . "</th>";
             echo "<th>" . __('Associated element') . "</th>";
             echo "<th>" . __('Description') . "</th></tr>";
             for ($i = 0; $i < $number; $i++) {
                 $ID = $DB->result($result, $i, "id");
                 Ticket::showVeryShort($ID, 'Ticket$2');
             }
         }
         echo "</table>";
         echo "</td></tr></table>";
     }
 }
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI, $LANG, $PLUGIN_HOOKS;
     $searchopt =& Search::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         return PluginMobileSearch::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     switch ($table . '.' . $field) {
         case "glpi_users_validation.name":
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserNameMobile($split[$k], 2);
                             $out .= $userdata['name'] . "&nbsp;";
                         } else {
                             $out .= getUserNameMobile($split[$k], 1);
                         }
                     }
                 }
                 return $out;
             } else {
                 if (!empty($linkfield)) {
                     $toadd = '';
                     if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                         $userdata = getUserNameMobile($data[$NAME . $num . "_3"], 2);
                         $toadd = "&nbsp;";
                     }
                     //Stevenes
                     $name1 = explode("\$\$", $data[$NAME . $num]);
                     //	return $name1['0'].' ('.$name1['1'].')';
                     $link_user = $_SESSION['mobileSearchLastLink'] = "<a href=" . $CFG_GLPI["root_doc"] . "/plugins/mobile/front/item.php?itemtype=user&menu=admin&ssmenu=user&id=" . $name1['1'] . ">" . $name1['0'] . " (" . $name1['1'] . ")</a>";
                     return $link_user;
                     // return formatUserNameMobile($data[$NAME.$num."_3"],$data[$NAME.$num],$data[$NAME.$num."_2"], $data[$NAME.$num."_4"],1).$toadd;
                 }
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
             break;
         case "glpi_profiles.name":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . $split2[$k];
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . $split2[$k];
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             } else {
                 if ($data[$NAME . $num . "_2"] == 0) {
                     // Set name for Root entity
                     $data[$NAME . $num] = $LANG['entity'][2];
                 }
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . $duration . " " . $LANG['financial'][57];
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
         case "glpi_infocoms.sink_time":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][9];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.warranty_duration":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][57];
                     }
                     if ($val < 0) {
                         $out .= $LANG['financial'][2];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return $LANG['financial'][80];
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return $LANG['buttons'][32];
                 case pow(2, Alert::NOTICE):
                     return $LANG['financial'][10];
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return $LANG['buttons'][32] . " + " . $LANG['financial'][10];
             }
             return "";
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                 $options['field'][0] = 12;
                 $options['searchtype'][0] = 'equals';
                 $options['contains'][0] = 'all';
                 $options['link'][0] = 'AND';
                 $options['itemtype2'][0] = $itemtype;
                 $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                 $options['searchtype2'][0] = 'equals';
                 $options['contains2'][0] = $data['id'];
                 $options['link2'][0] = 'AND';
                 $options['reset'] = 'reset';
                 $out = "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options) . "\" data-back='false'>";
                 $out .= $data[$NAME . $num];
                 $out .= "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return $LANG['software'][4];
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title='" . $LANG['reservation'][22] . "'\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' data-back='false'>" . $LANG['common'][49] . "</a>";
             }
             return "<a title='" . $LANG['reservation'][22] . "'\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' data-back='false'>" . resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 return $events[$data[$NAME . $num]];
             }
             return '';
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             // status Stevenes Donato
             if ($data[$NAME . $num] == "1") {
                 $data[$NAME . $num] = "new";
             }
             if ($data[$NAME . $num] == "2") {
                 $data[$NAME . $num] = "assign";
             }
             if ($data[$NAME . $num] == "3") {
                 $data[$NAME . $num] = "plan";
             }
             if ($data[$NAME . $num] == "4") {
                 $data[$NAME . $num] = "waiting";
             }
             if ($data[$NAME . $num] == "5") {
                 $data[$NAME . $num] = "solved";
             }
             if ($data[$NAME . $num] == "6") {
                 $data[$NAME . $num] = "closed";
             }
             //
             return "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . $data[$NAME . $num] . ".png\"\n                        alt='{$status}' title='{$status}'>&nbsp;{$status}";
         case 'glpi_tickets.priority':
             return Ticket::getPriorityName($data[$NAME . $num]);
         case 'glpi_tickets.urgency':
             return Ticket::getUrgencyName($data[$NAME . $num]);
         case 'glpi_tickets.impact':
             return Ticket::getImpactName($data[$NAME . $num]);
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && class_exists($data[$NAME . $num . "_2"])) {
                 $item = new $data[$NAME . $num . "_2"]();
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(true);
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.id':
             $link = getItemTypeFormURLMobile('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num];
             //$out .= 'id='.$data[$NAME.$num."_2"];
             $out .= "\" data-back='false'>" . $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 //$out .= " (".$data[$NAME.$num."_2"].")";
                 $out .= $data[$NAME . $num . "_2"];
             }
             $out .= "</a>";
             return $out;
         case 'glpi_ticketvalidations.status':
         case "glpi_tickets.global_validation":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $status = TicketValidation::getStatus($val);
                 $bgcolor = TicketValidation::getStatusColor($val);
                 $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
             }
             return $out;
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 if (!empty($data[$NAME . $num . "_2"])) {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $link = getItemTypeFormURLMobile($searchopt[$ID]["itemlink_type"]);
                     } else {
                         $link = getItemTypeFormURLMobile($itemtype);
                     }
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"] . "\" data-back='false'>";
                     $out .= $data[$NAME . $num] . $unit;
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $out .= " (" . $data[$NAME . $num . "_2"] . ")";
                     }
                     $out .= "</a>";
                     return $out;
                 } else {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $out = "";
                         $split = explode("\$\$\$\$", $data[$NAME . $num]);
                         $count_display = 0;
                         $separate = '<br>';
                         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                             $separate = '<hr>';
                         }
                         for ($k = 0; $k < count($split); $k++) {
                             if (strlen(trim($split[$k])) > 0) {
                                 $split2 = explode("\$\$", $split[$k]);
                                 if (isset($split2[1]) && $split2[1] > 0) {
                                     if ($count_display) {
                                         $out .= $separate;
                                     }
                                     $count_display++;
                                     $page = getItemTypeFormURLMobile($searchopt[$ID]["itemlink_type"]);
                                     $page .= strpos($page, '?') ? '&id' : '?id';
                                     $out .= "<a id='" . $searchopt[$ID]["itemlink_type"] . "_" . $split2[1] . "'\n                                       href='{$page}=" . $split2[1] . "' data-back='false'>";
                                     $out .= $split2[0] . $unit;
                                     if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                         $out .= " (" . $split2[1] . ")";
                                     }
                                     $out .= "</a>";
                                 }
                             }
                         }
                         return $out;
                     }
                 }
                 break;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 return str_replace('$$$$', $separate, nl2br($data[$NAME . $num]));
             case "date":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 return timestampToString($data[$NAME . $num]);
             case "realtime":
                 return Ticket::getRealtime($data[$NAME . $num]);
             case "date_delay":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     if (strpos($val, ',')) {
                         list($dat, $dur) = explode(',', $val);
                         if (!empty($dat)) {
                             $out .= (empty($out) ? '' : '<br>') . getWarrantyExpir($dat, $dur);
                         }
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "email":
                 // Stevenes
                 //               $email=trim($data[$NAME.$num]);
                 $email = explode('$$', $data[$NAME . $num]);
                 if (!empty($email['0'])) {
                     return $email['0'];
                     //return "<a href='mailto:$email'>$email</a>";
                 }
                 return "&nbsp;";
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (utf8_strlen($link) > 30) {
                         $link = Toolbox::substr($link, 0, 30) . "...";
                     }
                     //return "<a href=\"".formatOutputWebLink($orig_link)."\" target='_blank'>$link</a>";
                     return $orig_link;
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', Html::formatNumber($split[$k], false, 0)) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num], false, 0)) . $unit;
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', Html::formatNumber($split[$k])) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num])) . $unit;
             case "bool":
                 return Dropdown::getYesNo($data[$NAME . $num]) . $unit;
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if (class_exists($data[$NAME . $num])) {
                     $obj = new $data[$NAME . $num]();
                     return $obj->getTypeName();
                 } else {
                     return "";
                 }
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 } else {
                     return $LANG['setup'][46];
                 }
                 break;
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $count_display++;
                 $out .= $split[$k] . $unit;
             }
         }
         return $out;
     }
     return $data[$NAME . $num] . $unit;
 }
Esempio n. 12
0
 public function showResult($output_type, $limit = 0, $params = array())
 {
     global $DB;
     $arrayRet = $this->execQuery($_REQUEST);
     $result = $arrayRet['query_result'];
     $query = $arrayRet['query'];
     $nbtot = $result ? $DB->numrows($result) : 0;
     if ($limit) {
         $start = isset($_REQUEST["start"]) ? $_REQUEST["start"] : 0;
         if ($start >= $nbtot) {
             $start = 0;
         }
         if ($start > 0 || $start + $limit < $nbtot) {
             $result = $DB->query($query . " LIMIT {$start},{$limit}");
         }
     } else {
         $start = 0;
     }
     $nbCols = $DB->num_fields($result);
     $nbrows = $DB->numrows($result);
     $groupByRackName = true;
     if (isset($_REQUEST['groupByRackName']) && $_REQUEST['groupByRackName'] == "on") {
         $groupByRackName = false;
     }
     $title = date("d/m/Y H:i");
     if ($nbtot == 0) {
         echo "<div class='center'><font class='red b'>" . __("No item found") . "</font></div>";
         Html::footer();
     } else {
         if ($output_type == Search::HTML_OUTPUT) {
             echo "<div class='center'><table class='tab_cadre_fixe'>";
             echo "<tr  class='tab_bg_1'><th>{$title}</th></tr>\n";
             echo "<tr class='tab_bg_2 center'><td class='center'>";
             $parameters = null;
             $parameters .= Toolbox::append_params($_REQUEST, '&amp;');
             $this->printPager($start, $nbtot, $_SERVER["PHP_SELF"], $parameters, 'PluginRacksRack');
         }
     }
     if ($nbtot > 0) {
         if ($output_type == Search::HTML_OUTPUT) {
             echo "<form method='POST' action='" . $_SERVER["PHP_SELF"] . "?start={$start}'>\n";
         }
         echo Search::showHeader($output_type, $nbrows, $nbCols, true);
         echo Search::showNewLine($output_type);
         $showAllFieds = true;
         $listFields = array();
         $cptField = 0;
         $showAllFieds = (!isset($_REQUEST['cb_object_name']) || $_REQUEST['cb_object_name'] != "on") && (!isset($_REQUEST['cb_object_location']) || $_REQUEST['cb_object_location'] != "on") && (!isset($_REQUEST['cb_group']) || $_REQUEST['cb_group'] != "on") && (!isset($_REQUEST['cb_manufacturer']) || $_REQUEST['cb_manufacturer'] != "on") && (!isset($_REQUEST['cb_model']) || $_REQUEST['cb_model'] != "on") && (!isset($_REQUEST['cb_serial_number']) || $_REQUEST['cb_serial_number'] != "on");
         $num = 1;
         $cptRow = 1;
         if (!$showAllFieds) {
             $this->showTitle($output_type, $num, __("Bay name", "racks"), 'name', false, $params);
             $cptField++;
             $this->showTitle($output_type, $num, __("Location"), 'location', false, $params);
             $cptField++;
             $this->showTitle($output_type, $num, _n("Place", "Places", 1, "racks"), 'roomlocation', false, $params);
             $cptField++;
             $this->showTitle($output_type, $num, __("U", "racks"), 'u', false, $params);
             $cptField++;
             $this->showTitle($output_type, $num, __("Front", "racks") . " / " . _x('Rack enclosure', 'Back', 'racks'), 'front_rear', false, $params);
             $cptField++;
             if (isset($_REQUEST['cb_object_name']) && $_REQUEST['cb_object_name'] == "on") {
                 $listFields['object_name'] = $_REQUEST['cb_object_name'];
                 $this->showTitle($output_type, $num, __("Object name", "racks"), 'object_name', false, $params);
                 $cptField++;
             }
             // Lieu
             if (isset($_REQUEST['cb_object_location']) && $_REQUEST['cb_object_location'] == "on") {
                 $listFields['object_location'] = $_REQUEST['cb_object_location'];
                 $this->showTitle($output_type, $num, __("Object location", "racks"), 'object_location', false, $params);
                 $cptField++;
             }
             // Groupe
             if (isset($_REQUEST['cb_group']) && $_REQUEST['cb_group'] == "on") {
                 $listFields['group'] = $_REQUEST['cb_group'];
                 $this->showTitle($output_type, $num, __("Group"), 'group', false, $params);
                 $cptField++;
             }
             // Fabricant
             if (isset($_REQUEST['cb_manufacturer']) && $_REQUEST['cb_manufacturer'] == "on") {
                 $listFields['manufacturer'] = $_REQUEST['cb_manufacturer'];
                 $this->showTitle($output_type, $num, __("Manufacturer"), 'manufacturer', false, $params);
                 $cptField++;
             }
             // Modèle
             if (isset($_REQUEST['cb_model']) && $_REQUEST['cb_model'] == "on") {
                 $listFields['model'] = $_REQUEST['cb_model'];
                 $this->showTitle($output_type, $num, __("Model"), 'model', false, $params);
                 $cptField++;
             }
             // Numéro de série
             if (isset($_REQUEST['cb_serial_number']) && $_REQUEST['cb_serial_number'] == "on") {
                 $listFields['serial_number'] = $_REQUEST['cb_serial_number'];
                 $this->showTitle($output_type, $num, __("Serial number"), 'group', false, $params);
                 $cptField++;
             }
         } else {
             $this->showTitle($output_type, $num, __("Bay name", "racks"), 'rack_name', false, $params);
             $listFields['rack_name'] = true;
             $this->showTitle($output_type, $num, __("Location"), 'location', false, $params);
             $listFields['location'] = true;
             $this->showTitle($output_type, $num, _n("Place", "Places", 1, "racks"), 'roomlocation', false, $params);
             $listFields['roomlocation'] = true;
             $this->showTitle($output_type, $num, __("U", "racks"), 'u', false, $params);
             $listFields['u'] = true;
             $this->showTitle($output_type, $num, __("Front", "racks") . " / " . _x('Rack enclosure', 'Back', 'racks'), 'front_rear', false, $params);
             $listFields['front_rear'] = true;
             $this->showTitle($output_type, $num, __("Object name", "racks"), 'object_name', false, $params);
             $listFields['object_name'] = true;
             $this->showTitle($output_type, $num, __("Object location", "racks"), 'object_location', false, $params);
             $listFields['object_location'] = true;
             $this->showTitle($output_type, $num, __("Group"), 'group', false, $params);
             $listFields['group'] = true;
             $this->showTitle($output_type, $num, __("Type"), 'type', false, $params);
             $listFields['type'] = true;
             $this->showTitle($output_type, $num, __("Manufacturer"), 'manufacturer', false, $params);
             $listFields['manufacturer'] = true;
             $this->showTitle($output_type, $num, __("Model"), 'model', false, $params);
             $listFields['model'] = true;
             $this->showTitle($output_type, $num, __("Serial number"), 'serial_number', false, $params);
             $listFields['serial_number'] = true;
             $this->showTitle($output_type, $num, __("Inventory number"), 'other_serial', false, $params);
             $listFields['other_serial'] = true;
             $cptField = 13;
         }
         echo self::showEndLine($output_type, $params);
         $num = 1;
         $cptRow = 1;
         $currentRack = -1;
         while ($row = $DB->fetch_array($result)) {
             // itemtype
             $itemtype = $row['itemtype'];
             $num = 1;
             $cptRow++;
             echo Search::showNewLine($output_type);
             if (isset($row['itemtype']) && $row['itemtype'] != "") {
                 $class = substr($itemtype, 0, -5);
                 $item = new $class();
                 $table = getTableForItemType($class);
                 $r = $DB->query("SELECT * FROM `" . $table . "` WHERE `id` = '" . $row["items_id"] . "' ");
                 $device = $DB->fetch_array($r);
             }
             // nom
             $link = Toolbox::getItemTypeFormURL("PluginRacksRack");
             if ($groupByRackName || $currentRack != $row['id']) {
                 if ($output_type == Search::HTML_OUTPUT) {
                     echo self::showItem($output_type, "<a href=\"" . $link . "?id=" . $row["id"] . "\">" . $row["name"] . "</a>", $num, $cptRow, null, $params);
                 } else {
                     echo self::showItem($output_type, $row["name"], $num, $cptRow, null, $params);
                 }
             } else {
                 echo self::showItem($output_type, "&nbsp;", $num, $cptRow, null, $params);
             }
             // lieu
             if ($groupByRackName || $currentRack != $row['id']) {
                 if (isset($row['locations_id'])) {
                     echo self::showItem($output_type, Dropdown::getDropdownName("glpi_locations", $row['locations_id']), $num, $cptRow, null, $params);
                 } else {
                     echo self::showItem($output_type, "&nbsp;", $num, $cptRow, null, $params);
                 }
             } else {
                 echo self::showItem($output_type, "&nbsp;", $num, $cptRow, null, $params);
             }
             // Emplacement
             if ($groupByRackName || $currentRack != $row['id']) {
                 $tmpId = $row['plugin_racks_roomlocations_id'];
                 $tmpId = $row['plugin_racks_roomlocations_id'];
                 $tmpObj = new PluginRacksRoomLocation();
                 $trans_name = "";
                 if ($tmpObj->getFromDB($tmpId)) {
                     $trans_name = $tmpObj->fields['name'];
                 }
                 $trans = DropdownTranslation::getTranslatedValue($tmpId, "PluginRacksRoomLocation", 'name', $_SESSION['glpilanguage']);
                 if (!empty($trans)) {
                     $trans_name = $trans;
                 }
                 if (isset($tmpId)) {
                     echo self::showItem($output_type, $trans_name, $num, $cptRow, null, $params);
                 } else {
                     echo self::showItem($output_type, '&nbsp;', $num, $cptRow, null, $params);
                 }
             } else {
                 echo self::showItem($output_type, "&nbsp;", $num, $cptRow, null, $params);
             }
             if (isset($row['itemtype']) && $row['itemtype'] != "") {
                 // U
                 if (isset($row['position']) && $row['position'] != "") {
                     echo self::showItem($output_type, $row['position'], $num, $cptRow, null, $params);
                 } else {
                     echo self::showItem($output_type, "&nbsp;", $num, $cptRow, null, $params);
                 }
                 // avant / arrière
                 if ($row['faces_id'] == 1) {
                     echo self::showItem($output_type, __("Front", "racks"), $num, $cptRow, null, $params);
                 } else {
                     echo self::showItem($output_type, _x('Rack enclosure', 'Back', 'racks'), $num, $cptRow, null, $params);
                 }
                 // Nom de l'objet
                 if (array_key_exists("object_name", $listFields)) {
                     $link = Toolbox::getItemTypeFormURL(substr($itemtype, 0, -5));
                     if ($itemtype != 'PluginRacksOtherModel') {
                         if ($output_type == Search::HTML_OUTPUT) {
                             echo self::showItem($output_type, "<a href=\"" . $link . "?id=" . $row["items_id"] . "\">" . $device["name"] . "</a>", $num, $cptRow, null, $params);
                         } else {
                             echo self::showItem($output_type, $device["name"], $num, $cptRow, null, $params);
                         }
                     } else {
                         echo self::showItem($output_type, $device["name"], $num, $cptRow, null, $params);
                     }
                 }
                 // Lieu de l'objet
                 if (array_key_exists("object_location", $listFields)) {
                     if ($itemtype != 'PluginRacksOtherModel') {
                         echo self::showItem($output_type, Dropdown::getDropdownName("glpi_locations", $device["locations_id"]), $num, $cptRow, null, $params);
                     } else {
                         echo self::showItem($output_type, Dropdown::EMPTY_VALUE, $num, $cptRow, null, $params);
                     }
                 }
                 // Groupe
                 if (array_key_exists("group", $listFields)) {
                     // Groupe
                     if ($itemtype != 'PluginRacksOtherModel') {
                         echo self::showItem($output_type, Dropdown::getDropdownName("glpi_groups", $device["groups_id_tech"]), $num, $cptRow, null, $params);
                     } else {
                         echo self::showItem($output_type, Dropdown::EMPTY_VALUE, $num, $cptRow, null, $params);
                     }
                 }
                 // type
                 if (array_key_exists("type", $listFields)) {
                     echo self::showItem($output_type, $item->getTypeName(), $num, $cptRow, null, $params);
                 }
                 // fabricant
                 if (array_key_exists("manufacturer", $listFields)) {
                     if ($itemtype != 'PluginRacksOtherModel') {
                         echo self::showItem($output_type, Dropdown::getDropdownName("glpi_manufacturers", $device["manufacturers_id"]), $num, $cptRow, null, $params);
                     } else {
                         echo self::showItem($output_type, Dropdown::EMPTY_VALUE, $num, $cptRow, null, $params);
                     }
                 }
                 // modèle
                 if (array_key_exists("model", $listFields)) {
                     $model_table = getTableForItemType($itemtype);
                     $modelfield = getForeignKeyFieldForTable(getTableForItemType($itemtype));
                     echo self::showItem($output_type, Dropdown::getDropdownName($model_table, $device[$modelfield]), $num, $cptRow, null, $params);
                 }
                 // numéro de série
                 if (array_key_exists("serial_number", $listFields)) {
                     if ($itemtype != 'PluginRacksOtherModel') {
                         echo self::showItem($output_type, $device['serial'], $num, $cptRow, null, $params);
                     } else {
                         echo self::showItem($output_type, Dropdown::EMPTY_VALUE, $num, $cptRow, null, $params);
                     }
                 }
                 // numéro d'inventaire
                 if (array_key_exists("other_serial", $listFields)) {
                     if ($itemtype != 'PluginRacksOtherModel') {
                         echo self::showItem($output_type, $device['otherserial'], $num, $cptRow, null, $params);
                     } else {
                         echo self::showItem($output_type, Dropdown::EMPTY_VALUE, $num, $cptRow, null, $params);
                     }
                 }
                 $currentRack = $row['id'];
             } else {
                 for ($k = 0; $k < $cptField - 3; $k++) {
                     echo self::showItem($output_type, "&nbsp;", $num, $cptRow, null, $params);
                 }
             }
             echo self::showEndLine($output_type, $params);
         }
         echo self::showFooter($output_type, $title, $params);
         if ($output_type == Search::HTML_OUTPUT) {
             Html::closeForm();
         }
     }
 }
Esempio n. 13
0
    public static function show($ID, $from_helpdesk)
    {
        global $LANG, $CFG_GLPI, $DB;
        //$logged = $_SESSION['glpiID'];
        if (!isset($_REQUEST['session'])) {
            $IDO = Session::getLoginUserID();
        } else {
            $IDO = $_REQUEST['session'];
        }
        $logged = $ID;
        /*
        echo $logged."logged2 ";
        echo Session::getLoginUserID()."session ";
        */
        if (isset($_REQUEST['id'])) {
            $ID = $_REQUEST['id'];
            $_SESSION["glpiID"] = $_REQUEST['id'];
            $query = "SELECT `profiles_id` AS id\nFROM `glpi_profiles_users`\nWHERE `users_id` = " . $IDO . "\nORDER BY `glpi_profiles_users`.`profiles_id` DESC";
            $result = $DB->query($query);
            $cont = $DB->numrows($result);
            $profile = $DB->fetch_assoc($result);
        } else {
            $ID = $_SESSION['glpiID'];
            $_SESSION['glpiID'] = $_SESSION['glpiID'];
            $query = "SELECT `profiles_id` AS id\nFROM `glpi_profiles_users`\nWHERE `users_id` = " . $IDO . "\nORDER BY `glpi_profiles_users`.`profiles_id` DESC";
            $result = $DB->query($query);
            $cont = $DB->numrows($result);
            $profile = $DB->fetch_assoc($result);
        }
        /*		
        echo $ID."id ";
        echo $_SESSION['glpiID']."glpiid ";
        echo $_SESSION['logged']."logged ";
        echo $logged."logged2 ";
        */
        if (!Session::haveRight("ticket", CREATE)) {
            return false;
        }
        if (Session::haveRight('validate_ticket', 1)) {
            //	      if (Session::haveRightsOr('ticketvalidation', array(TicketValidation::VALIDATEREQUEST, TicketValidation::VALIDATEINCIDENT))) {
            $opt = array();
            $opt['reset'] = 'reset';
            $opt['field'][0] = 55;
            // validation status
            $opt['searchtype'][0] = 'equals';
            $opt['contains'][0] = 'waiting';
            $opt['link'][0] = 'AND';
            $opt['field'][1] = 59;
            // validation aprobator
            $opt['searchtype'][1] = 'equals';
            $opt['contains'][1] = Session::getLoginUserID();
            //$opt['contains'][1]   = $ID;
            $opt['link'][1] = 'AND';
            $url_validate = $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($opt, '&amp;');
            if (TicketValidation::getNumberTicketsToValidate(Session::getLoginUserID()) > 0) {
                //if (TicketValidation::getNumberTicketsToValidate( $ID >0) {
                echo "<a href='{$url_validate}' title=\"" . $LANG['validation'][15] . "\"\n                      alt=\"" . $LANG['validation'][15] . "\">" . $LANG['validation'][33] . "</a><br><br>";
            }
        }
        // Stevenes Donato
        //email user
        $query = "SELECT  gu.id, ge.email, gu.`firstname`, gu.`realname`, gu.`name`\n                 FROM `glpi_users` gu, glpi_useremails ge\n                 WHERE gu.`id` = '{$ID}'\n\t\t\t\t\t  AND ge.users_id = gu.id ";
        $result = $DB->query($query);
        $email = $DB->result($result, 0, "email");
        $user_name = $DB->result($result, 0, "firstname") . " ";
        $user_sname = $DB->result($result, 0, "realname");
        //categories
        $query_cat = "SELECT id, completename\n\t\t\t\t\t\t\tFROM `glpi_itilcategories` \n\t\t\t\t\t\t\tWHERE `is_helpdeskvisible` = 1";
        $result_cat = $DB->query($query_cat);
        $itilcategories_id = $DB->fetch_assoc($result_cat);
        $sql_user = "******";
        $result_user = $DB->query($sql_user);
        $user = $DB->fetch_assoc($result_user);
        // Get saved data from a back system
        $use_email_notification = 1;
        if ($email == "") {
            $use_email_notification = 0;
        }
        $itemtype = 0;
        $items_id = "";
        $content = "";
        $title = "";
        //$itilcategories_id = 0;
        $urgency = 3;
        if (isset($_SESSION["helpdeskSaved"]["use_email_notification"])) {
            $use_email_notification = stripslashes($_SESSION["helpdeskSaved"]["use_email_notification"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["email"])) {
            $email = stripslashes($_SESSION["helpdeskSaved"]["user_email"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["itemtype"])) {
            $itemtype = stripslashes($_SESSION["helpdeskSaved"]["itemtype"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["items_id"])) {
            $items_id = stripslashes($_SESSION["helpdeskSaved"]["items_id"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["content"])) {
            $content = cleanPostForTextArea($_SESSION["helpdeskSaved"]["content"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["name"])) {
            $title = stripslashes($_SESSION["helpdeskSaved"]["name"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["itilcategories_id"])) {
            //$itilcategories_id = stripslashes($_SESSION["helpdeskSaved"]["itilcategories_id"]);
            $itilcategories_id = $_SESSION["helpdeskSaved"]["itilcategories_id"];
        }
        if (isset($_SESSION["helpdeskSaved"]["urgency"])) {
            $urgency = stripslashes($_SESSION["helpdeskSaved"]["urgency"]);
        }
        unset($_SESSION["helpdeskSaved"]);
        echo "<form method='post' name=\"helpdeskform\" action=\"" . $CFG_GLPI["root_doc"] . "/plugins/mobile/front/tracking.injector.php?ido=" . $IDO . "\" enctype=\"multipart/form-data\">";
        echo "<input type='hidden' name='_from_helpdesk' value='{$from_helpdesk}'>";
        if ($CFG_GLPI['urgency_mask'] == 1 << 3) {
            // Dont show dropdown if only 1 value enabled
            echo "<input type='hidden' name='urgency' value='3'>";
        }
        echo "<input type='hidden' name='entities_id' value='" . $_SESSION["glpiactive_entity"] . "'>";
        echo "<div class='force_left input_right'><table class='tab_cadre'>";
        echo "<tr><th colspan='1'>" . $LANG['job'][11] . "&nbsp;: </th></tr>";
        echo "<tr><th colspan='1'>";
        if (Session::isMultiEntitiesMode()) {
            echo "&nbsp;(" . Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]) . ")";
        }
        echo "</th></tr>";
        //Requerente
        if ($cont != "1" && $profile != "1") {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['job'][4] . "&nbsp;: </td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td >";
            // Dropdown::show('ITILCategories', array('value' => $user,'condition'=>'is_deleted=0'));
            //Dropdown::showFromArray("user_id", $user);
            echo "\n\n<script>\nfunction getComboA(sel) {\n    var id = sel.options[sel.selectedIndex].value; \n    //var name = sel.options[sel.selectedIndex].id;\n    //document.getElementById('user').innerHTML = id;\n    window.location.assign('" . $CFG_GLPI['root_doc'] . "/plugins/mobile/front/helpdesk.php?id='+id+'&session=" . $IDO . "');    \n}\n</script> ";
            echo "<select id='sel_user' onchange='getComboA(this)'>";
            echo '<option value=" "> -- Selecione -- </option>';
            while ($user = $DB->fetch_array($result_user)) {
                echo "<option value=" . $user['id'] . " id= \"" . $user['name'] . " " . $user['sname'] . " \">" . $user['name'] . " " . $user['sname'] . "</option>";
            }
            echo "</select>";
            echo "</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['job'][4] . "&nbsp;: </td></tr>";
            echo "<tr class='center tab_bg_1'>";
            echo "<td >" . $user_name . $user_sname . "</td></tr>";
            echo "<input type='hidden' name='logged' value='" . $logged . "'>";
        }
        if ($CFG_GLPI['urgency_mask'] != 1 << 3) {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['joblist'][29] . "&nbsp;: </td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td>";
            //Ticket::dropdownUrgency("urgency",$urgency);
            Ticket::dropdownUrgency(array('value' => $values["urgency"]));
            echo "</td></tr>";
        }
        if (NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['help'][8] . "&nbsp;:</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td >";
            Dropdown::showYesNo('use_email_notification', $use_email_notification);
            echo "</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['plugin_mobile']["email"] . "&nbsp;:</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td ><input type='text' id='user_email' name='user_email' value=\"{$email}\" size='40' onchange=\"use_email_notification.value='1'\">";
            echo "</td></tr>";
        }
        if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['help'][24] . "&nbsp;: </td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td >";
            Item_Ticket::dropdownMyDevices(Session::getLoginUserID(), $_SESSION["glpiactive_entity"]);
            //Ticket::dropdownMyDevices($ID,$_SESSION["glpiactive_entity"]);
            echo "</td></tr>";
        }
        //Stevenes Donato
        echo "<tr class='tab_bg_1'>";
        echo "<td class='force_left'>" . $LANG['common'][36] . "&nbsp;:</td></tr>";
        echo "<tr class='tab_bg_1'><td>";
        //Dropdown::show('TicketCategory', array('value' => $itilcategories_id,'condition'=>'`is_helpdeskvisible`=1'));
        //Dropdown::show('ITILCategory', array('value' => $itilcategories_id,'condition'=>'`is_helpdeskvisible`=1'));
        //Dropdown::getDropdownName("glpi_itilcategories", $this->fields["itilcategories_id"]);
        //Dropdown::showFromArray("completename", $itilcategories_id);
        echo "<script>\n\t\tfunction getCat(sel) {\n\t\t    //var x = document.getElementById('sel_cat').value;\n\t\t    var cat = sel.options[sel.selectedIndex].value; \n\t\t    //document.getElementById('demo').innerHTML = 'Categoria: ' + cat;\n\t\t    //document.getElementById('demo').innerHTML = '<input type=\\'text\\' name=\\'itilcategories_id\\' value=\\' +cat+ \\'/>';\n\t\t    document.getElementById('categoria').value = cat;\t\t   \n\t\t}\n\t\t</script>";
        echo "<select id='sel_cat' onchange='getCat(this)'>";
        echo '<option value=" "> -- ' . $LANG['dropdown'][35] . '-- </option>';
        while ($cat = $DB->fetch_array($result_cat)) {
            echo "<option value=" . $cat['id'] . " id= \"" . $cat['completename'] . " \">" . $cat['completename'] . " </option>";
        }
        echo "</select>" . "\n";
        echo "</td></tr>";
        echo "<tr><td>";
        //echo '<label for="itilcategories_id" id="demo"></label>';
        //echo "<span id='demo'></span>";
        echo "<input id='categoria' type='hidden' name='itilcategories_id' value='' />";
        echo "</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td>" . $LANG['common'][57] . "&nbsp;:</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td ><input type='text' maxlength='250' size='50' name='name' value=\"{$title}\" required ></td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td>" . $LANG['joblist'][6] . "&nbsp;:</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td  colspan='1'><textarea name='content' cols='78' rows='14' required >{$content}</textarea>";
        echo "</td></tr>";
        echo "<tr class='tab_bg_1'><td>" . $LANG['document'][2] . " (" . Document::getMaxUploadSize() . ")&nbsp;:";
        /*
         * we hide the picture (aide.png) to prevent the form openning in other window,
         * outside the mobile plugin layout.
               echo "<img src=\"".$CFG_GLPI["root_doc"]."/pics/aide.png\" class='pointer' alt=\"".
                      $LANG['central'][7]."\" onclick=\"window.open('".$CFG_GLPI["root_doc"].
                      "/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,height=800')\">";
        */
        echo "<input type='hidden' name='ido' value='" . $IDO . "'>";
        ?>

<script>
function getID() {
    var ido = document.getElementById('ido').value; 
    document.getElementById('session').innerHTML = "$_SESSION['logged']="+ido;
    //window.location.assign('".$CFG_GLPI['root_doc']."/plugins/mobile/front/helpdesk.php?id='+id+'&session=".$IDO."');    
}
</script>
<div id="session" style="display:none;"></div>

<?php 
        echo "</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td><input type='file' class='ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c' name='filename' value=\"\" size='25'></td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td colspan='1' class='center'>";
        echo "<input type='submit' value=\"" . $LANG['help'][14] . "\" class='submit' >";
        echo "</td></tr>";
        echo "</table></div>";
        //</form>";
        Html::closeForm();
    }
Esempio n. 14
0
 public function getMenu($sector = "none", $item = "none", $option = "")
 {
     global $LANG, $CFG_GLPI;
     // INVENTORY
     $showstate = false;
     $menu['inventory']['title'] = $LANG['Menu'][38];
     $menu['inventory']['default'] = '/front/computer.php';
     $menu['inventory']['icon'] = 'icons/inventory.png';
     if (Session::haveRight("computer", CREATE)) {
         $menu['inventory']['content']['computer']['title'] = $LANG['Menu'][0];
         $menu['inventory']['content']['computer']['shortcut'] = 'c';
         $menu['inventory']['content']['computer']['icon'] = 'icons/computer.png';
         $menu['inventory']['content']['computer']['page'] = '/front/search.php?itemtype=computer&menu=inventory&ssmenu=computer';
         $menu['inventory']['content']['computer']['links']['search'] = '/front/computer.php';
         if (Session::haveRight("computer", UPDATE)) {
             $menu['inventory']['content']['computer']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Computer&amp;add=1';
             $menu['inventory']['content']['computer']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Computer&amp;add=0';
         }
         $showstate = true;
     }
     if (Session::haveRight("monitor", CREATE)) {
         $menu['inventory']['content']['monitor']['title'] = $LANG['Menu'][3];
         $menu['inventory']['content']['monitor']['shortcut'] = 'm';
         $menu['inventory']['content']['monitor']['icon'] = 'icons/monitor.png';
         $menu['inventory']['content']['monitor']['page'] = '/front/search.php?itemtype=monitor&menu=inventory&ssmenu=monitor';
         $menu['inventory']['content']['monitor']['links']['search'] = '/front/monitor.php';
         if (Session::haveRight("monitor", UPDATE)) {
             $menu['inventory']['content']['monitor']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Monitor&amp;add=1';
             $menu['inventory']['content']['monitor']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Monitor&amp;add=0';
         }
         $showstate = true;
     }
     if (Session::haveRight("software", CREATE)) {
         $menu['inventory']['content']['software']['title'] = $LANG['Menu'][4];
         $menu['inventory']['content']['software']['shortcut'] = 's';
         $menu['inventory']['content']['software']['icon'] = 'icons/software.png';
         $menu['inventory']['content']['software']['page'] = '/front/search.php?itemtype=software&menu=inventory&ssmenu=software';
         $menu['inventory']['content']['software']['links']['search'] = '/front/software.php';
         if (Session::haveRight("software", UPDATE)) {
             $menu['inventory']['content']['software']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Software&amp;add=1';
             $menu['inventory']['content']['software']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Software&amp;add=0';
         }
         $showstate = true;
     }
     if (Session::haveRight("networking", CREATE)) {
         $menu['inventory']['content']['networking']['title'] = $LANG['Menu'][1];
         $menu['inventory']['content']['networking']['shortcut'] = 'n';
         $menu['inventory']['content']['networking']['icon'] = 'icons/network.png';
         $menu['inventory']['content']['networking']['page'] = '/front/search.php?itemtype=networkequipment&menu=inventory&ssmenu=networking';
         $menu['inventory']['content']['networking']['links']['search'] = '/front/networkequipment.php';
         if (Session::haveRight("networking", UPDATE)) {
             $menu['inventory']['content']['networking']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=NetworkEquipment&amp;add=1';
             $menu['inventory']['content']['networking']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=NetworkEquipment&amp;add=0';
         }
         $showstate = true;
     }
     if (Session::haveRight("peripheral", CREATE)) {
         $menu['inventory']['content']['peripheral']['title'] = $LANG['Menu'][16];
         $menu['inventory']['content']['peripheral']['shortcut'] = 'n';
         $menu['inventory']['content']['peripheral']['icon'] = 'icons/connect.png';
         $menu['inventory']['content']['peripheral']['page'] = '/front/search.php?itemtype=peripheral&menu=inventory&ssmenu=peripheral';
         $menu['inventory']['content']['peripheral']['links']['search'] = '/front/peripheral.php';
         if (Session::haveRight("peripheral", UPDATE)) {
             $menu['inventory']['content']['peripheral']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Peripheral&amp;add=1';
             $menu['inventory']['content']['peripheral']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Peripheral&amp;add=0';
         }
         $showstate = true;
     }
     if (Session::haveRight("printer", CREATE)) {
         $menu['inventory']['content']['printer']['title'] = $LANG['Menu'][2];
         $menu['inventory']['content']['printer']['shortcut'] = 'p';
         $menu['inventory']['content']['printer']['icon'] = 'icons/print.png';
         $menu['inventory']['content']['printer']['page'] = '/front/search.php?itemtype=printer&menu=inventory&ssmenu=printer';
         $menu['inventory']['content']['printer']['links']['search'] = '/front/printer.php';
         if (Session::haveRight("printer", UPDATE)) {
             $menu['inventory']['content']['printer']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Printer&amp;add=1';
             $menu['inventory']['content']['printer']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Printer&amp;add=0';
         }
         $showstate = true;
     }
     if (Session::haveRight("cartridge", CREATE)) {
         $menu['inventory']['content']['cartridge']['title'] = $LANG['Menu'][21];
         $menu['inventory']['content']['cartridge']['shortcut'] = 'c';
         $menu['inventory']['content']['cartridge']['icon'] = 'icons/cartridge.png';
         $menu['inventory']['content']['cartridge']['page'] = '/front/search.php?itemtype=cartridgeitem&menu=inventory&ssmenu=cartridge';
         $menu['inventory']['content']['cartridge']['links']['search'] = '/front/cartridgeitem.php';
         if (Session::haveRight("cartridge", UPDATE)) {
             $menu['inventory']['content']['cartridge']['links']['add'] = '/front/cartridgeitem.form.php';
         }
     }
     if (Session::haveRight("consumable", CREATE)) {
         $menu['inventory']['content']['consumable']['title'] = $LANG['Menu'][32];
         $menu['inventory']['content']['consumable']['shortcut'] = 'g';
         $menu['inventory']['content']['consumable']['icon'] = 'icons/coffe_cup.png';
         $menu['inventory']['content']['consumable']['page'] = '/front/search.php?itemtype=consumableitem&menu=inventory&ssmenu=consumable';
         $menu['inventory']['content']['consumable']['links']['search'] = '/front/consumableitem.php';
         if (Session::haveRight("consumable", UPDATE)) {
             $menu['inventory']['content']['consumable']['links']['add'] = '/front/consumableitem.form.php';
         }
         $menu['inventory']['content']['consumable']['links']['summary'] = '/front/consumableitem.php?' . 'synthese=yes';
     }
     if (Session::haveRight("phone", CREATE)) {
         $menu['inventory']['content']['phone']['title'] = $LANG['Menu'][34];
         $menu['inventory']['content']['phone']['shortcut'] = 't';
         $menu['inventory']['content']['phone']['icon'] = 'icons/phone.png';
         $menu['inventory']['content']['phone']['page'] = '/front/search.php?itemtype=phone&menu=inventory&ssmenu=phone';
         $menu['inventory']['content']['phone']['links']['search'] = '/front/phone.php';
         if (Session::haveRight("phone", UPDATE)) {
             $menu['inventory']['content']['phone']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Phone&amp;add=1';
             $menu['inventory']['content']['phone']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Phone&amp;add=0';
         }
         $showstate = true;
     }
     if ($showstate) {
         $menu['inventory']['content']['state']['title'] = $LANG['Menu'][28];
         $menu['inventory']['content']['state']['shortcut'] = 'n';
         $menu['inventory']['content']['state']['icon'] = 'icons/list.png';
         $menu['inventory']['content']['state']['page'] = '/front/search.php?itemtype=state&menu=inventory&ssmenu=state';
         $menu['inventory']['content']['state']['links']['search'] = '/front/states.php';
         $menu['inventory']['content']['state']['links']['summary'] = '/front/states.php?synthese=yes';
     }
     // ASSISTANCE
     $menu['maintain']['title'] = $LANG['title'][24];
     $menu['maintain']['default'] = '/front/ticket.php';
     $menu['maintain']['icon'] = 'icons/assistance.png';
     //   if (Session::haveRight("observe_ticket","1") || Session::haveRight("show_all_ticket","1") || Session::haveRight("create_ticket","1")) {
     if (Session::haveRight("ticket", CREATE) || Session::haveRight("ticket", UPDATE)) {
         //if (Session::haveRight("ticket",CREATE) ) {
         $menu['maintain']['content']['ticket']['title'] = $LANG['Menu'][5];
         $menu['maintain']['content']['ticket']['icon'] = 'icons/ticket.png';
         $menu['maintain']['content']['ticket']['shortcut'] = 't';
         $menu['maintain']['content']['ticket']['page'] = '/front/search.php?itemtype=ticket&menu=maintain&ssmenu=ticket';
         $menu['maintain']['content']['ticket']['links']['search'] = '/front/ticket.php';
         $menu['maintain']['content']['ticket']['links']['search'] = '/front/ticket.php';
         if (Session::haveRight('ticket', Ticket::READALL)) {
             $opt = array();
             $opt['reset'] = 'reset';
             $opt['field'][0] = 55;
             // validation status
             $opt['searchtype'][0] = 'equals';
             $opt['contains'][0] = 'waiting';
             $opt['link'][0] = 'AND';
             $opt['field'][1] = 59;
             // validation aprobator
             $opt['searchtype'][1] = 'equals';
             $opt['contains'][1] = Session::getLoginUserID();
             $opt['link'][1] = 'AND';
             $pic_validate = "<img title=\"" . $LANG['validation'][15] . "\" alt=\"" . $LANG['validation'][15] . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/menu_showall.png'>";
             $menu['maintain']['content']['ticket']['links'][$pic_validate] = '/front/ticket.php?' . Toolbox::append_params($opt, '&amp;');
         }
     }
     if (Session::haveRight("ticket", CREATE) || Session::haveRight("ticket", Ticket::READALL)) {
         $menu['maintain']['content']['helpdesk']['title'] = $LANG['job'][13];
         $menu['maintain']['content']['helpdesk']['icon'] = 'icons/ticket.png';
         $menu['maintain']['content']['helpdesk']['shortcut'] = 'c';
         $menu['maintain']['content']['helpdesk']['page'] = '/front/helpdesk.php';
         $menu['maintain']['content']['ticket']['links']['add'] = '/front/ticket.form.php';
     }
     if (Session::haveRight("planning", CREATE) || Session::haveRight("planning", Ticket::READALL)) {
         $menu['maintain']['content']['planning']['title'] = __('Planning');
         //$LANG['Menu'][29];
         $menu['maintain']['content']['planning']['shortcut'] = 'l';
         $menu['maintain']['content']['planning']['icon'] = 'icons/planning.png';
         $menu['maintain']['content']['planning']['page'] = '/front/planning.php';
         $menu['maintain']['content']['planning']['links']['search'] = '/front/planning.php';
         $menu['maintain']['content']['planning']['external'] = true;
     }
     if (Session::haveRight("statistic", "1")) {
         $menu['maintain']['content']['stat']['title'] = $LANG['Menu'][13];
         $menu['maintain']['content']['stat']['shortcut'] = '1';
         $menu['maintain']['content']['stat']['icon'] = 'icons/charts.png';
         $menu['maintain']['content']['stat']['page'] = '/front/stat.php';
     }
     // FINANCIAL
     if (Session::haveRight("budget", READ)) {
         $menu['financial']['content']['budget']['title'] = $LANG['financial'][110];
         $menu['financial']['content']['budget']['shortcut'] = 'n';
         $menu['financial']['content']['budget']['icon'] = 'icons/euro.png';
         $menu['financial']['content']['budget']['page'] = '/front/search.php?itemtype=budget&menu=financial&ssmenu=budget';
         $menu['financial']['content']['budget']['links']['search'] = '/front/budget.php';
         if (Session::haveRight("contract", UPDATE)) {
             $menu['financial']['content']['budget']['links']['add'] = '/front/setup.templates.php?' . 'itemtype=Budget&amp;add=1';
             $menu['financial']['content']['budget']['links']['template'] = '/front/setup.templates.php?' . 'itemtype=Budget&amp;add=0';
         }
     }
     $menu['financial']['title'] = $LANG['Menu'][26];
     $menu['financial']['icon'] = 'icons/wallet.png';
     if (Session::haveRight("contact_enterprise", READ)) {
         $menu['financial']['content']['supplier']['title'] = $LANG['Menu'][23];
         $menu['financial']['content']['supplier']['shortcut'] = 'e';
         $menu['financial']['content']['supplier']['icon'] = 'icons/track.png';
         $menu['financial']['content']['supplier']['page'] = '/front/search.php?itemtype=supplier&menu=financial&ssmenu=supplier';
         $menu['financial']['content']['supplier']['links']['search'] = '/front/supplier.php';
         $menu['financial']['default'] = '/front/contact.php';
         $menu['financial']['content']['contact']['title'] = $LANG['Menu'][22];
         $menu['financial']['content']['contact']['icon'] = 'icons/contact.png';
         $menu['financial']['content']['contact']['shortcut'] = 't';
         $menu['financial']['content']['contact']['page'] = '/front/search.php?itemtype=contact&menu=financial&ssmenu=contact';
         $menu['financial']['content']['contact']['links']['search'] = '/front/contact.php';
         if (Session::haveRight("contact_enterprise", UPDATE)) {
             $menu['financial']['content']['contact']['links']['add'] = '/front/contact.form.php';
             $menu['financial']['content']['supplier']['links']['add'] = '/front/supplier.form.php';
         }
     }
     if (Session::haveRight("contract", READ)) {
         $menu['financial']['content']['contract']['title'] = $LANG['Menu'][25];
         $menu['financial']['content']['contract']['shortcut'] = 'n';
         $menu['financial']['content']['contract']['icon'] = 'icons/case.png';
         $menu['financial']['content']['contract']['page'] = '/front/search.php?itemtype=contract&menu=financial&ssmenu=contract';
         $menu['financial']['content']['contract']['links']['search'] = '/front/contract.php';
         if (Session::haveRight("contract", UPDATE)) {
             $menu['financial']['content']['contract']['links']['add'] = '/front/contract.form.php';
         }
     }
     if (Session::haveRight("document", READ)) {
         $menu['financial']['content']['document']['title'] = $LANG['Menu'][27];
         $menu['financial']['content']['document']['shortcut'] = 'd';
         $menu['financial']['content']['document']['icon'] = 'icons/doc.png';
         $menu['financial']['content']['document']['page'] = '/front/search.php?itemtype=document&menu=financial&ssmenu=document';
         $menu['financial']['content']['document']['links']['search'] = '/front/document.php';
         if (Session::haveRight("document", UPDATE)) {
             $menu['financial']['content']['document']['links']['add'] = '/front/document.form.php';
         }
     }
     // UTILS
     /*$menu['utils']['title']=$LANG['Menu'][18];
           $menu['utils']['default']='/front/reminder.php';
     
           $menu['utils']['content']['reminder']['title']=$LANG['title'][37];
           $menu['utils']['content']['reminder']['page']='/front/search.php?itemtype=document&menu=utils&ssmenu=reminder';
           $menu['utils']['content']['reminder']['links']['search']='/front/reminder.php';
           $menu['utils']['content']['reminder']['links']['add']='/front/reminder.form.php';
     
           if (Session::haveRight("knowbase",READ) || Session::haveRight("faq",READ)) {
              $menu['utils']['content']['knowbase']['title']=$LANG['Menu'][19];
              $menu['utils']['content']['knowbase']['page']='/front/search.php?itemtype=knowbaseitem&menu=utils&ssmenu=knowbase';
              $menu['utils']['content']['knowbase']['links']['search']='/front/knowbaseitem.php';
              if (Session::haveRight("knowbase",UPDATE) || Session::haveRight("faq",UPDATE)) {
                 $menu['utils']['content']['knowbase']['links']['add']='/front/knowbaseitem.form.php?id=new';
              }
           }
     
           if (Session::haveRight("reservation_helpdesk","1") || Session::haveRight("reservation_central",READ)) {
              $menu['utils']['content']['reservation']['title']=$LANG['Menu'][17];
              $menu['utils']['content']['reservation']['page']='/front/search.php?itemtype=reservationitem&menu=utils&ssmenu=reservation';
              $menu['utils']['content']['reservation']['links']['search']='/front/reservationitem.php';
              $menu['utils']['content']['reservation']['links']['showall']='/front/reservation.php';
           }
     
           if (Session::haveRight("reports",READ)) {
              $menu['utils']['content']['report']['title']=$LANG['Menu'][6];
              $menu['utils']['content']['report']['page']='/front/report.php';
           }
     
           if ($CFG_GLPI["use_ocs_mode"] && Session::haveRight("ocsng",UPDATE)) {
              $menu['utils']['content']['ocsng']['title']=$LANG['Menu'][33];
              $menu['utils']['content']['ocsng']['page']='/front/ocsng.php';
           }
     
           // PLUGINS
           if (isset($PLUGIN_HOOKS["menu_entry"]) && count($PLUGIN_HOOKS["menu_entry"])) {
              $menu['plugins']['title']=$LANG['common'][29];
              $plugins=array();
              foreach  ($PLUGIN_HOOKS["menu_entry"] as $plugin => $active) {
                 if ($active) { // true or a string
                    $function="plugin_version_$plugin";
                    if (function_exists($function)) {
                       $plugins[$plugin]=$function();
                    }
                 }
              }
              if (count($plugins)) {
                 $list=array();
                 foreach ($plugins as $key => $val) {
                    $list[$key]=$val["name"];
                 }
                 asort($list);
                 foreach ($list as $key => $val) {
                    $menu['plugins']['content'][$key]['title']=$val;
                    $menu['plugins']['content'][$key]['page']='/plugins/'.$key.'/';
                    if (is_string($PLUGIN_HOOKS["menu_entry"][$key])) {
                       $menu['plugins']['content'][$key]['page'] .= $PLUGIN_HOOKS["menu_entry"][$key];
                    }
     
                    // Set default link for plugins
                    if (!isset($menu['plugins']['default'])) {
                       $menu['plugins']['default']=$menu['plugins']['content'][$key]['page'];
                    }
     
                    if ($sector=="plugins"&&$item==$key) {
                       if (isset($PLUGIN_HOOKS["submenu_entry"][$key])
                           && is_array($PLUGIN_HOOKS["submenu_entry"][$key])) {
     
                          foreach ($PLUGIN_HOOKS["submenu_entry"][$key] as $name => $link) {
     
                             // New complete option management
                             if ($name=="options") {
                                $menu['plugins']['content'][$key]['options']=$link;
                             } else { // Keep it for compatibility
                                if (is_array($link)) {
                                   // Simple link option
                                   if (isset($link[$option])) {
                                      $menu['plugins']['content'][$key]['links'][$name]='/plugins/'.$key.'/'.
                                                                                      $link[$option];
                                   }
                                } else {
                                   $menu['plugins']['content'][$key]['links'][$name]='/plugins/'.$key.'/'.$link;
                                }
                             }
                          }
                       }
                    }
                 }
              }
           }*/
     /// ADMINISTRATION
     $menu['admin']['title'] = $LANG['Menu'][15];
     $menu['admin']['default'] = '/front/user.php';
     $menu['admin']['icon'] = 'icons/cogs.png';
     if (Session::haveRight("user", READ)) {
         $menu['admin']['content']['user']['title'] = $LANG['Menu'][14];
         $menu['admin']['content']['user']['shortcut'] = 'u';
         $menu['admin']['content']['user']['icon'] = 'icons/user.png';
         $menu['admin']['content']['user']['page'] = '/front/search.php?itemtype=user&menu=admin&ssmenu=user';
         $menu['admin']['content']['user']['links']['search'] = '/front/user.php';
         if (Session::haveRight("user", UPDATE)) {
             $menu['admin']['content']['user']['links']['add'] = "/front/user.form.php";
         }
         $menu['admin']['content']['user']['options']['ldap']['title'] = $LANG['login'][2];
         $menu['admin']['content']['user']['options']['ldap']['page'] = "/front/ldap.php";
     }
     if (Session::haveRight("group", READ)) {
         $menu['admin']['content']['group']['title'] = $LANG['Menu'][36];
         $menu['admin']['content']['group']['shortcut'] = 'g';
         $menu['admin']['content']['group']['icon'] = 'icons/users.png';
         $menu['admin']['content']['group']['page'] = '/front/search.php?itemtype=group&menu=admin&ssmenu=group';
         $menu['admin']['content']['group']['links']['search'] = '/front/group.php';
         if (Session::haveRight("group", UPDATE)) {
             $menu['admin']['content']['group']['links']['add'] = "/front/group.form.php";
             $menu['admin']['content']['group']['options']['ldap']['title'] = $LANG['login'][2];
             $menu['admin']['content']['group']['options']['ldap']['page'] = "/front/ldap.group.php";
         }
     }
     if (Session::haveRight("entity", READ)) {
         $menu['admin']['content']['entity']['title'] = $LANG['Menu'][37];
         $menu['admin']['content']['entity']['shortcut'] = 'z';
         $menu['admin']['content']['entity']['icon'] = 'icons/layers_2.png';
         $menu['admin']['content']['entity']['page'] = '/front/search.php?itemtype=entity&menu=admin&ssmenu=entity';
         $menu['admin']['content']['entity']['links']['search'] = '/front/entity.php';
         $menu['admin']['content']['entity']['links']['add'] = "/front/entity.form.php";
     }
     /*if (Session::haveRight("rule_ldap",READ)
                 || Session::haveRight("rule_ocs",READ)
                    || Session::haveRight("entity_rule_ticket",READ)
                       || Session::haveRight("rule_softwarecategories",READ)
                          || Session::haveRight("rule_mailcollector",READ)) {
     
              $menu['admin']['content']['rule']['title']=$LANG['rulesengine'][17];
              $menu['admin']['content']['rule']['shortcut']='r';
              $menu['admin']['content']['rule']['page']='/front/search.php?itemtype=rule&menu=admin&ssmenu=rule';
              
              if ($sector=='admin' && $item == 'rule') {
     
                 $menu['admin']['content']['rule']['options']['ocs']['title']=$LANG['Menu'][33];
                 $menu['admin']['content']['rule']['options']['ocs']['page']='/front/ruleocs.php';
                 $menu['admin']['content']['rule']['options']['ocs']['links']['search']='/front/ruleocs.php';
                 if (Session::haveRight("rule_ocs",UPDATE)) {
                    $menu['admin']['content']['rule']['options']['ocs']['links']['add']='/front/ruleocs.form.php';
                 }
     
                 $menu['admin']['content']['rule']['options']['right']['title']=$LANG['Menu'][37]." / ".$LANG['Menu'][41];
                 $menu['admin']['content']['rule']['options']['right']['page']='/front/ruleright.php';
                 $menu['admin']['content']['rule']['options']['right']['links']['search']='/front/ruleright.php';
                 if (Session::haveRight("rule_ldap",UPDATE)) {
                    $menu['admin']['content']['rule']['options']['right']['links']['add']='/front/ruleright.form.php';
                 }
     
                 $menu['admin']['content']['rule']['options']['mailcollector']['title']=$LANG['rulesengine'][70];
                 $menu['admin']['content']['rule']['options']['mailcollector']['page']='/front/rulemailcollector.php';
                 $menu['admin']['content']['rule']['options']['mailcollector']['links']['search']='/front/rulemailcollector.php';
                 if (Session::haveRight("rule_mailcollector",UPDATE)) {
                    $menu['admin']['content']['rule']['options']['mailcollector']['links']['add']='/front/rulemailcollector.form.php';
                 }
     
                 $menu['admin']['content']['rule']['options']['ticket']['title']=$LANG['Menu'][5];
                 $menu['admin']['content']['rule']['options']['ticket']['page']='/front/ruleticket.php';
                 $menu['admin']['content']['rule']['options']['ticket']['links']['search']='/front/ruleticket.php';
                 if (Session::haveRight("entity_rule_ticket",UPDATE)) {
                    $menu['admin']['content']['rule']['options']['ticket']['links']['add']='/front/ruleticket.form.php';
                 }
     
                 $menu['admin']['content']['rule']['options']['softwarecategories']['title']=$LANG['softwarecategories'][5];
                 $menu['admin']['content']['rule']['options']['softwarecategories']['page']='/front/rulesoftwarecategory.php';
                 $menu['admin']['content']['rule']['options']['softwarecategories']['links']['search']='/front/rulesoftwarecategory.php';
                 if (Session::haveRight("rule_softwarecategories",UPDATE)) {
                    $menu['admin']['content']['rule']['options']['softwarecategories']['links']['add']='/front/rulesoftwarecategory.form.php';
                 }
              }
           }
     
           if (Session::haveRight("rule_dictionnary_dropdown",READ) || Session::haveRight("rule_dictionnary_software",READ)) {
              $menu['admin']['content']['dictionnary']['title']=$LANG['rulesengine'][77];
              $menu['admin']['content']['dictionnary']['shortcut']='r';
              $menu['admin']['content']['dictionnary']['page']='/front/dictionnary.php';
     
              if ($sector=='admin' && $item == 'dictionnary') {
     
                 $menu['admin']['content']['dictionnary']['options']['manufacturers']['title']=$LANG['common'][5];
                 $menu['admin']['content']['dictionnary']['options']['manufacturers']['page']='/front/ruledictionnarymanufacturer.php';
                 $menu['admin']['content']['dictionnary']['options']['manufacturers']['links']['search']='/front/ruledictionnarymanufacturer.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['manufacturers']['links']['add']='/front/ruledictionnarymanufacturer.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['software']['title']=$LANG['Menu'][4];
                 $menu['admin']['content']['dictionnary']['options']['software']['page']='/front/ruledictionnarysoftware.php';
                 $menu['admin']['content']['dictionnary']['options']['software']['links']['search']='/front/ruledictionnarysoftware.php';
                 if (Session::haveRight("rule_dictionnary_software",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['software']['links']['add']='/front/ruledictionnarysoftware.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['model.computer']['title']=$LANG['setup'][91];
                 $menu['admin']['content']['dictionnary']['options']['model.computer']['page']='/front/ruledictionnarycomputermodel.php';
                 $menu['admin']['content']['dictionnary']['options']['model.computer']['links']['search']='/front/ruledictionnarycomputermodel.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['model.computer']['links']['add']='/front/ruledictionnarycomputermodel.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['model.monitor']['title']=$LANG['setup'][94];
                 $menu['admin']['content']['dictionnary']['options']['model.monitor']['page']='/front/ruledictionnarymodelmonitor.php';
                 $menu['admin']['content']['dictionnary']['options']['model.monitor']['links']['search']='/front/ruledictionnarymonitormodel.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['model.monitor']['links']['add']='/front/ruledictionnarymonitormodel.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['model.printer']['title']=$LANG['setup'][96];
                 $menu['admin']['content']['dictionnary']['options']['model.printer']['page']='/front/ruledictionnaryprintermodel.php';
                 $menu['admin']['content']['dictionnary']['options']['model.printer']['links']['search']='/front/ruledictionnaryprintermodel.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['model.printer']['links']['add']='/front/ruledictionnaryprintermodel.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['model.peripheral']['title']=$LANG['setup'][97];
                 $menu['admin']['content']['dictionnary']['options']['model.peripheral']['page']='/front/ruledictionnaryperipheralmodel.php';
                 $menu['admin']['content']['dictionnary']['options']['model.peripheral']['links']['search']='/front/ruledictionnaryperipheralmodel.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['model.peripheral']['links']['add']='/front/ruledictionnaryperipheralmodel.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['model.networking']['title']=$LANG['setup'][95];
                 $menu['admin']['content']['dictionnary']['options']['model.networking']['page']='/front/ruledictionnarynetworkequipmentmodel.php';
                 $menu['admin']['content']['dictionnary']['options']['model.networking']['links']['search']='/front/ruledictionnarynetworkequipmentmodel.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['model.networking']['links']['add']='/front/ruledictionnarynetworkequipmentmodel.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['model.phone']['title']=$LANG['setup'][503];
                 $menu['admin']['content']['dictionnary']['options']['model.phone']['page']='/front/ruledictionnaryphonemodel.php';
                 $menu['admin']['content']['dictionnary']['options']['model.phone']['links']['search']='/front/ruledictionnaryphonemodel.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['model.phone']['links']['add']='/front/ruledictionnaryphonemodel.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['type.computer']['title']=$LANG['setup'][4];
                 $menu['admin']['content']['dictionnary']['options']['type.computer']['page']='/front/ruledictionnarycomputertype.php';
                 $menu['admin']['content']['dictionnary']['options']['type.computer']['links']['search']='/front/ruledictionnarycomputertype.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['type.computer']['links']['add']='/front/ruledictionnarycomputertype.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['type.monitor']['title']=$LANG['setup'][44];
                 $menu['admin']['content']['dictionnary']['options']['type.monitor']['page']='/front/ruledictionnarymonitortype.php';
                 $menu['admin']['content']['dictionnary']['options']['type.monitor']['links']['search']='/front/ruledictionnarymonitortype.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['type.monitor']['links']['add']='/front/ruledictionnarymonitortype.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['type.printer']['title']=$LANG['setup'][43];
                 $menu['admin']['content']['dictionnary']['options']['type.printer']['page']='/front/ruledictionnaryprintertype.php';
                 $menu['admin']['content']['dictionnary']['options']['type.printer']['links']['search']='/front/ruledictionnaryprintertype.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['type.printer']['links']['add']='/front/ruledictionnaryprintertype.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['type.peripheral']['title']=$LANG['setup'][69];
                 $menu['admin']['content']['dictionnary']['options']['type.peripheral']['page']='/front/ruledictionnaryperipheraltype.php';
                 $menu['admin']['content']['dictionnary']['options']['type.peripheral']['links']['search']='/front/ruledictionnaryperipheraltype.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['type.peripheral']['links']['add']='/front/ruledictionnaryperipheraltype.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['type.networking']['title']=$LANG['setup'][42];
                 $menu['admin']['content']['dictionnary']['options']['type.networking']['page']='/front/ruledictionnarynetworkequipmenttype.php';
                 $menu['admin']['content']['dictionnary']['options']['type.networking']['links']['search']='/front/ruledictionnarynetworkequipmenttype.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['type.networking']['links']['add']='/front/ruledictionnarynetworkequipmenttype.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['type.phone']['title']=$LANG['setup'][504];
                 $menu['admin']['content']['dictionnary']['options']['type.phone']['page']='/front/ruledictionnaryphonetype.php';
                 $menu['admin']['content']['dictionnary']['options']['type.phone']['links']['search']='/front/ruledictionnaryphonetype.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['type.phone']['links']['add']='/front/ruledictionnaryphonetype.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['os']['title']=$LANG['computers'][9];
                 $menu['admin']['content']['dictionnary']['options']['os']['page']='/front/ruledictionnaryoperatingsystem.php';
                 $menu['admin']['content']['dictionnary']['options']['os']['links']['search']='/front/ruledictionnaryoperatingsystem.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['os']['links']['add']='/front/ruledictionnaryoperatingsystem.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['os_sp']['title']=$LANG['computers'][53];
                 $menu['admin']['content']['dictionnary']['options']['os_sp']['page']='/front/ruledictionnaryoperatingsystemservicepack.php';
                 $menu['admin']['content']['dictionnary']['options']['os_sp']['links']['search']='/front/ruledictionnaryoperatingsystemservicepack.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['os_sp']['links']['add']='/front/ruledictionnaryoperatingsystemservicepack.form.php';
                 }
     
                 $menu['admin']['content']['dictionnary']['options']['os_version']['title']=$LANG['computers'][52];
                 $menu['admin']['content']['dictionnary']['options']['os_version']['page']='/front/ruledictionnaryoperatingsystemversion.php';
                 $menu['admin']['content']['dictionnary']['options']['os_version']['links']['search']='/front/rruledictionnaryoperatingsystemversion.php';
                 if (Session::haveRight("rule_dictionnary_dropdown",UPDATE)) {
                    $menu['admin']['content']['dictionnary']['options']['os_version']['links']['add']='/front/ruledictionnaryoperatingsystemversion.form.php';
                 }
              }
           }*/
     if (Session::haveRight("profile", READ)) {
         $menu['admin']['content']['profile']['title'] = $LANG['Menu'][35];
         $menu['admin']['content']['profile']['shortcut'] = 'p';
         $menu['admin']['content']['profile']['icon'] = 'icons/key.png';
         $menu['admin']['content']['profile']['page'] = '/front/search.php?itemtype=profile&menu=admin&ssmenu=profile';
         $menu['admin']['content']['profile']['links']['search'] = "/front/profile.php";
         if (Session::haveRight("profile", UPDATE)) {
             $menu['admin']['content']['profile']['links']['add'] = "/front/profile.form.php";
         }
     }
     if (Session::haveRight("transfer", READ) && Session::isMultiEntitiesMode()) {
         $menu['admin']['content']['transfer']['title'] = $LANG['transfer'][1];
         $menu['admin']['content']['transfer']['shortcut'] = 't';
         $menu['admin']['content']['transfer']['icon'] = 'icons/folder_arrow.png';
         $menu['admin']['content']['transfer']['page'] = '/front/search.php?itemtype=transfer&menu=admin&ssmenu=transfer';
         $menu['admin']['content']['transfer']['links']['search'] = "/front/transfer.php";
         if (Session::haveRight("transfer", UPDATE)) {
             $menu['admin']['content']['transfer']['links']['summary'] = "/front/transfer.action.php";
             $menu['admin']['content']['transfer']['links']['add'] = "/front/transfer.form.php";
         }
     }
     /*if (Session::haveRight("backup",UPDATE)) {
          $menu['admin']['content']['backup']['title']=$LANG['Menu'][12];
          $menu['admin']['content']['backup']['shortcut']='b';
          $menu['admin']['content']['backup']['page']='/front/search.php?itemtype=backup&menu=admin&ssmenu=backup';
       }*/
     /*if (Session::haveRight("logs",READ)) {
          $menu['admin']['content']['log']['title']=$LANG['Menu'][30];
          $menu['admin']['content']['log']['shortcut']='l';
          $menu['admin']['content']['log']['page']='/front/event.php';
          $menu['admin']['content']['log']['page']='/front/search.php?itemtype=log&menu=admin&ssmenu=log';
       }*/
     /*/// CONFIG
           $config=array();
           $addconfig=array();
           $menu['config']['title']=$LANG['common'][12];
     
           if (Session::haveRight("dropdown",READ) || Session::haveRight("entity_dropdown",READ)) {
              $menu['config']['content']['dropdowns']['title']=$LANG['setup'][0];
              $menu['config']['content']['dropdowns']['page']='/front/dropdown.php';
              $menu['config']['default']='/front/dropdown.php';
     
              if ($item=="dropdowns") {
                 $dps = Dropdown::getStandardDropdownItemTypes();
     
                 foreach ($dps as $tab) {
                    foreach ($tab as $key => $val) {
                       if ($key == $option) {
                          $tmp = new $key();
                          $menu['config']['content']['dropdowns']['options'][$option]['title']=$val;
                          $menu['config']['content']['dropdowns']['options'][$option]['page']=
                                                        $tmp->getSearchURL(false);
                          $menu['config']['content']['dropdowns']['options'][$option]['links']['search']=
                                                        $tmp->getSearchURL(false);
                          if ($tmp->canCreate()) {
                             $menu['config']['content']['dropdowns']['options'][$option]['links']['add']=
                                                        $tmp->getFormURL(false);
                          }
                       }
                    }
                 }
              }
           }
     
           if (Session::haveRight("device",UPDATE)) {
              $menu['config']['content']['device']['title']=$LANG['title'][30];
              $menu['config']['content']['device']['page']='/front/device.php';
     
              if ($item=="device") {
                 $dps = Dropdown::getDeviceItemTypes();
     
                 foreach ($dps as $tab) {
                    foreach ($tab as $key => $val) {
                       if ($key == $option) {
                          $tmp = new $key();
                          $menu['config']['content']['device']['options'][$option]['title']=$val;
                          $menu['config']['content']['device']['options'][$option]['page']=
                                                        $tmp->getSearchURL(false);
                          $menu['config']['content']['device']['options'][$option]['links']['search']=
                                                        $tmp->getSearchURL(false);
                          if ($tmp->canCreate()) {
                             $menu['config']['content']['device']['options'][$option]['links']['add']=
                                                        $tmp->getFormURL(false);
                          }
                       }
                    }
                 }
              }
           }
     
     
           if (Session::haveRight("config",UPDATE) || Session::haveRight("notification",READ)) {
     
              $menu['config']['content']['mailing']['title']=$LANG['setup'][704];
              $menu['config']['content']['mailing']['page']='/front/setup.notification.php';
              $menu['config']['content']['mailing']['options']['notification']['title']=$LANG['setup'][704];
              $menu['config']['content']['mailing']['options']['notification']['page']='/front/notification.php';
              $menu['config']['content']['mailing']['options']['notification']['links']['add']='/front/notification.form.php';
              $menu['config']['content']['mailing']['options']['notification']['links']['search']='/front/notification.php';
     
           }
     
           if (Session::haveRight("config",UPDATE)) {
     
              $menu['config']['content']['config']['title']=$LANG['setup'][703];
              $menu['config']['content']['config']['page']='/front/config.form.php';
     
              $menu['config']['content']['crontask']['title']=$LANG['crontask'][0];
              $menu['config']['content']['crontask']['page']='/front/crontask.php';
              $menu['config']['content']['crontask']['links']['search']="/front/crontask.php";
     
             $menu['config']['content']['mailing']['options']['config']['title']=$LANG['mailing'][118];
             $menu['config']['content']['mailing']['options']['config']['page']='/front/notificationmailsetting.form.php';
     
              $menu['config']['content']['mailing']['options']['notificationtemplate']['title']=$LANG['mailing'][113];
              $menu['config']['content']['mailing']['options']['notificationtemplate']['page']='/front/notificationtemplate.php';
              $menu['config']['content']['mailing']['options']['notificationtemplate']['links']['add']='/front/notificationtemplate.form.php';
              $menu['config']['content']['mailing']['options']['notificationtemplate']['links']['search']='/front/notificationtemplate.php';
     
              $menu['config']['content']['extauth']['title']=$LANG['login'][10];
              $menu['config']['content']['extauth']['page']='/front/setup.auth.php';
     
              $menu['config']['content']['extauth']['options']['ldap']['title']=$LANG['login'][2];
              $menu['config']['content']['extauth']['options']['ldap']['page']='/front/authldap.php';
     
              $menu['config']['content']['extauth']['options']['imap']['title']=$LANG['login'][3];
              $menu['config']['content']['extauth']['options']['imap']['page']='/front/authmail.php';
     
              $menu['config']['content']['extauth']['options']['others']['title']=$LANG['common'][67];
              $menu['config']['content']['extauth']['options']['others']['page']='/front/auth.others.php';
     
              $menu['config']['content']['extauth']['options']['settings']['title']=$LANG['common'][12];
              $menu['config']['content']['extauth']['options']['settings']['page']='/front/auth.settings.php';
     
              switch ($option) {
                 case "ldap" : // LDAP
                    $menu['config']['content']['extauth']['options']['ldap']['links']['search']='/front/authldap.php';
                    $menu['config']['content']['extauth']['options']['ldap']['links']['add']='' .
                            '/front/authldap.form.php';
                    break;
     
                 case "imap" : // IMAP
                    $menu['config']['content']['extauth']['links']['search']='/front/authmail.php';
                    $menu['config']['content']['extauth']['links']['add']='' .
                            '/front/authmail.form.php';
                    break;
              }
     
              $menu['config']['content']['mailcollector']['title']=$LANG['Menu'][39];
              $menu['config']['content']['mailcollector']['page']='/front/mailcollector.php';
              if (canUseImapPop()) {
                 $menu['config']['content']['mailcollector']['links']['search']='/front/mailcollector.php';
                 $menu['config']['content']['mailcollector']['links']['add']='/front/mailcollector.form.php';
                 $menu['config']['content']['mailcollector']['options']['rejectedemails']['links']['search']='/front/rejectedemail.php';
              }
           }
     
           if ($CFG_GLPI["use_ocs_mode"] && Session::haveRight("config",UPDATE)) {
              $menu['config']['content']['ocsng']['title']=$LANG['setup'][134];
              $menu['config']['content']['ocsng']['page']='/front/ocsserver.php';
              $menu['config']['content']['ocsng']['links']['search']='/front/ocsserver.php';
              $menu['config']['content']['ocsng']['links']['add']='/front/ocsserver.form.php';
           }
     
           if (Session::haveRight("link",READ)) {
              $menu['config']['content']['link']['title']=$LANG['title'][33];
              $menu['config']['content']['link']['page']='/front/link.php';
              $menu['config']['content']['link']['hide']=true;
              $menu['config']['content']['link']['links']['search']='/front/link.php';
              if (Session::haveRight("link",UPDATE)) {
                 $menu['config']['content']['link']['links']['add']="/front/link.form.php";
              }
           }
     
           if (Session::haveRight("config",UPDATE)) {
              $menu['config']['content']['plugins']['title']=$LANG['common'][29];
              $menu['config']['content']['plugins']['page']='/front/plugin.php';
           }
     
     */
     // Special items
     $menu['preference']['title'] = $LANG['Menu'][11];
     $menu['preference']['default'] = '/front/preference.php';
     return $menu;
 }
Esempio n. 15
0
 /**
  * load a bookmark
  *
  * @param $ID                 ID of the bookmark
  * @param $opener    boolean  load bookmark in opener window ? false -> current window
  *                            (true by default)
  *
  * @return nothing
  **/
 function load($ID, $opener = true)
 {
     global $CFG_GLPI;
     if ($params = $this->getParameters($ID)) {
         $url = $CFG_GLPI['root_doc'] . "/" . rawurldecode($this->fields["path"]);
         $url .= "?" . Toolbox::append_params($params);
         if ($opener) {
             echo "<script type='text/javascript' >\n";
             echo "window.parent.location.href='{$url}';";
             echo "</script>";
             exit;
         } else {
             Html::redirect($url);
         }
     }
 }
        // status
        $options2['criteria'][1]['searchtype'] = 'equals';
        $options2['criteria'][1]['value'] = 'notold';
        $options2['criteria'][1]['link'] = 'AND';
        $options2['reset'] = 'reset';
        $url = $ticket->getSearchURL() . "?" . Toolbox::append_params($options2, '&amp;');
        echo "&nbsp;<a href='{$url}' title=\"" . __s('Processing') . "\" target='_blank'>(";
        printf(__('%1$s: %2$s'), __('Processing'), $ticket->countActiveObjectsForTechGroup($_POST['groups_id_assign']));
        echo ")</a>";
    } else {
        if (isset($_POST['suppliers_id_assign']) && $_POST['suppliers_id_assign'] > 0) {
            $ticket = new Ticket();
            $options2['criteria'][0]['field'] = 6;
            // suppliers_id assign
            $options2['criteria'][0]['searchtype'] = 'equals';
            $options2['criteria'][0]['value'] = $_POST['suppliers_id_assign'];
            $options2['criteria'][0]['link'] = 'AND';
            $options2['criteria'][1]['field'] = 12;
            // status
            $options2['criteria'][1]['searchtype'] = 'equals';
            $options2['criteria'][1]['value'] = 'notold';
            $options2['criteria'][1]['link'] = 'AND';
            $options2['reset'] = 'reset';
            $url = $ticket->getSearchURL() . "?" . Toolbox::append_params($options2, '&amp;');
            //TRANS: %d is number of objects for the user
            echo "&nbsp;<a href='{$url}' title=\"" . __s('Processing') . "\" target='_blank'>(";
            printf(__('%1$s: %2$s'), __('Processing'), $ticket->countActiveObjectsForSupplier($_POST['suppliers_id_assign']));
            echo ")</a>";
        }
    }
}
Esempio n. 17
0
 static function showCentralSpecificList($type)
 {
     global $CFG_GLPI, $DB;
     if (!Session::haveRight("ticket", Ticket::READALL) && !Session::haveRight("ticket", Ticket::READASSIGN) && !Session::haveRight("ticket", CREATE) && !Session::haveRight("ticketvalidation", TicketValidation::VALIDATEREQUEST & TicketValidation::VALIDATEINCIDENT)) {
         return false;
     }
     $groups = implode("','", $_SESSION['glpigroups']);
     $numrows = 0;
     $is_deleted = " `glpi_tickets`.`is_deleted` = 0 ";
     if ($type == "notold") {
         $title = __("Tickets to follow (climbed)", "escalade");
         $status = CommonITILObject::INCOMING . ", " . CommonITILObject::PLANNED . ", " . CommonITILObject::ASSIGNED . ", " . CommonITILObject::WAITING;
         $search_assign = " `glpi_plugin_escalade_histories`.`groups_id` IN ('{$groups}')\n            AND (`glpi_groups_tickets`.`groups_id` NOT IN ('{$groups}')\n            OR `glpi_groups_tickets`.`groups_id` IS NULL)";
         $query_join = "LEFT JOIN `glpi_plugin_escalade_histories`\n            ON (`glpi_tickets`.`id` = `glpi_plugin_escalade_histories`.`tickets_id`)\n         LEFT JOIN `glpi_groups_tickets`\n            ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id`\n               AND `glpi_groups_tickets`.`type`=2)";
     } else {
         $title = __("Tickets to close (climbed)", "escalade");
         $status = CommonITILObject::SOLVED;
         $search_assign = " (`glpi_groups_tickets`.`groups_id` IN ('{$groups}'))";
         $query_join = "LEFT JOIN `glpi_groups_tickets`\n            ON (`glpi_tickets`.`id` = `glpi_groups_tickets`.`tickets_id`\n               AND `glpi_groups_tickets`.`type`=2)";
     }
     $query = "SELECT DISTINCT `glpi_tickets`.`id`\n               FROM `glpi_tickets`\n               LEFT JOIN `glpi_tickets_users`\n                  ON (`glpi_tickets`.`id` = `glpi_tickets_users`.`tickets_id`)";
     $query .= $query_join;
     $query .= "WHERE {$is_deleted} AND ( {$search_assign} )\n                            AND (`status` IN ({$status}))" . getEntitiesRestrictRequest("AND", "glpi_tickets");
     $query .= " ORDER BY glpi_tickets.date_mod DESC";
     $result = $DB->query($query);
     $numrows = $DB->numrows($result);
     if (!$numrows) {
         return;
     }
     $query .= " LIMIT 0, 5";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     //show central list
     if ($numrows > 0) {
         //construct link to ticket list
         $options['reset'] = 'reset';
         $options['criteria'][0]['field'] = 12;
         // status
         $options['criteria'][0]['searchtype'] = 'equals';
         if ($type == 'notold') {
             $options['criteria'][0]['value'] = 'notold';
         } else {
             if ($type == 'solved') {
                 $options['criteria'][0]['value'] = 5;
             }
         }
         $options['criteria'][0]['link'] = 'AND';
         if ($type == 'notold') {
             $options['criteria'][1]['field'] = 1881;
             // groups_id_assign for escalade history
             $options['criteria'][1]['searchtype'] = 'equals';
             $options['criteria'][1]['value'] = 'mygroups';
             $options['criteria'][1]['link'] = 'AND';
         }
         $options['criteria'][2]['field'] = 8;
         // groups_id_assign
         if ($type == 'notold') {
             $options['criteria'][2]['searchtype'] = 'notequals';
         } else {
             $options['criteria'][2]['searchtype'] = 'equals';
         }
         $options['criteria'][2]['value'] = 'mygroups';
         $options['criteria'][2]['link'] = 'AND';
         echo "<table class='tab_cadrehov' id='pluginEscaladeCentralList'>";
         echo "<tr><th colspan='5'>";
         echo "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">" . Html::makeTitle($title, $number, $numrows) . "</a>";
         echo "</th></tr>";
         if ($number) {
             echo "<tr>";
             echo "<th></th>";
             echo "<th>" . __('Requester') . "</th>";
             echo "<th>" . __('Associated element') . "</th>";
             echo "<th>" . __('Description') . "</th></tr>";
             for ($i = 0; $i < $number; $i++) {
                 $ID = $DB->result($result, $i, "id");
                 Ticket::showVeryShort($ID, 'Ticket$2');
             }
         }
         echo "</table>";
         echo "<br />";
     }
 }
Esempio n. 18
0
/**
 * Update from 0.84.1 to 0.84.3
 *
 * @return bool for success (will die for most error)
**/
function update0841to0843()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.84.3'));
    $migration->setVersion('0.84.3');
    $backup_tables = false;
    $newtables = array();
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    // Upgrade ticket bookmarks and clean _glpi_csrf_token
    $status = array('new' => CommonITILObject::INCOMING, 'assign' => CommonITILObject::ASSIGNED, 'plan' => CommonITILObject::PLANNED, 'waiting' => CommonITILObject::WAITING, 'solved' => CommonITILObject::SOLVED, 'closed' => CommonITILObject::CLOSED, 'accepted' => CommonITILObject::ACCEPTED, 'observe' => CommonITILObject::OBSERVED, 'evaluation' => CommonITILObject::EVALUATION, 'approbation' => CommonITILObject::APPROVAL, 'test' => CommonITILObject::TEST, 'qualification' => CommonITILObject::QUALIFICATION);
    $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);
                // unset _glpi_csrf_token
                if (isset($options['_glpi_csrf_token'])) {
                    unset($options['_glpi_csrf_token']);
                }
                if (isset($options['field'])) {
                    // update ticket statuses
                    if (($data['itemtype'] == 'Ticket' || $data['itemtype'] == 'Problem') && $data['type'] == Bookmark::SEARCH) {
                        foreach ($options['field'] as $key => $val) {
                            if ($val == 12 && isset($options['contains'][$key])) {
                                if (isset($status[$options['contains'][$key]])) {
                                    $options['contains'][$key] = $status[$options['contains'][$key]];
                                }
                            }
                        }
                    }
                    // Fix computer / allassets bookmarks : 17 -> 7 / 18 -> 8 / 7 -> 17
                    if (($data['itemtype'] == 'Computer' || $data['itemtype'] == 'AllAssets') && $data['type'] == Bookmark::SEARCH) {
                        foreach ($options['field'] as $key => $val) {
                            switch ($val) {
                                case 17:
                                    if (isset($options['contains'][$key])) {
                                        $options['field'][$key] = 7;
                                    }
                                    break;
                                case 18:
                                    if (isset($options['contains'][$key])) {
                                        $options['field'][$key] = 8;
                                    }
                                    break;
                                case 7:
                                    if (isset($options['contains'][$key])) {
                                        $options['field'][$key] = 17;
                                    }
                                    break;
                            }
                        }
                    }
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                        SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                        WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.84.3 update bookmarks");
            }
        }
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
Esempio n. 19
0
 /**
  * Generic Function to display Items
  *
  * @param $itemtype              item type
  * @param $ID                    ID of the SEARCH_OPTION item
  * @param $data            array containing data results
  * @param $num                   item num in the request
  * @param $meta                  is a meta item ? (default 0)
  * @param $addobjectparams array added parameters for union search
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI;
     $showuserlink = 0;
     if (Session::haveRight('user', READ)) {
         $showuserlink = 1;
     }
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) {
             return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']);
         }
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     if (count($addobjectparams)) {
         $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     /// TODO try to clean all specific cases using SpecificToDisplay
     switch ($table . '.' . $field) {
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserName($split[$k], 2);
                             $tooltip = "";
                             if (Session::haveRight('user', READ)) {
                                 $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                             }
                             $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);
                         } else {
                             $out .= getUserName($split[$k], $showuserlink);
                         }
                     }
                 }
                 // Manage alternative_email for tickets_users
                 if ($itemtype == 'Ticket' && isset($data[$NAME . $num . '_2'])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . '_2']);
                     for ($k = 0; $k < count($split); $k++) {
                         $split2 = explode(" ", $split[$k]);
                         if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                         }
                     }
                 }
                 return $out;
             }
             if ($itemtype != 'User') {
                 $toadd = '';
                 if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                     $userdata = getUserName($data[$NAME . $num . "_3"], 2);
                     $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                 }
                 if (Session::haveRight('user', READ)) {
                     $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 1);
                 } else {
                     $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 0);
                 }
                 return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
         case "glpi_profiles.name":
             if ($itemtype == 'User' && $ID == 20) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_entities', $split2[$k]));
                         $comp = '';
                         if ($split3[$k]) {
                             $comp = __(READ);
                             if ($split4[$k]) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                             }
                         }
                         if ($split4[$k]) {
                             $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                         }
                         if (!empty($comp)) {
                             $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_profiles', $split2[$k]));
                         $comp = '';
                         if ($split3[$k]) {
                             $comp = __(READ);
                             if ($split4[$k]) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                             }
                         }
                         if ($split4[$k]) {
                             $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                         }
                         if (!empty($comp)) {
                             $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = Toolbox::strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = Toolbox::strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . sprintf(_n('%d month', '%d months', $duration), $duration);
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
             //          case "glpi_infocoms.sink_time" :
             //             if (!empty($data[$NAME.$num])) {
             //                $split = explode("$$$$", $data[$NAME.$num]);
             //                $out   = '';
             //                foreach ($split as $val) {
             //                   $out .= (empty($out)?'':'<br>');
             //                   if ($val > 0) {
             //                      //TRANS: %d is a number of years
             //                      $out .= sprintf(_n('%d year', '%d years', $val), $val);
             //                   }
             //                }
             //                return $out;
             //             }
             //             return "&nbsp;";
             //
             //          case "glpi_infocoms.warranty_duration" :
             //             if (!empty($data[$NAME.$num])) {
             //                $split = explode("$$$$", $data[$NAME.$num]);
             //                $out   = '';
             //                foreach ($split as $val) {
             //                   $out .= (empty($out)?'':'<br>');
             //                   if ($val > 0) {
             //                      $out .= sprintf(_n('%d month', '%d months', $val), $val);
             //                   }
             //                   if ($val < 0) {
             //                      $out .= __('Lifelong');
             //                   }
             //                }
             //                return $out;
             //             }
             //             return "&nbsp;";
         //          case "glpi_infocoms.sink_time" :
         //             if (!empty($data[$NAME.$num])) {
         //                $split = explode("$$$$", $data[$NAME.$num]);
         //                $out   = '';
         //                foreach ($split as $val) {
         //                   $out .= (empty($out)?'':'<br>');
         //                   if ($val > 0) {
         //                      //TRANS: %d is a number of years
         //                      $out .= sprintf(_n('%d year', '%d years', $val), $val);
         //                   }
         //                }
         //                return $out;
         //             }
         //             return "&nbsp;";
         //
         //          case "glpi_infocoms.warranty_duration" :
         //             if (!empty($data[$NAME.$num])) {
         //                $split = explode("$$$$", $data[$NAME.$num]);
         //                $out   = '';
         //                foreach ($split as $val) {
         //                   $out .= (empty($out)?'':'<br>');
         //                   if ($val > 0) {
         //                      $out .= sprintf(_n('%d month', '%d months', $val), $val);
         //                   }
         //                   if ($val < 0) {
         //                      $out .= __('Lifelong');
         //                   }
         //                }
         //                return $out;
         //             }
         //             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return __s('Warranty expiration date');
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return __('End');
                 case pow(2, Alert::NOTICE):
                     return __('Notice');
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return __('End + Notice');
             }
             return "";
         case "glpi_tickets_tickets.tickets_id_1":
             $out = "";
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
             $displayed = array();
             for ($k = 0; $k < count($split); $k++) {
                 $linkid = $split[$k] == $data['id'] ? $split2[$k] : $split[$k];
                 if ($linkid > 0 && !isset($displayed[$linkid])) {
                     $text = "<a ";
                     $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">";
                     $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>";
                     if (count($displayed)) {
                         $out .= "<br>";
                     }
                     $displayed[$linkid] = $linkid;
                     $out .= $text;
                 }
             }
             return $out;
         case "glpi_problems.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("problem", Problem::READALL)) {
                 if ($itemtype == 'ITILCategory') {
                     $options['field'][0] = 7;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='problem{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                 if ($itemtype == 'User') {
                     $options['field'][0] = 4;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                     $options['field'][1] = 22;
                     $options['searchtype'][1] = 'equals';
                     $options['contains'][1] = $data['id'];
                     $options['link'][1] = 'OR';
                     $options['field'][2] = 5;
                     $options['searchtype'][2] = 'equals';
                     $options['contains'][2] = $data['id'];
                     $options['link'][2] = 'OR';
                 } else {
                     if ($itemtype == 'ITILCategory') {
                         $options['field'][0] = 7;
                         $options['searchtype'][0] = 'equals';
                         $options['contains'][0] = $data['id'];
                         $options['link'][0] = 'AND';
                     } else {
                         $options['field'][0] = 12;
                         $options['searchtype'][0] = 'equals';
                         $options['contains'][0] = 'all';
                         $options['link'][0] = 'AND';
                         $options['itemtype2'][0] = $itemtype;
                         $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                         $options['searchtype2'][0] = 'equals';
                         $options['contains2'][0] = $data['id'];
                         $options['link2'][0] = 'AND';
                     }
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_tickets.due_date":
             // Due date + progress
             if ($ID == 151) {
                 $out = Html::convDate($data[$NAME . $num]);
                 // No due date in waiting status
                 if ($data[$NAME . $num . '_2'] == CommonITILObject::WAITING) {
                     return '';
                 }
                 if (empty($data[$NAME . $num])) {
                     return '';
                 }
                 if ($data[$NAME . $num . '_2'] == Ticket::SOLVED || $data[$NAME . $num . '_2'] == Ticket::CLOSED) {
                     return $data[$NAME . $num];
                 }
                 $ticket = new Ticket();
                 $ticket->getFromDB($data['ITEM_0']);
                 $percentage = 0;
                 $totaltime = 0;
                 $currenttime = 0;
                 if ($ticket->fields['slas_id'] != 0) {
                     // Have SLA
                     $sla = new SLA();
                     $sla->getFromDB($ticket->fields['slas_id']);
                     $currenttime = $sla->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s'));
                     $totaltime = $sla->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]);
                 } else {
                     $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']);
                     if ($calendars_id != 0) {
                         // Ticket entity have calendar
                         $calendar = new Calendar();
                         $calendar->getFromDB($calendars_id);
                         $currenttime = $calendar->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $calendar->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]);
                     } else {
                         // No calendar
                         $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($ticket->fields['date']);
                         $totaltime = strtotime($data[$NAME . $num]) - strtotime($ticket->fields['date']);
                     }
                 }
                 if ($totaltime != 0) {
                     $percentage = round(100 * $currenttime / $totaltime);
                 } else {
                     // Total time is null : no active time
                     $percentage = 100;
                 }
                 if ($percentage > 100) {
                     $percentage = 100;
                 }
                 $percentage_text = $percentage;
                 if ($_SESSION['glpiduedatewarning_unit'] == '%') {
                     $less_warn_limit = $_SESSION['glpiduedatewarning_less'];
                     $less_warn = 100 - $percentage;
                 } else {
                     if ($_SESSION['glpiduedatewarning_unit'] == 'hours') {
                         $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;
                         $less_warn = $totaltime - $currenttime;
                     } else {
                         if ($_SESSION['glpiduedatewarning_unit'] == 'days') {
                             $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;
                             $less_warn = $totaltime - $currenttime;
                         }
                     }
                 }
                 if ($_SESSION['glpiduedatecritical_unit'] == '%') {
                     $less_crit_limit = $_SESSION['glpiduedatecritical_less'];
                     $less_crit = 100 - $percentage;
                 } else {
                     if ($_SESSION['glpiduedatecritical_unit'] == 'hours') {
                         $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;
                         $less_crit = $totaltime - $currenttime;
                     } else {
                         if ($_SESSION['glpiduedatecritical_unit'] == 'days') {
                             $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;
                             $less_crit = $totaltime - $currenttime;
                         }
                     }
                 }
                 $color = $_SESSION['glpiduedateok_color'];
                 if ($less_crit < $less_crit_limit) {
                     $color = $_SESSION['glpiduedatecritical_color'];
                 } else {
                     if ($less_warn < $less_warn_limit) {
                         $color = $_SESSION['glpiduedatewarning_color'];
                     }
                 }
                 //Calculate bar progress
                 $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n                         border: 1px solid #9BA563;' >";
                 $out .= "<div style='position:absolute;'>&nbsp;" . $percentage_text . "%</div>";
                 $out .= "<div class='center' style='background-color: " . $color . ";\n                         width: " . $percentage . "%; height: 12px' ></div>";
                 $out .= "</div>";
                 return $out;
             }
             break;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return __('Unlimited');
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title=\"" . __s('Modify the comment') . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>";
             }
             return "<a title=\"" . __s('Modify the comment') . "\"\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 if (isset($events[$data[$NAME . $num]])) {
                     return $events[$data[$NAME . $num]];
                 }
             }
             return '';
         case 'glpi_reminders.state':
             return Planning::getState($data[$NAME . $num]);
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_changes.status':
             $status = Change::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Change::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_problems.status':
             $status = Problem::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Problem::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Ticket::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && ($item = getItemForItemtype($data[$NAME . $num . "_2"]))) {
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(array('comments' => true));
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.name':
             if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 $link = Toolbox::getItemTypeFormURL('Ticket');
                 foreach ($split as $val) {
                     if (!empty($val)) {
                         $split2 = self::explodeWithID("\$\$", $val);
                         $out .= "<a id='ticket" . $split2[1] . "' href=\"" . $link;
                         $out .= strstr($link, '?') ? '&amp;' : '?';
                         $out .= 'id=' . $split2[1];
                         $out .= "\">";
                         $name = $split2[0];
                         if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]);
                         }
                         $out .= $name . "</a><br>";
                     }
                 }
                 return $out;
             }
             $link = Toolbox::getItemTypeFormURL('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num . "_2"];
             // Force solution tab if solved
             if ($data[$NAME . $num . "_4"] == CommonITILObject::SOLVED) {
                 $out .= "&amp;forcetab=Ticket\$2";
             }
             $out .= "\">";
             $name = $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]);
             }
             $out .= $name . "</a>";
             $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br($data[$NAME . $num . "_3"]), array('applyto' => 'ticket' . $data[$NAME . $num . "_2"], 'display' => false)));
             return $out;
         case 'glpi_ticketvalidations.status':
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 if (!empty($val)) {
                     $split2 = self::explodeWithID("\$\$", $val);
                     $status = TicketValidation::getStatus($split2[0]);
                     $bgcolor = TicketValidation::getStatusColor($split2[0]);
                     $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
                 }
             }
             return $out;
         case 'glpi_ticketsatisfactions.type':
             return TicketSatisfaction::getTypeInquestName($data[$NAME . $num]);
         case 'glpi_ticketsatisfactions.satisfaction':
             return TicketSatisfaction::displaySatisfaction($data[$NAME . $num]);
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     /// TODO try to use getvalueToDisplay instead of redefine display system
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]);
                 if (isset($data[$NAME . $num . "_2"]) && strlen($data[$NAME . $num . "_2"])) {
                     $link = Toolbox::getItemTypeFormURL($linkitemtype);
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"];
                     if (isset($searchopt[$ID]['forcetab'])) {
                         $out .= "&amp;forcetab=" . $searchopt[$ID]['forcetab'];
                     }
                     $out .= "\">";
                     $name = Dropdown::getValueWithUnit($data[$NAME . $num], $unit);
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]);
                     }
                     $out .= $name . "</a>";
                     return $out;
                 }
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $split2 = self::explodeWithID("\$\$", $split[$k]);
                         if (isset($split2[1]) && $split2[1] > 0) {
                             if ($count_display) {
                                 $out .= $separate;
                             }
                             $count_display++;
                             $page = Toolbox::getItemTypeFormURL($linkitemtype);
                             $page .= strpos($page, '?') ? '&id' : '?id';
                             $name = Dropdown::getValueWithUnit($split2[0], $unit);
                             if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                 $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]);
                             }
                             $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $split2[1] . "' href='{$page}=" . $split2[1] . "'>" . $name . "</a>";
                         }
                     }
                 }
                 return $out;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 $count_display = 0;
                 foreach ($split as $val) {
                     if (strlen(trim($val)) > 0) {
                         $split2 = self::explodeWithID("\$\$", $val);
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                             $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($split2[0])));
                         } else {
                             $text = nl2br($split2[0]);
                         }
                         if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) {
                             $rand = mt_rand();
                             $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false)));
                         } else {
                             $out .= $text;
                         }
                     }
                 }
                 return $out;
             case "date":
             case "date_delay":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 $withdays = true;
                 if (isset($searchopt[$ID]['withdays'])) {
                     $withdays = $searchopt[$ID]['withdays'];
                 }
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($val, $withseconds, $withdays);
                 }
                 return $out;
             case "email":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 $count_display = 0;
                 foreach ($split as $val) {
                     $split2 = self::explodeWithID("\$\$", $val);
                     if ($count_display) {
                         $out .= "<br>";
                     }
                     $count_display++;
                     if (!empty($val)) {
                         $out .= empty($out) ? '' : '<br>';
                         $out .= "<a href='mailto:{$split2['0']}'>{$split2['0']}</a>";
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) {
                                 $out .= $searchopt[$ID]['toadd'][$split2[0]];
                             } else {
                                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($split2[0], false, 0));
                                 $out .= Dropdown::getValueWithUnit($number, $unit);
                             }
                         }
                     }
                     return $out;
                 }
                 if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$NAME . $num]])) {
                     return $searchopt[$ID]['toadd'][$data[$NAME . $num]];
                 } else {
                     $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num], false, 0));
                     return Dropdown::getValueWithUnit($number, $unit);
                 }
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) {
                                 $out .= $searchopt[$ID]['toadd'][$split2[0]];
                             } else {
                                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($split2[0]));
                                 $out .= Dropdown::getValueWithUnit($number, $unit);
                             }
                         }
                     }
                     return $out;
                 }
                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num]));
                 return Dropdown::getValueWithUnit($number, $unit);
             case "bool":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($split2[0]), $unit);
                         }
                     }
                     return $out;
                 }
                 return Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$NAME . $num]), $unit);
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if ($obj = getItemForItemtype($data[$NAME . $num])) {
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 }
                 return __('Default value');
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $withoutid = self::explodeWithID("\$\$", $split[$k]);
                 $count_display++;
                 // Get specific display if available
                 $itemtype = getItemTypeForTable($table);
                 if ($item = getItemForItemtype($itemtype)) {
                     $tmpdata = array($field => $withoutid[0]);
                     $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true));
                 }
                 if (!empty($specific)) {
                     $out .= $specific;
                 } else {
                     $out .= Dropdown::getValueWithUnit($withoutid[0], $unit);
                 }
             }
         }
         return $out;
     }
     // Get specific display if available
     $itemtype = getItemTypeForTable($table);
     if ($item = getItemForItemtype($itemtype)) {
         $tmpdata = array($field => $data[$NAME . $num]);
         if (isset($searchopt[$ID]['additionalfields']) && count($searchopt[$ID]['additionalfields'])) {
             foreach ($searchopt[$ID]['additionalfields'] as $key) {
                 $tmpdata[$key] = $data[$NAME . $num . '_' . $key];
             }
         }
         $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true));
         if (!empty($specific)) {
             return $specific;
         }
     }
     // Manage auto CONCAT id
     $split = self::explodeWithID('$$', $data[$NAME . $num]);
     $split[0] = trim($split[0]);
     if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split[0]])) {
         return $searchopt[$ID]['toadd'][$split[0]];
     }
     // Empty is 0 or empty
     if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) {
         return $searchopt[$ID]['emptylabel'];
     }
     return Dropdown::getValueWithUnit($split[0], $unit);
 }
Esempio n. 20
0
/**
 * Update from 0.72.3 to 0.78
 *
 * @return bool for success (will die for most error)
**/
function update0723to078()
{
    global $DB, $migration;
    $updateresult = true;
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.78'));
    $migration->setVersion('0.78');
    //TRANS: %s is 'Clean DB : rename tables'
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB : rename tables'));
    $changes = array();
    $glpi_tables = array('glpi_alerts' => 'glpi_alerts', 'glpi_auth_ldap' => 'glpi_authldaps', 'glpi_auth_ldap_replicate' => 'glpi_authldapreplicates', 'glpi_auth_mail' => 'glpi_authmails', 'glpi_dropdown_auto_update' => 'glpi_autoupdatesystems', 'glpi_bookmark' => 'glpi_bookmarks', 'glpi_display_default' => 'glpi_bookmarks_users', 'glpi_dropdown_budget' => 'glpi_budgets', 'glpi_cartridges' => 'glpi_cartridges', 'glpi_cartridges_type' => 'glpi_cartridgeitems', 'glpi_cartridges_assoc' => 'glpi_cartridges_printermodels', 'glpi_dropdown_cartridge_type' => 'glpi_cartridgeitemtypes', 'glpi_computers' => 'glpi_computers', 'glpi_computerdisks' => 'glpi_computerdisks', 'glpi_dropdown_model' => 'glpi_computermodels', 'glpi_type_computers' => 'glpi_computertypes', 'glpi_connect_wire' => 'glpi_computers_items', 'glpi_inst_software' => 'glpi_computers_softwareversions', 'glpi_config' => 'glpi_configs', 'glpi_consumables' => 'glpi_consumables', 'glpi_consumables_type' => 'glpi_consumableitems', 'glpi_dropdown_consumable_type' => 'glpi_consumableitemtypes', 'glpi_contact_enterprise' => 'glpi_contacts_suppliers', 'glpi_contacts' => 'glpi_contacts', 'glpi_dropdown_contact_type' => 'glpi_contacttypes', 'glpi_contracts' => 'glpi_contracts', 'glpi_dropdown_contract_type' => 'glpi_contracttypes', 'glpi_contract_device' => 'glpi_contracts_items', 'glpi_contract_enterprise' => 'glpi_contracts_suppliers', 'glpi_device_case' => 'glpi_devicecases', 'glpi_dropdown_case_type' => 'glpi_devicecasetypes', 'glpi_device_control' => 'glpi_devicecontrols', 'glpi_device_drive' => 'glpi_devicedrives', 'glpi_device_gfxcard' => 'glpi_devicegraphiccards', 'glpi_device_hdd' => 'glpi_deviceharddrives', 'glpi_device_iface' => 'glpi_devicenetworkcards', 'glpi_device_moboard' => 'glpi_devicemotherboards', 'glpi_device_pci' => 'glpi_devicepcis', 'glpi_device_power' => 'glpi_devicepowersupplies', 'glpi_device_processor' => 'glpi_deviceprocessors', 'glpi_device_ram' => 'glpi_devicememories', 'glpi_dropdown_ram_type' => 'glpi_devicememorytypes', 'glpi_device_sndcard' => 'glpi_devicesoundcards', 'glpi_display' => 'glpi_displaypreferences', 'glpi_docs' => 'glpi_documents', 'glpi_dropdown_rubdocs' => 'glpi_documentcategories', 'glpi_type_docs' => 'glpi_documenttypes', 'glpi_doc_device' => 'glpi_documents_items', 'glpi_dropdown_domain' => 'glpi_domains', 'glpi_entities' => 'glpi_entities', 'glpi_entities_data' => 'glpi_entitydatas', 'glpi_event_log' => 'glpi_events', 'glpi_dropdown_filesystems' => 'glpi_filesystems', 'glpi_groups' => 'glpi_groups', 'glpi_users_groups' => 'glpi_groups_users', 'glpi_infocoms' => 'glpi_infocoms', 'glpi_dropdown_interface' => 'glpi_interfacetypes', 'glpi_kbitems' => 'glpi_knowbaseitems', 'glpi_dropdown_kbcategories' => 'glpi_knowbaseitemcategories', 'glpi_links' => 'glpi_links', 'glpi_links_device' => 'glpi_links_itemtypes', 'glpi_dropdown_locations' => 'glpi_locations', 'glpi_history' => 'glpi_logs', 'glpi_mailgate' => 'glpi_mailcollectors', 'glpi_mailing' => 'glpi_mailingsettings', 'glpi_dropdown_manufacturer' => 'glpi_manufacturers', 'glpi_monitors' => 'glpi_monitors', 'glpi_dropdown_model_monitors' => 'glpi_monitormodels', 'glpi_type_monitors' => 'glpi_monitortypes', 'glpi_dropdown_netpoint' => 'glpi_netpoints', 'glpi_networking' => 'glpi_networkequipments', 'glpi_dropdown_firmware' => 'glpi_networkequipmentfirmwares', 'glpi_dropdown_model_networking' => 'glpi_networkequipmentmodels', 'glpi_type_networking' => 'glpi_networkequipmenttypes', 'glpi_dropdown_iface' => 'glpi_networkinterfaces', 'glpi_networking_ports' => 'glpi_networkports', 'glpi_networking_vlan' => 'glpi_networkports_vlans', 'glpi_networking_wire' => 'glpi_networkports_networkports', 'glpi_dropdown_network' => 'glpi_networks', 'glpi_ocs_admin_link' => 'glpi_ocsadmininfoslinks', 'glpi_ocs_link' => 'glpi_ocslinks', 'glpi_ocs_config' => 'glpi_ocsservers', 'glpi_dropdown_os' => 'glpi_operatingsystems', 'glpi_dropdown_os_sp' => 'glpi_operatingsystemservicepacks', 'glpi_dropdown_os_version' => 'glpi_operatingsystemversions', 'glpi_peripherals' => 'glpi_peripherals', 'glpi_dropdown_model_peripherals' => 'glpi_peripheralmodels', 'glpi_type_peripherals' => 'glpi_peripheraltypes', 'glpi_phones' => 'glpi_phones', 'glpi_dropdown_model_phones' => 'glpi_phonemodels', 'glpi_dropdown_phone_power' => 'glpi_phonepowersupplies', 'glpi_type_phones' => 'glpi_phonetypes', 'glpi_plugins' => 'glpi_plugins', 'glpi_printers' => 'glpi_printers', 'glpi_dropdown_model_printers' => 'glpi_printermodels', 'glpi_type_printers' => 'glpi_printertypes', 'glpi_profiles' => 'glpi_profiles', 'glpi_users_profiles' => 'glpi_profiles_users', 'glpi_registry' => 'glpi_registrykeys', 'glpi_reminder' => 'glpi_reminders', 'glpi_reservation_resa' => 'glpi_reservations', 'glpi_reservation_item' => 'glpi_reservationitems', 'glpi_rules_descriptions' => 'glpi_rules', 'glpi_rules_actions' => 'glpi_ruleactions', 'glpi_rule_cache_model_computer' => 'glpi_rulecachecomputermodels', 'glpi_rule_cache_type_computer' => 'glpi_rulecachecomputertypes', 'glpi_rule_cache_manufacturer' => 'glpi_rulecachemanufacturers', 'glpi_rule_cache_model_monitor' => 'glpi_rulecachemonitormodels', 'glpi_rule_cache_type_monitor' => 'glpi_rulecachemonitortypes', 'glpi_rule_cache_model_networking' => 'glpi_rulecachenetworkequipmentmodels', 'glpi_rule_cache_type_networking' => 'glpi_rulecachenetworkequipmenttypes', 'glpi_rule_cache_os' => 'glpi_rulecacheoperatingsystems', 'glpi_rule_cache_os_sp' => 'glpi_rulecacheoperatingsystemservicepacks', 'glpi_rule_cache_os_version' => 'glpi_rulecacheoperatingsystemversions', 'glpi_rule_cache_model_peripheral' => 'glpi_rulecacheperipheralmodels', 'glpi_rule_cache_type_peripheral' => 'glpi_rulecacheperipheraltypes', 'glpi_rule_cache_model_phone' => 'glpi_rulecachephonemodels', 'glpi_rule_cache_type_phone' => 'glpi_rulecachephonetypes', 'glpi_rule_cache_model_printer' => 'glpi_rulecacheprintermodels', 'glpi_rule_cache_type_printer' => 'glpi_rulecacheprintertypes', 'glpi_rule_cache_software' => 'glpi_rulecachesoftwares', 'glpi_rules_criterias' => 'glpi_rulecriterias', 'glpi_rules_ldap_parameters' => 'glpi_rulerightparameters', 'glpi_software' => 'glpi_softwares', 'glpi_dropdown_software_category' => 'glpi_softwarecategories', 'glpi_softwarelicenses' => 'glpi_softwarelicenses', 'glpi_dropdown_licensetypes' => 'glpi_softwarelicensetypes', 'glpi_softwareversions' => 'glpi_softwareversions', 'glpi_dropdown_state' => 'glpi_states', 'glpi_enterprises' => 'glpi_suppliers', 'glpi_dropdown_enttype' => 'glpi_suppliertypes', 'glpi_tracking' => 'glpi_tickets', 'glpi_dropdown_tracking_category' => 'glpi_ticketcategories', 'glpi_followups' => 'glpi_ticketfollowups', 'glpi_tracking_planning' => 'glpi_ticketplannings', 'glpi_transfers' => 'glpi_transfers', 'glpi_users' => 'glpi_users', 'glpi_dropdown_user_titles' => 'glpi_usertitles', 'glpi_dropdown_user_types' => 'glpi_usercategories', 'glpi_dropdown_vlan' => 'glpi_vlans');
    $backup_tables = false;
    foreach ($glpi_tables as $original_table => $new_table) {
        if (strcmp($original_table, $new_table) != 0) {
            // Original table exists ?
            if (TableExists($original_table)) {
                // rename new tables if exists ?
                if (TableExists($new_table)) {
                    if (TableExists("backup_{$new_table}")) {
                        $query = "DROP TABLE `backup_" . $new_table . "`";
                        $DB->queryOrDie($query, "0.78 drop backup table backup_{$new_table}");
                    }
                    $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
                    $backup_tables = true;
                    $query = "RENAME TABLE `{$new_table}`\n                         TO `backup_{$new_table}`";
                    $DB->queryOrDie($query, "0.78 backup table {$new_table}");
                }
                // rename original table
                $query = "RENAME TABLE `{$original_table}`\n                      TO `{$new_table}`";
                $DB->queryOrDie($query, "0.78 rename {$original_table} to {$new_table}");
            }
        }
        if (FieldExists($new_table, 'ID', false)) {
            // ALTER ID -> id
            $changes[$new_table][] = "CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: rename foreign keys'));
    $foreignkeys = array('assign' => array(array('to' => 'users_id_assign', 'tables' => array('glpi_tickets'))), 'assign_group' => array(array('to' => 'groups_id_assign', 'tables' => array('glpi_tickets'))), 'assign_ent' => array(array('to' => 'suppliers_id_assign', 'tables' => array('glpi_tickets'))), 'auth_method' => array(array('to' => 'authtype', 'noindex' => array('glpi_users'), 'tables' => array('glpi_users'))), 'author' => array(array('to' => 'users_id', 'tables' => array('glpi_ticketfollowups', 'glpi_knowbaseitems', 'glpi_tickets'))), 'auto_update' => array(array('to' => 'autoupdatesystems_id', 'tables' => array('glpi_computers'))), 'budget' => array(array('to' => 'budgets_id', 'tables' => array('glpi_infocoms'))), 'buy_version' => array(array('to' => 'softwareversions_id_buy', 'tables' => array('glpi_softwarelicenses'))), 'category' => array(array('to' => 'ticketcategories_id', 'tables' => array('glpi_tickets')), array('to' => 'softwarecategories_id', 'tables' => array('glpi_softwares'))), 'categoryID' => array(array('to' => 'knowbaseitemcategories_id', 'tables' => array('glpi_knowbaseitems'))), 'category_on_software_delete' => array(array('to' => 'softwarecategories_id_ondelete', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'category applyed when a software is deleted'))), 'cID' => array(array('to' => 'computers_id', 'tables' => array('glpi_computers_softwareversions'))), 'computer' => array(array('to' => 'items_id', 'noindex' => array('glpi_tickets'), 'tables' => array('glpi_tickets'))), 'computer_id' => array(array('to' => 'computers_id', 'tables' => array('glpi_registrykeys'))), 'contract_type' => array(array('to' => 'contracttypes_id', 'tables' => array('glpi_contracts'))), 'default_rubdoc_tracking' => array(array('to' => 'documentcategories_id_forticket', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'default category for documents added with a ticket'))), 'default_state' => array(array('to' => 'states_id_default', 'noindex' => array('glpi_ocsservers'), 'tables' => array('glpi_ocsservers'))), 'device_type' => array(array('to' => 'itemtype', 'noindex' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_bookmarks_users', 'glpi_documents_items', 'glpi_infocoms', 'glpi_links_itemtypes', 'glpi_networkports', 'glpi_reservationitems', 'glpi_tickets'), 'tables' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms', 'glpi_bookmarks', 'glpi_bookmarks_users', 'glpi_links_itemtypes', 'glpi_networkports', 'glpi_reservationitems', 'glpi_tickets'))), 'domain' => array(array('to' => 'domains_id', 'tables' => array('glpi_computers', 'glpi_networkequipments', 'glpi_printers'))), 'end1' => array(array('to' => 'items_id', 'noindex' => array('glpi_computers_items'), 'tables' => array('glpi_computers_items'), 'comments' => array('glpi_computers_items' => 'RELATION to various table, according to itemtype (ID)')), array('to' => 'networkports_id_1', 'noindex' => array('glpi_networkports_networkports'), 'tables' => array('glpi_networkports_networkports'))), 'end2' => array(array('to' => 'computers_id', 'tables' => array('glpi_computers_items')), array('to' => 'networkports_id_2', 'tables' => array('glpi_networkports_networkports'))), 'extra_ldap_server' => array(array('to' => 'authldaps_id_extra', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'extra server'))), 'firmware' => array(array('to' => 'networkequipmentfirmwares_id', 'tables' => array('glpi_networkequipments'))), 'FK_bookmark' => array(array('to' => 'bookmarks_id', 'tables' => array('glpi_bookmarks_users'))), 'FK_computers' => array(array('to' => 'computers_id', 'tables' => array('glpi_computerdisks', 'glpi_softwarelicenses'))), 'FK_contact' => array(array('to' => 'contacts_id', 'tables' => array('glpi_contacts_suppliers'))), 'FK_contract' => array(array('to' => 'contracts_id', 'noindex' => array('glpi_contracts_items'), 'tables' => array('glpi_contracts_suppliers', 'glpi_contracts_items'))), 'FK_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms'), 'tables' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms'))), 'FK_doc' => array(array('to' => 'documents_id', 'noindex' => array('glpi_documents_items'), 'tables' => array('glpi_documents_items'))), 'FK_enterprise' => array(array('to' => 'suppliers_id', 'noindex' => array('glpi_contacts_suppliers', 'glpi_contracts_suppliers'), 'tables' => array('glpi_contacts_suppliers', 'glpi_contracts_suppliers', 'glpi_infocoms'))), 'FK_entities' => array(array('to' => 'entities_id', 'noindex' => array('glpi_locations', 'glpi_netpoints', 'glpi_entitydatas'), 'tables' => array('glpi_bookmarks', 'glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_locations', 'glpi_netpoints', 'glpi_suppliers', 'glpi_entitydatas', 'glpi_groups', 'glpi_knowbaseitems', 'glpi_links', 'glpi_mailcollectors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_reminders', 'glpi_rules', 'glpi_softwares', 'glpi_softwarelicenses', 'glpi_tickets', 'glpi_users', 'glpi_profiles_users'), 'default' => array('glpi_bookmarks' => "-1"))), 'FK_filesystems' => array(array('to' => 'filesystems_id', 'tables' => array('glpi_computerdisks'))), 'FK_glpi_cartridges_type' => array(array('to' => 'cartridgeitems_id', 'tables' => array('glpi_cartridges', 'glpi_cartridges_printermodels'))), 'FK_glpi_consumables_type' => array(array('to' => 'consumableitems_id', 'noindex' => array(''), 'tables' => array('glpi_consumables'))), 'FK_glpi_dropdown_model_printers' => array(array('to' => 'printermodels_id', 'noindex' => array('glpi_cartridges_printermodels'), 'tables' => array('glpi_cartridges_printermodels'))), 'FK_glpi_enterprise' => array(array('to' => 'manufacturers_id', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_devicecases', 'glpi_devicecontrols', 'glpi_devicedrives', 'glpi_devicegraphiccards', 'glpi_deviceharddrives', 'glpi_devicenetworkcards', 'glpi_devicemotherboards', 'glpi_devicepcis', 'glpi_devicepowersupplies', 'glpi_deviceprocessors', 'glpi_devicememories', 'glpi_devicesoundcards', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'FK_glpi_printers' => array(array('to' => 'printers_id', 'tables' => array('glpi_cartridges'))), 'FK_group' => array(array('to' => 'groups_id', 'tables' => array('glpi_tickets'))), 'FK_groups' => array(array('to' => 'groups_id', 'tables' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares', 'glpi_groups_users'))), 'FK_interface' => array(array('to' => 'interfacetypes_id', 'tables' => array('glpi_devicegraphiccards'))), 'FK_item' => array(array('to' => 'items_id', 'noindex' => array('glpi_mailingsettings'), 'tables' => array('glpi_mailingsettings'))), 'FK_links' => array(array('to' => 'links_id', 'tables' => array('glpi_links_itemtypes'))), 'FK_port' => array(array('to' => 'networkports_id', 'noindex' => array('glpi_networkports_vlans'), 'tables' => array('glpi_networkports_vlans'))), 'FK_profiles' => array(array('to' => 'profiles_id', 'tables' => array('glpi_profiles_users', 'glpi_users'))), 'FK_rules' => array(array('to' => 'rules_id', 'tables' => array('glpi_rulecriterias', 'glpi_ruleactions'))), 'FK_tracking' => array(array('to' => 'tickets_id', 'tables' => array('glpi_documents'))), 'FK_users' => array(array('to' => 'users_id', 'noindex' => array('glpi_displaypreferences', 'glpi_bookmarks_users', 'glpi_groups_users'), 'tables' => array('glpi_bookmarks', 'glpi_displaypreferences', 'glpi_documents', 'glpi_groups', 'glpi_reminders', 'glpi_bookmarks_users', 'glpi_groups_users', 'glpi_profiles_users', 'glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'FK_vlan' => array(array('to' => 'vlans_id', 'tables' => array('glpi_networkports_vlans'))), 'glpi_id' => array(array('to' => 'computers_id', 'tables' => array('glpi_ocslinks'))), 'id_assign' => array(array('to' => 'users_id', 'tables' => array('glpi_ticketplannings'))), 'id_auth' => array(array('to' => 'auths_id', 'noindex' => array('glpi_users'), 'tables' => array('glpi_users'))), 'id_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_reservationitems'), 'tables' => array('glpi_reservationitems'))), 'id_followup' => array(array('to' => 'ticketfollowups_id', 'tables' => array('glpi_ticketplannings'))), 'id_item' => array(array('to' => 'reservationitems_id', 'tables' => array('glpi_reservations'))), 'id_user' => array(array('to' => 'users_id', 'tables' => array('glpi_consumables', 'glpi_reservations'))), 'iface' => array(array('to' => 'networkinterfaces_id', 'tables' => array('glpi_networkports'))), 'interface' => array(array('to' => 'interfacetypes_id', 'tables' => array('glpi_devicecontrols', 'glpi_deviceharddrives', 'glpi_devicedrives'))), 'item' => array(array('to' => 'items_id', 'noindex' => array('glpi_events'), 'tables' => array('glpi_events'))), 'link_if_status' => array(array('to' => 'states_id_linkif', 'noindex' => array('glpi_ocsservers'), 'tables' => array('glpi_ocsservers'))), 'location' => array(array('to' => 'locations_id', 'noindex' => array('glpi_netpoints'), 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_netpoints', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_users', 'glpi_softwares'))), 'model' => array(array('to' => 'computermodels_id', 'tables' => array('glpi_computers')), array('to' => 'monitormodels_id', 'tables' => array('glpi_monitors')), array('to' => 'networkequipmentmodels_id', 'tables' => array('glpi_networkequipments')), array('to' => 'peripheralmodels_id', 'tables' => array('glpi_peripherals')), array('to' => 'phonemodels_id', 'tables' => array('glpi_phones')), array('to' => 'printermodels_id', 'tables' => array('glpi_printers'))), 'netpoint' => array(array('to' => 'netpoints_id', 'tables' => array('glpi_networkports'))), 'network' => array(array('to' => 'networks_id', 'tables' => array('glpi_computers', 'glpi_networkequipments', 'glpi_printers'))), 'ocs_id' => array(array('to' => 'ocsid', 'noindex' => array('glpi_ocslinks'), 'tables' => array('glpi_ocslinks'))), 'ocs_server_id' => array(array('to' => 'ocsservers_id', 'noindex' => array('glpi_ocslinks'), 'tables' => array('glpi_ocsadmininfoslinks', 'glpi_ocslinks'))), 'on_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_networkports'), 'tables' => array('glpi_networkports'))), 'os' => array(array('to' => 'operatingsystems_id', 'tables' => array('glpi_computers'))), 'os_sp' => array(array('to' => 'operatingsystemservicepacks_id', 'tables' => array('glpi_computers'))), 'os_version' => array(array('to' => 'operatingsystemversions_id', 'tables' => array('glpi_computers'))), 'parentID' => array(array('to' => 'knowbaseitemcategories_id', 'noindex' => array('glpi_knowbaseitemcategories'), 'tables' => array('glpi_knowbaseitemcategories')), array('to' => 'locations_id', 'tables' => array('glpi_locations')), array('to' => 'ticketcategories_id', 'tables' => array('glpi_ticketcategories')), array('to' => 'entities_id', 'tables' => array('glpi_entities'))), 'platform' => array(array('to' => 'operatingsystems_id', 'tables' => array('glpi_softwares'))), 'power' => array(array('to' => 'phonepowersupplies_id', 'tables' => array('glpi_phones'))), 'recipient' => array(array('to' => 'users_id_recipient', 'tables' => array('glpi_tickets'))), 'rubrique' => array(array('to' => 'documentcategories_id', 'tables' => array('glpi_documents'))), 'rule_id' => array(array('to' => 'rules_id', 'tables' => array('glpi_rulecachemanufacturers', 'glpi_rulecachecomputermodels', 'glpi_rulecachemonitormodels', 'glpi_rulecachenetworkequipmentmodels', 'glpi_rulecacheperipheralmodels', 'glpi_rulecachephonemodels', 'glpi_rulecacheprintermodels', 'glpi_rulecacheoperatingsystems', 'glpi_rulecacheoperatingsystemservicepacks', 'glpi_rulecacheoperatingsystemversions', 'glpi_rulecachesoftwares', 'glpi_rulecachecomputertypes', 'glpi_rulecachemonitortypes', 'glpi_rulecachenetworkequipmenttypes', 'glpi_rulecacheperipheraltypes', 'glpi_rulecachephonetypes', 'glpi_rulecacheprintertypes'))), 'server_id' => array(array('to' => 'authldaps_id', 'tables' => array('glpi_authldapreplicates'))), 'sID' => array(array('to' => 'softwares_id', 'tables' => array('glpi_softwarelicenses', 'glpi_softwareversions'))), 'state' => array(array('to' => 'states_id', 'tables' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwareversions'))), 'tech_num' => array(array('to' => 'users_id_tech', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'title' => array(array('to' => 'usertitles_id', 'tables' => array('glpi_users'))), 'tracking' => array(array('to' => 'tickets_id', 'tables' => array('glpi_ticketfollowups'))), 'type' => array(array('to' => 'cartridgeitemtypes_id', 'tables' => array('glpi_cartridgeitems')), array('to' => 'computertypes_id', 'tables' => array('glpi_computers')), array('to' => 'consumableitemtypes_id', 'tables' => array('glpi_consumableitems')), array('to' => 'contacttypes_id', 'tables' => array('glpi_contacts')), array('to' => 'devicecasetypes_id', 'tables' => array('glpi_devicecases')), array('to' => 'devicememorytypes_id', 'tables' => array('glpi_devicememories')), array('to' => 'suppliertypes_id', 'tables' => array('glpi_suppliers')), array('to' => 'monitortypes_id', 'tables' => array('glpi_monitors')), array('to' => 'networkequipmenttypes_id', 'tables' => array('glpi_networkequipments')), array('to' => 'peripheraltypes_id', 'tables' => array('glpi_peripherals')), array('to' => 'phonetypes_id', 'tables' => array('glpi_phones')), array('to' => 'printertypes_id', 'tables' => array('glpi_printers')), array('to' => 'softwarelicensetypes_id', 'tables' => array('glpi_softwarelicenses')), array('to' => 'usercategories_id', 'tables' => array('glpi_users')), array('to' => 'itemtype', 'noindex' => array('glpi_computers_items'), 'tables' => array('glpi_computers_items', 'glpi_displaypreferences'))), 'update_software' => array(array('to' => 'softwares_id', 'tables' => array('glpi_softwares'))), 'use_version' => array(array('to' => 'softwareversions_id_use', 'tables' => array('glpi_softwarelicenses'))), 'vID' => array(array('to' => 'softwareversions_id', 'tables' => array('glpi_computers_softwareversions'))));
    foreach ($foreignkeys as $oldname => $newnames) {
        foreach ($newnames as $tab) {
            $newname = $tab['to'];
            foreach ($tab['tables'] as $table) {
                $doindex = true;
                if (isset($tab['noindex']) && in_array($table, $tab['noindex'])) {
                    $doindex = false;
                }
                // Rename field
                if (FieldExists($table, $oldname, false)) {
                    $addcomment = '';
                    if (isset($tab['comments']) && isset($tab['comments'][$table])) {
                        $addcomment = " COMMENT '" . $tab['comments'][$table] . "' ";
                    }
                    $default_value = 0;
                    if (isset($tab['default']) && isset($tab['default'][$table])) {
                        $default_value = $tab['default'][$table];
                    }
                    // Manage NULL fields
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = '{$default_value}'\n                         WHERE `{$oldname}` IS NULL ";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                    $changes[$table][] = "CHANGE COLUMN `{$oldname}` `{$newname}` INT( 11 ) NOT NULL\n                                                   DEFAULT '{$default_value}' {$addcomment}";
                } else {
                    $updateresult = false;
                    $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
                }
                // If do index : delete old one / create new one
                if ($doindex) {
                    if (!isIndex($table, $newname)) {
                        $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                    }
                    if ($oldname != $newname && isIndex($table, $oldname)) {
                        $changes[$table][] = "DROP INDEX `{$oldname}`";
                    }
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: rename bool values'));
    $boolfields = array('glpi_authldaps' => array(array('from' => 'ldap_use_tls', 'to' => 'use_tls', 'default' => 0, 'noindex ' => true), array('from' => 'use_dn', 'to' => 'use_dn', 'default' => 1, 'noindex' => true)), 'glpi_bookmarks' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 1), array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0)), 'glpi_cartridgeitems' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_computers' => array(array('from' => 'is_template', 'to' => 'is_template', 'default' => 0), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'ocs_import', 'to' => 'is_ocs_import', 'default' => 0)), 'glpi_configs' => array(array('from' => 'jobs_at_login', 'to' => 'show_jobs_at_login', 'default' => 0, 'noindex' => true), array('from' => 'mailing', 'to' => 'use_mailing', 'default' => 0, 'noindex' => true), array('from' => 'permit_helpdesk', 'to' => 'use_anonymous_helpdesk', 'default' => 0, 'noindex' => true), array('from' => 'existing_auth_server_field_clean_domain', 'to' => 'existing_auth_server_field_clean_domain', 'default' => 0, 'noindex' => true), array('from' => 'auto_assign', 'to' => 'use_auto_assign_to_tech', 'default' => 0, 'noindex' => true), array('from' => 'public_faq', 'to' => 'use_public_faq', 'default' => 0, 'noindex' => true), array('from' => 'url_in_mail', 'to' => 'show_link_in_mail', 'default' => 0, 'noindex' => true), array('from' => 'use_ajax', 'to' => 'use_ajax', 'default' => 0, 'noindex' => true), array('from' => 'ajax_autocompletion', 'to' => 'use_ajax_autocompletion', 'default' => 1, 'noindex' => true), array('from' => 'auto_add_users', 'to' => 'is_users_auto_add', 'default' => 1, 'noindex' => true), array('from' => 'view_ID', 'to' => 'is_ids_visible', 'default' => 0, 'noindex' => true), array('from' => 'ocs_mode', 'to' => 'use_ocs_mode', 'default' => 0, 'noindex' => true), array('from' => 'followup_on_update_ticket', 'to' => 'add_followup_on_update_ticket', 'default' => 1, 'noindex' => true), array('from' => 'licenses_alert', 'to' => 'use_licenses_alert', 'default' => 0, 'noindex' => true), array('from' => 'keep_tracking_on_delete', 'to' => 'keep_tickets_on_delete', 'default' => 1, 'noindex' => true), array('from' => 'use_errorlog', 'to' => 'use_log_in_files', 'default' => 0, 'noindex ' => true), array('from' => 'autoupdate_link_contact', 'to' => 'is_contact_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoupdate_link_user', 'to' => 'is_user_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoupdate_link_group', 'to' => 'is_group_autoupdate', 'default' => 1, 'noindex ' => true), array('from' => 'autoupdate_link_location', 'to' => 'is_location_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoclean_link_contact', 'to' => 'is_contact_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_user', 'to' => 'is_user_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_group', 'to' => 'is_group_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_location', 'to' => 'is_location_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'flat_dropdowntree', 'to' => 'use_flat_dropdowntree', 'default' => 0, 'noindex' => true), array('from' => 'autoname_entity', 'to' => 'use_autoname_by_entity', 'default' => 1, 'noindex' => true), array('from' => 'expand_soft_categorized', 'to' => 'is_categorized_soft_expanded', 'default' => 1, 'noindex' => true), array('from' => 'expand_soft_not_categorized', 'to' => 'is_not_categorized_soft_expanded', 'default' => 1, 'noindex' => true), array('from' => 'ticket_title_mandatory', 'to' => 'is_ticket_title_mandatory', 'default' => 0, 'noindex' => true), array('from' => 'ticket_content_mandatory', 'to' => 'is_ticket_content_mandatory', 'default' => 1, 'noindex' => true), array('from' => 'ticket_category_mandatory', 'to' => 'is_ticket_category_mandatory', 'default' => 0, 'noindex' => true), array('from' => 'followup_private', 'to' => 'followup_private', 'default' => 0, 'noindex' => true), array('from' => 'software_helpdesk_visible', 'to' => 'default_software_helpdesk_visible', 'default' => 1, 'noindex' => true)), 'glpi_consumableitems' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_contacts' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_contracts' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'monday', 'to' => 'use_monday', 'default' => 0), array('from' => 'saturday', 'to' => 'use_saturday', 'default' => 0)), 'glpi_devicecontrols' => array(array('from' => 'raid', 'to' => 'is_raid', 'default' => 0, 'noindex' => true)), 'glpi_devicedrives' => array(array('from' => 'is_writer', 'to' => 'is_writer', 'default' => 1, 'noindex' => true)), 'glpi_devicepowersupplies' => array(array('from' => 'atx', 'to' => 'is_atx', 'default' => 1, 'noindex' => true)), 'glpi_documents' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_documenttypes' => array(array('from' => 'upload', 'to' => 'is_uploadable', 'default' => 1)), 'glpi_groups' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true)), 'glpi_knowbaseitems' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1, 'noindex' => true), array('from' => 'faq', 'to' => 'is_faq', 'default' => 0)), 'glpi_links' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1, 'noindex' => true)), 'glpi_monitors' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_micro', 'to' => 'have_micro', 'default' => 0, 'noindex' => true), array('from' => 'flags_speaker', 'to' => 'have_speaker', 'default' => 0, 'noindex' => true), array('from' => 'flags_subd', 'to' => 'have_subd', 'default' => 0, 'noindex' => true), array('from' => 'flags_bnc', 'to' => 'have_bnc', 'default' => 0, 'noindex' => true), array('from' => 'flags_dvi', 'to' => 'have_dvi', 'default' => 0, 'noindex' => true), array('from' => 'flags_pivot', 'to' => 'have_pivot', 'default' => 0, 'noindex' => true)), 'glpi_networkequipments' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true)), 'glpi_ocslinks' => array(array('from' => 'auto_update', 'to' => 'use_auto_update', 'default' => 1)), 'glpi_ocsservers' => array(array('from' => 'import_periph', 'to' => 'import_periph', 'default' => 0, 'noindex' => true), array('from' => 'import_monitor', 'to' => 'import_monitor', 'default' => 0, 'noindex' => true), array('from' => 'import_software', 'to' => 'import_software', 'default' => 0, 'noindex' => true), array('from' => 'import_printer', 'to' => 'import_printer', 'default' => 0, 'noindex' => true), array('from' => 'import_general_name', 'to' => 'import_general_name', 'default' => 0, 'noindex' => true), array('from' => 'import_general_os', 'to' => 'import_general_os', 'default' => 0, 'noindex' => true), array('from' => 'import_general_serial', 'to' => 'import_general_serial', 'default' => 0, 'noindex' => true), array('from' => 'import_general_model', 'to' => 'import_general_model', 'default' => 0, 'noindex' => true), array('from' => 'import_general_enterprise', 'to' => 'import_general_manufacturer', 'default' => 0, 'noindex' => true), array('from' => 'import_general_type', 'to' => 'import_general_type', 'default' => 0, 'noindex' => true), array('from' => 'import_general_domain', 'to' => 'import_general_domain', 'default' => 0, 'noindex' => true), array('from' => 'import_general_contact', 'to' => 'import_general_contact', 'default' => 0, 'noindex' => true), array('from' => 'import_general_comments', 'to' => 'import_general_comment', 'default' => 0, 'noindex' => true), array('from' => 'import_device_processor', 'to' => 'import_device_processor', 'default' => 0, 'noindex' => true), array('from' => 'import_device_memory', 'to' => 'import_device_memory', 'default' => 0, 'noindex' => true), array('from' => 'import_device_hdd', 'to' => 'import_device_hdd', 'default' => 0, 'noindex' => true), array('from' => 'import_device_iface', 'to' => 'import_device_iface', 'default' => 0, 'noindex' => true), array('from' => 'import_device_gfxcard', 'to' => 'import_device_gfxcard', 'default' => 0, 'noindex' => true), array('from' => 'import_device_sound', 'to' => 'import_device_sound', 'default' => 0, 'noindex' => true), array('from' => 'import_device_drives', 'to' => 'import_device_drive', 'default' => 0, 'noindex' => true), array('from' => 'import_device_ports', 'to' => 'import_device_port', 'default' => 0, 'noindex' => true), array('from' => 'import_device_modems', 'to' => 'import_device_modem', 'default' => 0, 'noindex' => true), array('from' => 'import_registry', 'to' => 'import_registry', 'default' => 0, 'noindex' => true), array('from' => 'import_os_serial', 'to' => 'import_os_serial', 'default' => 0, 'noindex' => true), array('from' => 'import_ip', 'to' => 'import_ip', 'default' => 0, 'noindex' => true), array('from' => 'import_disk', 'to' => 'import_disk', 'default' => 0, 'noindex' => true), array('from' => 'import_monitor_comments', 'to' => 'import_monitor_comment', 'default' => 0, 'noindex' => true), array('from' => 'glpi_link_enabled', 'to' => 'is_glpi_link_enabled', 'default' => 0, 'noindex' => true), array('from' => 'link_ip', 'to' => 'use_ip_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_name', 'to' => 'use_name_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_mac_address', 'to' => 'use_mac_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_serial', 'to' => 'use_serial_to_link', 'default' => 0, 'noindex' => true), array('from' => 'use_soft_dict', 'to' => 'use_soft_dict', 'default' => 0, 'noindex' => true)), 'glpi_peripherals' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true)), 'glpi_phones' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_hp', 'to' => 'have_hp', 'default' => 0, 'noindex' => true), array('from' => 'flags_casque', 'to' => 'have_headset', 'default' => 0, 'noindex' => true)), 'glpi_printers' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_usb', 'to' => 'have_usb', 'default' => 0, 'noindex' => true), array('from' => 'flags_par', 'to' => 'have_parallel', 'default' => 0, 'noindex' => true), array('from' => 'flags_serial', 'to' => 'have_serial', 'default' => 0, 'noindex' => true)), 'glpi_profiles_users' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1), array('from' => 'dynamic', 'to' => 'is_dynamic', 'default' => 0)), 'glpi_profiles' => array(array('from' => 'is_default', 'to' => 'is_default', 'default' => 0)), 'glpi_reminders' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 1), array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0), array('from' => 'rv', 'to' => 'is_planned', 'default' => 0)), 'glpi_reservationitems' => array(array('from' => 'active', 'to' => 'is_active', 'default' => 1)), 'glpi_rules' => array(array('from' => 'active', 'to' => 'is_active', 'default' => 1)), 'glpi_suppliers' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_softwares' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'helpdesk_visible', 'to' => 'is_helpdesk_visible', 'default' => 1), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_update', 'to' => 'is_update', 'default' => 0, 'noindex' => true)), 'glpi_softwarelicenses' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true)), 'glpi_tickets' => array(array('from' => 'emailupdates', 'to' => 'use_email_notification', 'default' => 0, 'noindex' => true)), 'glpi_ticketfollowups' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 0)), 'glpi_users' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'active', 'to' => 'is_active', 'default' => 1), array('from' => 'jobs_at_login', 'to' => 'show_jobs_at_login', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'followup_private', 'to' => 'followup_private', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'expand_soft_categorized', 'to' => 'is_categorized_soft_expanded', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'expand_soft_not_categorized', 'to' => 'is_not_categorized_soft_expanded', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'flat_dropdowntree', 'to' => 'use_flat_dropdowntree', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'view_ID', 'to' => 'is_ids_visible', 'default' => NULL, 'maybenull' => true, 'noindex' => true)));
    foreach ($boolfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $NULL = "NOT NULL";
                if (isset($update['maybenull']) && $update['maybenull']) {
                    $NULL = "NULL";
                    // Manage not zero values
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = 1\n                         WHERE `{$oldname}` <> 0\n                               AND `{$oldname}` IS NOT NULL";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                } else {
                    // Manage NULL fields
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = 0\n                         WHERE `{$oldname}` IS NULL";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                    // Manage not zero values
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = 1\n                         WHERE `{$oldname}` <> 0";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                }
                $default = "DEFAULT NULL";
                if (isset($update['default']) && !is_null($update['default'])) {
                    $default = "DEFAULT " . $update['default'];
                }
                $changes[$table][] = "CHANGE `{$oldname}` `{$newname}` TINYINT( 1 ) {$NULL} {$default}";
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($newname != $oldname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: update text fields'));
    $textfields = array('comments' => array('to' => 'comment', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_autoupdatesystems', 'glpi_budgets', 'glpi_cartridgeitemtypes', 'glpi_devicecasetypes', 'glpi_consumableitemtypes', 'glpi_contacttypes', 'glpi_contracttypes', 'glpi_domains', 'glpi_suppliertypes', 'glpi_filesystems', 'glpi_networkequipmentfirmwares', 'glpi_networkinterfaces', 'glpi_interfacetypes', 'glpi_knowbaseitemcategories', 'glpi_softwarelicensetypes', 'glpi_locations', 'glpi_manufacturers', 'glpi_computermodels', 'glpi_monitormodels', 'glpi_networkequipmentmodels', 'glpi_peripheralmodels', 'glpi_phonemodels', 'glpi_printermodels', 'glpi_netpoints', 'glpi_networks', 'glpi_operatingsystems', 'glpi_operatingsystemservicepacks', 'glpi_operatingsystemversions', 'glpi_phonepowersupplies', 'glpi_devicememorytypes', 'glpi_documentcategories', 'glpi_softwarecategories', 'glpi_states', 'glpi_ticketcategories', 'glpi_usertitles', 'glpi_usercategories', 'glpi_vlans', 'glpi_suppliers', 'glpi_entities', 'glpi_groups', 'glpi_infocoms', 'glpi_monitors', 'glpi_phones', 'glpi_printers', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_reservationitems', 'glpi_rules', 'glpi_softwares', 'glpi_softwarelicenses', 'glpi_softwareversions', 'glpi_computertypes', 'glpi_monitortypes', 'glpi_networkequipmenttypes', 'glpi_peripheraltypes', 'glpi_phonetypes', 'glpi_printertypes', 'glpi_users')), 'notes' => array('to' => 'notepad', 'long' => true, 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_suppliers', 'glpi_entitydatas', 'glpi_printers', 'glpi_monitors', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_softwares')), 'ldap_condition' => array('to' => 'condition', 'tables' => array('glpi_authldaps')), 'import_printers' => array('to' => 'import_printer', 'long' => true, 'tables' => array('glpi_ocslinks')), 'contents' => array('to' => 'content', 'long' => true, 'tables' => array('glpi_tickets', 'glpi_ticketfollowups')));
    foreach ($textfields as $oldname => $tab) {
        $newname = $tab['to'];
        $type = "TEXT";
        if (isset($tab['long']) && $tab['long']) {
            $type = "LONGTEXT";
        }
        foreach ($tab['tables'] as $table) {
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$oldname}` `{$newname}` {$type} NULL DEFAULT NULL ";
                $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}");
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
        }
    }
    $varcharfields = array('glpi_authldaps' => array(array('from' => 'ldap_host', 'to' => 'host', 'noindex' => true), array('from' => 'ldap_basedn', 'to' => 'basedn', 'noindex' => true), array('from' => 'ldap_rootdn', 'to' => 'rootdn', 'noindex' => true), array('from' => 'ldap_pass', 'to' => 'rootdn_password', 'noindex' => true), array('from' => 'ldap_login', 'to' => 'login_field', 'default' => 'uid', 'noindex' => true), array('from' => 'ldap_field_group', 'to' => 'group_field', 'noindex' => true), array('from' => 'ldap_group_condition', 'to' => 'group_condition', 'noindex' => true), array('from' => 'ldap_field_group_member', 'to' => 'group_member_field', 'noindex' => true), array('from' => 'ldap_field_email', 'to' => 'email_field', 'noindex' => true), array('from' => 'ldap_field_realname', 'to' => 'realname_field', 'noindex' => true), array('from' => 'ldap_field_firstname', 'to' => 'firstname_field', 'noindex' => true), array('from' => 'ldap_field_phone', 'to' => 'phone_field', 'noindex' => true), array('from' => 'ldap_field_phone2', 'to' => 'phone2_field', 'noindex' => true), array('from' => 'ldap_field_mobile', 'to' => 'mobile_field', 'noindex' => true), array('from' => 'ldap_field_comments', 'to' => 'comment_field', 'noindex' => true), array('from' => 'ldap_field_title', 'to' => 'title_field', 'noindex' => true), array('from' => 'ldap_field_type', 'to' => 'category_field', 'noindex' => true), array('from' => 'ldap_field_language', 'to' => 'language_field', 'noindex' => true)), 'glpi_authldapreplicates' => array(array('from' => 'ldap_host', 'to' => 'host', 'noindex' => true)), 'glpi_authmails' => array(array('from' => 'imap_auth_server', 'to' => 'connect_string', 'noindex' => true), array('from' => 'imap_host', 'to' => 'host', 'noindex' => true)), 'glpi_computers' => array(array('from' => 'os_license_id', 'to' => 'os_licenseid', 'noindex' => true), array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_configs' => array(array('from' => 'helpdeskhelp_url', 'to' => 'helpdesk_doc_url', 'noindex' => true), array('from' => 'centralhelp_url', 'to' => 'central_doc_url', 'noindex' => true)), 'glpi_contracts' => array(array('from' => 'compta_num', 'to' => 'accounting_number', 'noindex' => true)), 'glpi_events' => array(array('from' => 'itemtype', 'to' => 'type', 'noindex' => true)), 'glpi_infocoms' => array(array('from' => 'num_commande', 'to' => 'order_number', 'noindex' => true), array('from' => 'bon_livraison', 'to' => 'delivery_number', 'noindex' => true), array('from' => 'num_immo', 'to' => 'immo_number', 'noindex' => true), array('from' => 'facture', 'to' => 'bill', 'noindex' => true)), 'glpi_monitors' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_networkequipments' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true), array('from' => 'ifmac', 'to' => 'mac', 'noindex' => true), array('from' => 'ifaddr', 'to' => 'ip', 'noindex' => true)), 'glpi_networkports' => array(array('from' => 'ifmac', 'to' => 'mac', 'noindex' => true), array('from' => 'ifaddr', 'to' => 'ip', 'noindex' => true)), 'glpi_peripherals' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_phones' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_printers' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true), array('from' => 'ramSize', 'to' => 'memory_size', 'noindex' => true)), 'glpi_registrykeys' => array(array('from' => 'registry_hive', 'to' => 'hive', 'noindex' => true), array('from' => 'registry_path', 'to' => 'path', 'noindex' => true), array('from' => 'registry_value', 'to' => 'value', 'noindex' => true), array('from' => 'registry_ocs_name', 'to' => 'ocs_name', 'noindex' => true)), 'glpi_softwares' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_tickets' => array(array('from' => 'uemail', 'to' => 'user_email', 'noindex' => true)));
    foreach ($varcharfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            $default = "DEFAULT NULL";
            if (isset($update['default']) && !is_null($update['default'])) {
                $default = "DEFAULT '" . $update['default'] . "'";
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$oldname}` `{$newname}` VARCHAR( 255 ) NULL {$default} ";
                $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}");
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.");
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($newname != $oldname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $charfields = array('glpi_profiles' => array(array('from' => 'user_auth_method', 'to' => 'user_authtype', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_tracking', 'to' => 'rule_ticket', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_softwarecategories', 'to' => 'rule_softwarecategories', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_dictionnary_software', 'to' => 'rule_dictionnary_software', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_dictionnary_dropdown', 'to' => 'rule_dictionnary_dropdown', 'length' => 1, 'default' => NULL, 'noindex' => true)), 'glpi_configs' => array(array('from' => 'version', 'to' => 'version', 'length' => 10, 'default' => NULL, 'noindex' => true), array('from' => 'version', 'to' => 'version', 'length' => 10, 'default' => NULL, 'noindex' => true), array('from' => 'language', 'to' => 'language', 'length' => 10, 'default' => 'en_GB', 'noindex' => true, 'comments' => 'see define.php CFG_GLPI[language] array'), array('from' => 'priority_1', 'to' => 'priority_1', 'length' => 20, 'default' => '#fff2f2', 'noindex' => true), array('from' => 'priority_2', 'to' => 'priority_2', 'length' => 20, 'default' => '#ffe0e0', 'noindex' => true), array('from' => 'priority_3', 'to' => 'priority_3', 'length' => 20, 'default' => '#ffcece', 'noindex' => true), array('from' => 'priority_4', 'to' => 'priority_4', 'length' => 20, 'default' => '#ffbfbf', 'noindex' => true), array('from' => 'priority_5', 'to' => 'priority_5', 'length' => 20, 'default' => '#ffadad', 'noindex' => true), array('from' => 'founded_new_version', 'to' => 'founded_new_version', 'length' => 10, 'default' => NULL, 'noindex' => true)), 'glpi_rules' => array(array('from' => 'match', 'to' => 'match', 'length' => 10, 'default' => NULL, 'noindex' => true, 'comments' => 'see define.php *_MATCHING constant')), 'glpi_users' => array(array('from' => 'language', 'to' => 'language', 'length' => 10, 'default' => NULL, 'noindex' => true, 'comments' => 'see define.php CFG_GLPI[language] array'), array('from' => 'priority_1', 'to' => 'priority_1', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_2', 'to' => 'priority_2', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_3', 'to' => 'priority_3', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_4', 'to' => 'priority_4', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_5', 'to' => 'priority_5', 'length' => 20, 'default' => NULL, 'noindex' => true)));
    foreach ($charfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $length = $update['length'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            $default = "DEFAULT NULL";
            if (isset($update['default']) && !is_null($update['default'])) {
                $default = "DEFAULT '" . $update['default'] . "'";
            }
            $addcomment = "";
            if (isset($update['comments'])) {
                $addcomment = "COMMENT '" . $update['comments'] . "'";
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$oldname}` `{$newname}` CHAR( {$length} ) NULL {$default} {$addcomment} ";
                $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}");
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($oldname != $newname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $intfields = array('glpi_authldaps' => array(array('from' => 'ldap_port', 'to' => 'port', 'default' => 389, 'noindex' => true, 'checkdatas' => true), array('from' => 'ldap_search_for_groups', 'to' => 'group_search_type', 'default' => 0, 'noindex' => true), array('from' => 'ldap_opt_deref', 'to' => 'deref_option', 'default' => 0, 'noindex' => true), array('from' => 'timezone', 'to' => 'time_offset', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds')), 'glpi_authldapreplicates' => array(array('from' => 'ldap_port', 'to' => 'port', 'default' => 389, 'noindex' => true, 'checkdatas' => true)), 'glpi_bookmarks' => array(array('from' => 'type', 'to' => 'type', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php BOOKMARK_* constant')), 'glpi_cartridgeitems' => array(array('from' => 'alarm', 'to' => 'alarm_threshold', 'default' => 10)), 'glpi_configs' => array(array('from' => 'glpi_timezone', 'to' => 'time_offset', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'cartridges_alarm', 'to' => 'default_alarm_threshold', 'default' => 10, 'noindex' => true), array('from' => 'event_loglevel', 'to' => 'event_loglevel', 'default' => 5, 'noindex' => true), array('from' => 'cas_port', 'to' => 'cas_port', 'default' => 443, 'noindex' => true, 'checkdatas' => true), array('from' => 'auto_update_check', 'to' => 'auto_update_check', 'default' => 0, 'noindex' => true), array('from' => 'dateformat', 'to' => 'date_format', 'default' => 0, 'noindex' => true), array('from' => 'numberformat', 'to' => 'number_format', 'default' => 0, 'noindex' => true), array('from' => 'proxy_port', 'to' => 'proxy_port', 'default' => 8080, 'noindex' => true, 'checkdatas' => true), array('from' => 'contract_alerts', 'to' => 'default_contract_alert', 'default' => 0, 'noindex' => true), array('from' => 'infocom_alerts', 'to' => 'default_infocom_alert', 'default' => 0, 'noindex' => true), array('from' => 'cartridges_alert', 'to' => 'cartridges_alert_repeat', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'consumables_alert', 'to' => 'consumables_alert_repeat', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'monitors_management_restrict', 'to' => 'monitors_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'phones_management_restrict', 'to' => 'phones_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'peripherals_management_restrict', 'to' => 'peripherals_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'printers_management_restrict', 'to' => 'printers_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'autoupdate_link_state', 'to' => 'state_autoupdate_mode', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_state', 'to' => 'state_autoclean_mode', 'default' => 0, 'noindex' => true), array('from' => 'name_display_order', 'to' => 'names_format', 'default' => 0, 'noindex' => true, 'comments' => 'see *NAME_BEFORE constant in define.php'), array('from' => 'dropdown_limit', 'to' => 'dropdown_chars_limit', 'default' => 50, 'noindex' => true), array('from' => 'smtp_mode', 'to' => 'smtp_mode', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php MAIL_* constant'), array('from' => 'mailgate_filesize_max', 'to' => 'default_mailcollector_filesize_max', 'default' => 2097152, 'noindex' => true)), 'glpi_consumableitems' => array(array('from' => 'alarm', 'to' => 'alarm_threshold', 'default' => 10)), 'glpi_contracts' => array(array('from' => 'duration', 'to' => 'duration', 'default' => 0, 'noindex' => true), array('from' => 'notice', 'to' => 'notice', 'default' => 0, 'noindex' => true), array('from' => 'periodicity', 'to' => 'periodicity', 'default' => 0, 'noindex' => true), array('from' => 'facturation', 'to' => 'billing', 'default' => 0, 'noindex' => true), array('from' => 'device_countmax', 'to' => 'max_links_allowed', 'default' => 0, 'noindex' => true), array('from' => 'alert', 'to' => 'alert', 'default' => 0), array('from' => 'renewal', 'to' => 'renewal', 'default' => 0, 'noindex' => true)), 'glpi_displaypreferences' => array(array('from' => 'num', 'to' => 'num', 'default' => 0), array('from' => 'rank', 'to' => 'rank', 'default' => 0)), 'glpi_events' => array(array('from' => 'level', 'to' => 'level', 'default' => 0)), 'glpi_infocoms' => array(array('from' => 'warranty_duration', 'to' => 'warranty_duration', 'default' => 0, 'noindex' => true), array('from' => 'amort_time', 'to' => 'sink_time', 'default' => 0, 'noindex' => true), array('from' => 'amort_type', 'to' => 'sink_type', 'default' => 0, 'noindex' => true), array('from' => 'alert', 'to' => 'alert', 'default' => 0)), 'glpi_mailingsettings' => array(array('from' => 'item_type', 'to' => 'mailingtype', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php *_MAILING_TYPE constant')), 'glpi_monitors' => array(array('from' => 'size', 'to' => 'size', 'default' => 0, 'noindex' => true)), 'glpi_printers' => array(array('from' => 'initial_pages', 'to' => 'init_pages_counter', 'default' => 0, 'noindex' => true, 'checkdatas' => true)), 'glpi_profiles' => array(array('from' => 'helpdesk_hardware', 'to' => 'helpdesk_hardware', 'default' => 0, 'noindex' => true)), 'glpi_plugins' => array(array('from' => 'state', 'to' => 'state', 'default' => 0, 'comments' => 'see define.php PLUGIN_* constant')), 'glpi_reminders' => array(array('from' => 'state', 'to' => 'state', 'default' => 0)), 'glpi_ticketplannings' => array(array('from' => 'state', 'to' => 'state', 'default' => 1)), 'glpi_rulecriterias' => array(array('from' => 'condition', 'to' => 'condition', 'default' => 0, 'comments' => 'see define.php PATTERN_* and REGEX_* constant')), 'glpi_rules' => array(array('from' => 'sub_type', 'to' => 'sub_type', 'default' => 0, 'comments' => 'see define.php RULE_* constant')), 'glpi_tickets' => array(array('from' => 'request_type', 'to' => 'request_type', 'default' => 0, 'noindex' => true), array('from' => 'priority', 'to' => 'priority', 'default' => 1, 'noindex' => true)), 'glpi_transfers' => array(array('from' => 'keep_tickets', 'to' => 'keep_ticket', 'default' => 0, 'noindex' => true), array('from' => 'keep_networklinks', 'to' => 'keep_networklink', 'default' => 0, 'noindex' => true), array('from' => 'keep_reservations', 'to' => 'keep_reservation', 'default' => 0, 'noindex' => true), array('from' => 'keep_history', 'to' => 'keep_history', 'default' => 0, 'noindex' => true), array('from' => 'keep_devices', 'to' => 'keep_device', 'default' => 0, 'noindex' => true), array('from' => 'keep_infocoms', 'to' => 'keep_infocom', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_monitor', 'to' => 'keep_dc_monitor', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_monitor', 'to' => 'clean_dc_monitor', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_phone', 'to' => 'keep_dc_phone', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_phone', 'to' => 'clean_dc_phone', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_peripheral', 'to' => 'keep_dc_peripheral', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_peripheral', 'to' => 'clean_dc_peripheral', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_printer', 'to' => 'keep_dc_printer', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_printer', 'to' => 'clean_dc_printer', 'default' => 0, 'noindex' => true), array('from' => 'keep_enterprises', 'to' => 'keep_supplier', 'default' => 0, 'noindex' => true), array('from' => 'clean_enterprises', 'to' => 'clean_supplier', 'default' => 0, 'noindex' => true), array('from' => 'keep_contacts', 'to' => 'keep_contact', 'default' => 0, 'noindex' => true), array('from' => 'clean_contacts', 'to' => 'clean_contact', 'default' => 0, 'noindex' => true), array('from' => 'keep_contracts', 'to' => 'keep_contract', 'default' => 0, 'noindex' => true), array('from' => 'clean_contracts', 'to' => 'clean_contract', 'default' => 0, 'noindex' => true), array('from' => 'keep_softwares', 'to' => 'keep_software', 'default' => 0, 'noindex' => true), array('from' => 'clean_softwares', 'to' => 'clean_software', 'default' => 0, 'noindex' => true), array('from' => 'keep_documents', 'to' => 'keep_document', 'default' => 0, 'noindex' => true), array('from' => 'clean_documents', 'to' => 'clean_document', 'default' => 0, 'noindex' => true), array('from' => 'keep_cartridges_type', 'to' => 'keep_cartridgeitem', 'default' => 0, 'noindex' => true), array('from' => 'clean_cartridges_type', 'to' => 'clean_cartridgeitem', 'default' => 0, 'noindex' => true), array('from' => 'keep_cartridges', 'to' => 'keep_cartridge', 'default' => 0, 'noindex' => true), array('from' => 'keep_consumables', 'to' => 'keep_consumable', 'default' => 0, 'noindex' => true)), 'glpi_users' => array(array('from' => 'dateformat', 'to' => 'date_format', 'default' => NULL, 'noindex' => true, 'maybenull' => true), array('from' => 'numberformat', 'to' => 'number_format', 'default' => NULL, 'noindex' => true, 'maybenull' => true), array('from' => 'use_mode', 'to' => 'use_mode', 'default' => 0, 'noindex' => true), array('from' => 'dropdown_limit', 'to' => 'dropdown_chars_limit', 'default' => NULL, 'maybenull' => true, 'noindex' => true)));
    foreach ($intfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            $default = "DEFAULT NULL";
            if (isset($update['default']) && !is_null($update['default'])) {
                $default = "DEFAULT " . $update['default'] . "";
            }
            $NULL = "NOT NULL";
            if (isset($update['maybenull']) && $update['maybenull']) {
                $NULL = "NULL";
            }
            $check_datas = false;
            if (isset($update['checkdatas'])) {
                $check_datas = $update['checkdatas'];
            }
            $addcomment = "";
            if (isset($update['comments'])) {
                $addcomment = "COMMENT '" . $update['comments'] . "'";
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                if ($check_datas) {
                    $query = "SELECT `id`, `{$oldname}`\n                         FROM `{$table}`";
                    if ($result = $DB->query($query)) {
                        if ($DB->numrows($result) > 0) {
                            while ($data = $DB->fetch_assoc($result)) {
                                if (empty($data[$oldname]) && isset($update['default'])) {
                                    $data[$oldname] = $update['default'];
                                }
                                $query = "UPDATE `{$table}`\n                                  SET `{$oldname}` = '" . intval($data[$oldname]) . "'\n                                  WHERE `id` = " . $data['id'] . "";
                                $DB->query($query);
                            }
                        }
                    }
                }
                $changes[$table][] = "CHANGE `{$oldname}` `{$newname}` INT( 11 ) {$NULL} {$default} {$addcomment}";
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($newname != $oldname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: others field changes'));
    if (FieldExists('glpi_alerts', 'date', false)) {
        $changes['glpi_alerts'][] = "CHANGE `date` `date` DATETIME NOT NULL";
    }
    if (FieldExists('glpi_configs', 'date_fiscale', false)) {
        $changes['glpi_configs'][] = "CHANGE `date_fiscale` `date_tax` DATE NOT NULL\n                                                                     DEFAULT '2005-12-31'";
    }
    if (FieldExists('glpi_configs', 'sendexpire', false)) {
        $changes['glpi_configs'][] = "DROP `sendexpire`";
    }
    if (FieldExists('glpi_configs', 'show_admin_doc', false)) {
        $changes['glpi_configs'][] = "DROP `show_admin_doc`";
    }
    if (FieldExists('glpi_configs', 'licenses_management_restrict', false)) {
        $changes['glpi_configs'][] = "DROP `licenses_management_restrict`";
    }
    if (FieldExists('glpi_configs', 'nextprev_item', false)) {
        $changes['glpi_configs'][] = "DROP `nextprev_item`";
    }
    if (FieldExists('glpi_configs', 'logotxt', false)) {
        $changes['glpi_configs'][] = "DROP `logotxt`";
    }
    if (FieldExists('glpi_configs', 'num_of_events', false)) {
        $changes['glpi_configs'][] = "DROP `num_of_events`";
    }
    if (FieldExists('glpi_configs', 'tracking_order', false)) {
        $changes['glpi_configs'][] = "DROP `tracking_order`";
    }
    if (FieldExists('glpi_contracts', 'bill_type', false)) {
        $changes['glpi_contracts'][] = "DROP `bill_type`";
    }
    if (FieldExists('glpi_infocoms', 'amort_coeff', false)) {
        $changes['glpi_infocoms'][] = "CHANGE `amort_coeff` `sink_coeff` FLOAT NOT NULL DEFAULT '0'";
    }
    if (FieldExists('glpi_ocsservers', 'import_software_comments', false)) {
        $changes['glpi_ocsservers'][] = "DROP `import_software_comments`";
    }
    if (FieldExists('glpi_users', 'nextprev_item', false)) {
        $changes['glpi_users'][] = "DROP `nextprev_item`";
    }
    if (FieldExists('glpi_users', 'num_of_events', false)) {
        $changes['glpi_users'][] = "DROP `num_of_events`";
    }
    if (FieldExists('glpi_users', 'tracking_order', false)) {
        $changes['glpi_users'][] = "DROP `tracking_order`";
    }
    if (FieldExists('glpi_rulerightparameters', 'sub_type', false)) {
        $changes['glpi_rulerightparameters'][] = "DROP `sub_type`";
    }
    if (FieldExists('glpi_softwares', 'oldstate', false)) {
        $changes['glpi_softwares'][] = "DROP `oldstate`";
    }
    if (FieldExists('glpi_users', 'password', false)) {
        $changes['glpi_users'][] = "DROP `password`";
    }
    if (FieldExists('glpi_users', 'password_md5', false)) {
        $changes['glpi_users'][] = "CHANGE `password_md5` `password` CHAR( 40 )  NULL DEFAULT NULL";
    }
    if (!FieldExists('glpi_mailcollectors', 'filesize_max', false)) {
        $changes['glpi_mailcollectors'][] = "ADD `filesize_max` INT(11) NOT NULL DEFAULT 2097152";
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: index management'));
    if (!isIndex('glpi_alerts', 'unicity')) {
        $changes['glpi_alerts'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`, `type`)";
    }
    if (!isIndex('glpi_cartridges_printermodels', 'unicity')) {
        $changes['glpi_cartridges_printermodels'][] = "ADD UNIQUE `unicity` (`printermodels_id`,\n                                                                           `cartridgeitems_id`)";
    }
    if (!isIndex('glpi_computers_items', 'unicity')) {
        $changes['glpi_computers_items'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`,\n                                                                  `computers_id`)";
    }
    if (!isIndex('glpi_contacts_suppliers', 'unicity')) {
        $changes['glpi_contacts_suppliers'][] = "ADD UNIQUE `unicity` (`suppliers_id`, `contacts_id`)";
    }
    if (!isIndex('glpi_contracts_items', 'unicity')) {
        $changes['glpi_contracts_items'][] = "ADD UNIQUE `unicity` (`contracts_id`, `itemtype`,\n                                                                  `items_id`)";
    }
    if (!isIndex('glpi_contracts_items', 'item')) {
        $changes['glpi_contracts_items'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_contracts_suppliers', 'unicity')) {
        $changes['glpi_contracts_suppliers'][] = "ADD UNIQUE `unicity` (`suppliers_id`, `contracts_id`)";
    }
    if (!isIndex('glpi_displaypreferences', 'unicity')) {
        $changes['glpi_displaypreferences'][] = "ADD UNIQUE `unicity` (`users_id`, `itemtype`, `num`)";
    }
    if (!isIndex('glpi_bookmarks_users', 'unicity')) {
        $changes['glpi_bookmarks_users'][] = "ADD UNIQUE `unicity` (`users_id`, `itemtype`)";
    }
    if (!isIndex('glpi_documents_items', 'unicity')) {
        $changes['glpi_documents_items'][] = "ADD UNIQUE `unicity` (`documents_id`, `itemtype`,\n                                                                  `items_id`)";
    }
    if (!isIndex('glpi_documents_items', 'item')) {
        $changes['glpi_documents_items'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_knowbaseitemcategories', 'unicity')) {
        $changes['glpi_knowbaseitemcategories'][] = "ADD UNIQUE `unicity` (`knowbaseitemcategories_id`,\n                                                                         `name`)";
    }
    if (!isIndex('glpi_locations', 'unicity')) {
        $changes['glpi_locations'][] = "ADD UNIQUE `unicity` (`entities_id`, `locations_id`, `name`)";
    }
    if (isIndex('glpi_locations', 'name')) {
        $changes['glpi_locations'][] = "DROP INDEX `name` ";
    }
    if (!isIndex('glpi_netpoints', 'complete')) {
        $changes['glpi_netpoints'][] = "ADD INDEX `complete` (`entities_id`, `locations_id`, `name`)";
    }
    if (!isIndex('glpi_netpoints', 'location_name')) {
        $changes['glpi_netpoints'][] = "ADD INDEX `location_name` (`locations_id`, `name`)";
    }
    if (!isIndex('glpi_entities', 'unicity')) {
        $changes['glpi_entities'][] = "ADD UNIQUE `unicity` (`entities_id`, `name`)";
    }
    if (!isIndex('glpi_entitydatas', 'unicity')) {
        $changes['glpi_entitydatas'][] = "ADD UNIQUE `unicity` (`entities_id`)";
    }
    if (!isIndex('glpi_events', 'item')) {
        $changes['glpi_events'][] = "ADD INDEX `item` (`type`, `items_id`)";
    }
    if (!isIndex('glpi_infocoms', 'unicity')) {
        $changes['glpi_infocoms'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_knowbaseitems', 'date_mod')) {
        $changes['glpi_knowbaseitems'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_networkequipments', 'date_mod')) {
        $changes['glpi_networkequipments'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_links_itemtypes', 'unicity')) {
        $changes['glpi_links_itemtypes'][] = "ADD UNIQUE `unicity` (`itemtype`, `links_id`)";
    }
    if (!isIndex('glpi_mailingsettings', 'unicity')) {
        $changes['glpi_mailingsettings'][] = "ADD UNIQUE `unicity` (`type`, `items_id`, `mailingtype`)";
    }
    if (!isIndex('glpi_networkports', 'item')) {
        $changes['glpi_networkports'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_networkports_vlans', 'unicity')) {
        $changes['glpi_networkports_vlans'][] = "ADD UNIQUE `unicity` (`networkports_id`, `vlans_id`)";
    }
    if (!isIndex('glpi_networkports_networkports', 'unicity')) {
        $changes['glpi_networkports_networkports'][] = "ADD UNIQUE `unicity` (`networkports_id_1`,\n                                                                            `networkports_id_2`)";
    }
    if (!isIndex('glpi_ocslinks', 'unicity')) {
        $changes['glpi_ocslinks'][] = "ADD UNIQUE `unicity` (`ocsservers_id`, `ocsid`)";
    }
    if (!isIndex('glpi_peripherals', 'date_mod')) {
        $changes['glpi_peripherals'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_phones', 'date_mod')) {
        $changes['glpi_phones'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_plugins', 'unicity')) {
        $changes['glpi_plugins'][] = "ADD UNIQUE `unicity` (`directory`)";
    }
    if (!isIndex('glpi_printers', 'date_mod')) {
        $changes['glpi_printers'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_reminders', 'date_mod')) {
        $changes['glpi_reminders'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_reservationitems', 'item')) {
        $changes['glpi_reservationitems'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_tickets', 'item')) {
        $changes['glpi_tickets'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_documenttypes', 'date_mod')) {
        $changes['glpi_documenttypes'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_documenttypes', 'unicity')) {
        $changes['glpi_documenttypes'][] = "ADD UNIQUE `unicity` (`ext`)";
    }
    if (!isIndex('glpi_users', 'unicity')) {
        $changes['glpi_users'][] = "ADD UNIQUE `unicity` (`name`)";
    }
    if (!isIndex('glpi_users', 'date_mod')) {
        $changes['glpi_users'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_users', 'authitem')) {
        $changes['glpi_users'][] = "ADD INDEX `authitem` (`authtype`, `auths_id`)";
    }
    if (!isIndex('glpi_groups_users', 'unicity')) {
        $changes['glpi_groups_users'][] = "ADD UNIQUE `unicity` (`users_id`, `groups_id`)";
    }
    $indextodrop = array('glpi_alerts' => array('alert', 'FK_device'), 'glpi_cartridges_printermodels' => array('FK_glpi_type_printer'), 'glpi_computers_items' => array('connect', 'type', 'end1', 'end1_2'), 'glpi_consumables' => array('FK_glpi_cartridges_type'), 'glpi_contacts_suppliers' => array('FK_enterprise'), 'glpi_contracts_items' => array('FK_contract_device', 'device_type'), 'glpi_contracts_suppliers' => array('FK_enterprise'), 'glpi_displaypreferences' => array('display', 'FK_users'), 'glpi_bookmarks_users' => array('FK_users'), 'glpi_documents_items' => array('FK_doc_device', 'device_type', 'FK_device'), 'glpi_knowbaseitemcategories' => array('parentID_2', 'parentID'), 'glpi_locations' => array('FK_entities'), 'glpi_netpoints' => array('FK_entities', 'location'), 'glpi_entities' => array('name'), 'glpi_entitydatas' => array('FK_entities'), 'glpi_events' => array('comp', 'itemtype'), 'glpi_infocoms' => array('FK_device'), 'glpi_computers_softwareversions' => array('sID'), 'glpi_links_itemtypes' => array('link'), 'glpi_mailingsettings' => array('mailings', 'FK_item'), 'glpi_networkports' => array('device_type'), 'glpi_networkports_vlans' => array('portvlan'), 'glpi_networkports_networkports' => array('netwire', 'end1', 'end1_2'), 'glpi_ocslinks' => array('ocs_server_id'), 'glpi_plugins' => array('name'), 'glpi_reservationitems' => array('reservationitem'), 'glpi_tickets' => array('computer', 'device_type'), 'glpi_documenttypes' => array('extension'), 'glpi_users' => array('name'), 'glpi_groups_users' => array('usergroup'));
    foreach ($indextodrop as $table => $tab) {
        foreach ($tab as $indexname) {
            if (isIndex($table, $indexname)) {
                $changes[$table][] = "DROP INDEX `{$indexname}`";
            }
        }
    }
    foreach ($changes as $table => $tab) {
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $table));
        $query = "ALTER TABLE `{$table}`\n                " . implode($tab, " ,\n") . ";";
        $DB->queryOrDie($query, "0.78 multiple alter in {$table}");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Update itemtype fields'));
    // Convert itemtype to Class names
    $typetoname = array(GENERAL_TYPE => "", COMPUTER_TYPE => "Computer", NETWORKING_TYPE => "NetworkEquipment", PRINTER_TYPE => "Printer", MONITOR_TYPE => "Monitor", PERIPHERAL_TYPE => "Peripheral", SOFTWARE_TYPE => "Software", CONTACT_TYPE => "Contact", ENTERPRISE_TYPE => "Supplier", INFOCOM_TYPE => "Infocom", CONTRACT_TYPE => "Contract", CARTRIDGEITEM_TYPE => "CartridgeItem", TYPEDOC_TYPE => "DocumentType", DOCUMENT_TYPE => "Document", KNOWBASE_TYPE => "KnowbaseItem", USER_TYPE => "User", TRACKING_TYPE => "Ticket", CONSUMABLEITEM_TYPE => "ConsumableItem", CONSUMABLE_TYPE => "Consumable", CARTRIDGE_TYPE => "Cartridge", SOFTWARELICENSE_TYPE => "SoftwareLicense", LINK_TYPE => "Link", STATE_TYPE => "States", PHONE_TYPE => "Phone", DEVICE_TYPE => "Device", REMINDER_TYPE => "Reminder", STAT_TYPE => "Stat", GROUP_TYPE => "Group", ENTITY_TYPE => "Entity", RESERVATION_TYPE => "ReservationItem", AUTHMAIL_TYPE => "AuthMail", AUTHLDAP_TYPE => "AuthLDAP", OCSNG_TYPE => "OcsServer", REGISTRY_TYPE => "RegistryKey", PROFILE_TYPE => "Profile", MAILGATE_TYPE => "MailCollector", RULE_TYPE => "Rule", TRANSFER_TYPE => "Transfer", BOOKMARK_TYPE => "Bookmark", SOFTWAREVERSION_TYPE => "SoftwareVersion", PLUGIN_TYPE => "Plugin", COMPUTERDISK_TYPE => "ComputerDisk", NETWORKING_PORT_TYPE => "NetworkPort", FOLLOWUP_TYPE => "TicketFollowup", BUDGET_TYPE => "Budget");
    // End is not used in 0.72.x
    $devtypetoname = array(MOBOARD_DEVICE => 'DeviceMotherboard', PROCESSOR_DEVICE => 'DeviceProcessor', RAM_DEVICE => 'DeviceMemory', HDD_DEVICE => 'DeviceHardDrive', NETWORK_DEVICE => 'DeviceNetworkCard', DRIVE_DEVICE => 'DeviceDrive', CONTROL_DEVICE => 'DeviceControl', GFX_DEVICE => 'DeviceGraphicCard', SND_DEVICE => 'DeviceSoundCard', PCI_DEVICE => 'DevicePci', CASE_DEVICE => 'DeviceCase', POWER_DEVICE => 'DevicePowerSupply');
    $itemtype_tables = array("glpi_alerts", "glpi_bookmarks", "glpi_bookmarks_users", "glpi_computers_items", "glpi_contracts_items", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_links_itemtypes", "glpi_networkports", "glpi_reservationitems", "glpi_tickets");
    foreach ($itemtype_tables as $table) {
        $migration->displayMessage(sprintf(__('Data migration - %s'), "{$table}"));
        // Updating data
        // Alter itemtype field
        $query = "ALTER TABLE `{$table}`\n                CHANGE `itemtype` `itemtype` VARCHAR( 100 ) NOT NULL";
        $DB->queryOrDie($query, "0.78 alter itemtype of table {$table}");
        // Update values
        foreach ($typetoname as $key => $val) {
            $query = "UPDATE `{$table}`\n                   SET `itemtype` = '{$val}'\n                   WHERE `itemtype` = '{$key}'";
            $DB->queryOrDie($query, "0.78 update itemtype of table {$table} for {$val}");
        }
    }
    if (FieldExists('glpi_logs', 'device_type', false)) {
        // History migration, handled separatly for optimization
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_logs - 1'));
        $query = "ALTER TABLE `glpi_logs`\n                CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT,\n                ADD `itemtype` VARCHAR(100) NOT NULL DEFAULT ''  AFTER `device_type`,\n                ADD `items_id` INT( 11 ) NOT NULL DEFAULT '0' AFTER `itemtype`,\n                ADD `itemtype_link` VARCHAR(100) NOT NULL DEFAULT '' AFTER `device_internal_type`,\n                CHANGE `linked_action` `linked_action` INT( 11 ) NOT NULL DEFAULT '0'\n                                                       COMMENT 'see define.php HISTORY_* constant'";
        $DB->queryOrDie($query, "0.78 add item* fields to table glpi_logs");
        // Update values
        $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_logs'));
        // Copy data
        $query = "UPDATE `glpi_logs`\n                SET `itemtype` = `device_type`,\n                    `items_id` = `FK_glpi_device`,\n                    `itemtype_link` = `device_internal_type`";
        $DB->queryOrDie($query, "0.78 update glpi_logs default values");
        foreach ($typetoname as $key => $val) {
            $query = "UPDATE `glpi_logs`\n                   SET `itemtype` = '{$val}'\n                   WHERE `device_type` = '{$key}'";
            $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}");
            $query = "UPDATE `glpi_logs`\n                   SET `itemtype_link` = '{$val}'\n                   WHERE `device_internal_type` = '{$key}'\n                        AND `linked_action` IN (" . Log::HISTORY_ADD_RELATION . ",\n                                                " . Log::HISTORY_DEL_RELATION . ",\n                                                " . Log::HISTORY_DISCONNECT_DEVICE . ",\n                                                " . Log::HISTORY_CONNECT_DEVICE . ")";
            $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}");
        }
        foreach ($devtypetoname as $key => $val) {
            $query = "UPDATE `glpi_logs`\n                   SET `itemtype_link` = '{$val}'\n                   WHERE `device_internal_type` = '{$key}'\n                         AND `linked_action` IN (" . Log::HISTORY_ADD_DEVICE . ",\n                                                 " . Log::HISTORY_UPDATE_DEVICE . ",\n                                                 " . Log::HISTORY_DELETE_DEVICE . ")";
            $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}");
        }
        // Clean link
        $query = "UPDATE `glpi_logs`\n                SET `itemtype_link` = ''\n                WHERE `itemtype_link` = '0'";
        $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs");
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_logs - 2'));
        $query = "ALTER TABLE `glpi_logs`\n                DROP `device_type`,\n                DROP `FK_glpi_device`,\n                DROP `device_internal_type`,\n                ADD INDEX `itemtype_link` (`itemtype_link`),\n                ADD INDEX `item` (`itemtype`,`items_id`)";
        $DB->queryOrDie($query, "0.78 drop device* fields to table glpi_logs");
    }
    // Update glpi_profiles item_type
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: post actions after renaming'));
    if (!isIndex('glpi_locations', 'name')) {
        $query = " ALTER TABLE `glpi_locations`\n                 ADD INDEX `name` (`name`)";
        $DB->queryOrDie($query, "0.78 add name index in glpi_locations");
    }
    // Update values of mailcollectors
    $query = "SELECT `default_mailcollector_filesize_max`\n             FROM `glpi_configs`\n             WHERE `id` = 1";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            $query = "UPDATE `glpi_mailcollectors`\n                   SET `filesize_max` = '" . $DB->result($result, 0, 0) . "';";
            $DB->query($query);
        }
    }
    // For compatiblity with updates from past versions
    regenerateTreeCompleteName("glpi_locations");
    regenerateTreeCompleteName("glpi_knowbaseitemcategories");
    regenerateTreeCompleteName("glpi_ticketcategories");
    // Update timezone values
    if (FieldExists('glpi_configs', 'time_offset', false)) {
        $query = "UPDATE `glpi_configs`\n                SET `time_offset` = `time_offset`*3600";
        $DB->queryOrDie($query, "0.78 update time_offset value in glpi_configs");
    }
    if (FieldExists('glpi_authldaps', 'time_offset', false)) {
        $query = "UPDATE `glpi_authldaps`\n                SET `time_offset` = `time_offset`*3600";
        $DB->queryOrDie($query, "0.78 update time_offset value in glpi_authldaps");
    }
    // Change defaults store values :
    if (FieldExists('glpi_softwares', 'sofwtares_id', false)) {
        $query = "UPDATE `glpi_softwares`\n                SET `sofwtares_id` = 0\n                WHERE `sofwtares_id` < 0";
        $DB->queryOrDie($query, "0.78 update default value of sofwtares_id in glpi_softwares");
    }
    if (FieldExists('glpi_users', 'authtype', false)) {
        $query = "UPDATE `glpi_users`\n                SET `authtype` = 0\n                WHERE `authtype` < 0";
        $DB->queryOrDie($query, "0.78 update default value of authtype in glpi_users");
    }
    if (FieldExists('glpi_users', 'auths_id', false)) {
        $query = "UPDATE `glpi_users`\n                SET `auths_id` = 0\n                WHERE `auths_id` < 0";
        $DB->queryOrDie($query, "0.78 update default value of auths_id in glpi_users");
    }
    // Update glpi_ocsadmininfoslinks table for new field name
    if (FieldExists('glpi_ocsadmininfoslinks', 'glpi_column', false)) {
        $query = "UPDATE `glpi_ocsadmininfoslinks`\n                SET `glpi_column` = 'locations_id'\n                WHERE `glpi_column` = 'location'";
        $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks");
        $query = "UPDATE `glpi_ocsadmininfoslinks`\n                SET `glpi_column` = 'networks_id'\n                WHERE `glpi_column` = 'network'";
        $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks");
        $query = "UPDATE `glpi_ocsadmininfoslinks`\n                SET `glpi_column` = 'groups_id'\n                WHERE `glpi_column` = 'FK_groups'";
        $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks");
    }
    // Update bookmarks for new columns fields
    if (FieldExists('glpi_bookmarks', 'is_private', false)) {
        $query = "UPDATE `glpi_bookmarks`\n                SET `entities_id` = -1\n                WHERE `is_private` = 1";
        $DB->queryOrDie($query, "0.78 update value of entities_id in glpi_bookmarks");
    }
    if (FieldExists('glpi_reminders', 'is_private', false)) {
        $query = "UPDATE `glpi_reminders`\n                SET `entities_id` = -1\n                WHERE `is_private` = 1";
        $DB->queryOrDie($query, "0.78 update value of entities_id in glpi_reminders");
    }
    // Update bookmarks for new columns fields
    if (FieldExists('glpi_bookmarks', 'query', false)) {
        // All search
        $olds = array("deleted");
        $news = array("is_deleted");
        foreach ($olds as $key => $val) {
            $olds[$key] = "/&{$val}=/";
        }
        foreach ($news as $key => $val) {
            $news[$key] = "/&{$val}=/";
        }
        // Manage meta search
        foreach ($typetoname as $key => $val) {
            $olds[$key] = "/&type2\\[(\\d+)\\]={$key}/";
            $news[$key] = "&itemtype2[\\1]={$val}";
        }
        $query = "SELECT `id`, `query`\n                FROM `glpi_bookmarks`\n                WHERE `type` = " . Bookmark::SEARCH . " ";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query2 = "UPDATE `glpi_bookmarks`\n                          SET `query` = '" . addslashes(preg_replace($olds, $news, $data['query'])) . "'\n                          WHERE `id` = " . $data['id'] . "";
                    $DB->queryOrDie($query2, "0.78 update all bookmarks");
                }
            }
        }
        // Update bookmarks due to FHS change
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/documenttype.php'\n                 WHERE `path` = 'front/typedoc.php'";
        $DB->queryOrDie($query2, "0.78 update typedoc bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/consumableitem.php'\n                 WHERE `path` = 'front/consumable.php'";
        $DB->queryOrDie($query2, "0.78 update consumable bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/cartridgeitem.php'\n                 WHERE `path` = 'front/cartridge.php'";
        $DB->queryOrDie($query2, "0.78 update cartridge bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/ticket.php'\n                 WHERE `path` = 'front/tracking.php'";
        $DB->queryOrDie($query2, "0.78 update ticket bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/mailcollector.php'\n                 WHERE `path` = 'front/mailgate.php'";
        $DB->queryOrDie($query2, "0.78 update mailcollector bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/ocsserver.php'\n                 WHERE `path` = 'front/setup.ocsng.php'";
        $DB->queryOrDie($query2, "0.78 update ocsserver bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/supplier.php'\n                 WHERE `path` = 'front/enterprise.php'";
        $DB->queryOrDie($query2, "0.78 update supplier bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/networkequipment.php'\n                 WHERE `path` = 'front/networking.php'";
        $DB->queryOrDie($query2, "0.78 update networkequipment bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/states.php'\n                 WHERE `path` = 'front/state.php'";
        $DB->queryOrDie($query2, "0.78 update states bookmarks");
    }
    //// Upgrade rules datas
    $changes = array();
    // For Rule::RULE_AFFECT_RIGHTS
    $changes[1] = array('FK_entities' => 'entities_id', 'FK_profiles' => 'profiles_id', 'recursive' => 'is_recursive', 'active' => 'is_active');
    // For Rule::RULE_DICTIONNARY_SOFTWARE
    $changes[4] = array('helpdesk_visible ' => 'is_helpdesk_visible');
    // For Rule::RULE_OCS_AFFECT_COMPUTER
    $changes[0] = array('FK_entities' => 'entities_id');
    // For Rule::RULE_SOFTWARE_CATEGORY
    $changes[3] = array('category' => 'softwarecategories_id', 'comment' => 'comment');
    // For Rule::RULE_TRACKING_AUTO_ACTION
    $changes[2] = array('category' => 'ticketcategories_id', 'author' => 'users_id', 'author_location' => 'users_locations', 'FK_group' => 'groups_id', 'assign' => 'users_id_assign', 'assign_group' => 'groups_id_assign', 'device_type' => 'itemtype', 'FK_entities' => 'entities_id', 'contents' => 'content', 'request_type' => 'requesttypes_id');
    $DB->query("SET SESSION group_concat_max_len = 9999999;");
    foreach ($changes as $ruletype => $tab) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = " . $ruletype . "\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `field` = '{$new}'\n                         WHERE `field` = '{$old}'\n                               AND `rules_id` IN ({$rules});";
                    $DB->queryOrDie($query, "0.78 update datas for rules actions");
                }
                // Update criterias
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_rulecriterias`\n                         SET `criteria` = '{$new}'\n                         WHERE `criteria` = '{$old}'\n                               AND `rules_id` IN ({$rules});";
                    $DB->queryOrDie($query, "0.78 update datas for rules criterias");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_rulecachesoftwares'));
    $query = "ALTER TABLE `glpi_rules`\n             CHANGE `sub_type` `sub_type` VARCHAR( 255 ) NOT NULL DEFAULT ''";
    $DB->queryOrDie($query, "0.78 change subtype from INT(11) to VARCHAR(255) in glpi_rules");
    $subtypes = array(0 => 'RuleOcs', 1 => 'RuleRight', 2 => 'RuleTicket', 3 => 'RuleSoftwareCategory', 4 => 'RuleDictionnarySoftware', 5 => 'RuleDictionnaryManufacturer', 6 => 'RuleDictionnaryComputerModel', 7 => 'RuleDictionnaryComputerType', 8 => 'RuleDictionnaryMonitorModel', 9 => 'RuleDictionnaryMonitorType', 10 => 'RuleDictionnaryPrinterModel', 11 => 'RuleDictionnaryPrinterType', 12 => 'RuleDictionnaryPhoneModel', 13 => 'RuleDictionnaryPhoneType', 14 => 'RuleDictionnaryPeripheralModel', 15 => 'RuleDictionnaryPeripheralType', 16 => 'RuleDictionnaryNetworkEquipmentModel', 17 => 'RuleDictionnaryNetworkEquipmentType', 18 => 'RuleDictionnaryOperatingSystem', 19 => 'RuleDictionnaryOperatingSystemServicePack', 20 => 'RuleDictionnaryOperatingSystemVersion', 21 => 'RuleMailCollector');
    foreach ($subtypes as $old_subtype => $new_subtype) {
        $query = "UPDATE `glpi_rules`\n                SET `sub_type` = '{$new_subtype}'\n                WHERE `sub_type` = '{$old_subtype}'";
        $DB->queryOrDie($query, "0.78 change sub_type {$old_subtype} in {$new_subtype} in glpi_rules");
    }
    $DB->queryOrDie($query, "0.78 update itemtypes in business rules");
    //Update business rules itemtypes
    foreach ($typetoname as $key => $val) {
        if ($key != GENERAL_TYPE) {
            $query = "UPDATE `glpi_rulecriterias`\n                   SET `pattern` = '{$val}'\n                   WHERE `pattern` = '{$key}'\n                         AND `criteria` = 'itemtype'";
            $DB->queryOrDie($query, "0.78 update itemtype for business rules for {$val}");
        }
    }
    if (FieldExists("glpi_rulecachesoftwares", "ignore_ocs_import", false)) {
        $query = "ALTER TABLE `glpi_rulecachesoftwares`\n                CHANGE `ignore_ocs_import` `ignore_ocs_import` CHAR( 1 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.78 alter table glpi_rulecachesoftwares");
    }
    if (!FieldExists("glpi_rulecachesoftwares", "is_helpdesk_visible", false)) {
        $query = "ALTER TABLE `glpi_rulecachesoftwares`\n                ADD `is_helpdesk_visible` CHAR( 1 ) NULL ";
        $DB->queryOrDie($query, "0.78 add is_helpdesk_visible in glpi_rulecachesoftwares");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_entities'));
    if (!FieldExists("glpi_entities", "sons_cache", false)) {
        $query = "ALTER TABLE `glpi_entities`\n                ADD `sons_cache` LONGTEXT NULL ; ";
        $DB->queryOrDie($query, "0.78 add sons_cache field in glpi_entities");
    }
    if (!FieldExists("glpi_entities", "ancestors_cache", false)) {
        $query = "ALTER TABLE `glpi_entities`\n                ADD `ancestors_cache` LONGTEXT NULL ; ";
        $DB->queryOrDie($query, "0.78 add ancestors_cache field in glpi_entities");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_configs'));
    if (!FieldExists("glpi_configs", "default_graphtype", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `default_graphtype` char( 3 ) NOT NULL DEFAULT 'svg'";
        $DB->queryOrDie($query, "0.78 add default_graphtype in glpi_configs");
    }
    if (FieldExists('glpi_configs', 'license_deglobalisation', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `license_deglobalisation`;";
        $DB->queryOrDie($query, "0.78 alter clean glpi_configs table");
    }
    if (FieldExists("glpi_configs", "use_cache", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `use_cache`;";
        $DB->queryOrDie($query, "0.78 drop use_cache in glpi_configs");
    }
    if (FieldExists("glpi_configs", "cache_max_size", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `cache_max_size`;";
        $DB->queryOrDie($query, "0.78 drop cache_max_size in glpi_configs");
    }
    if (!FieldExists("glpi_configs", "default_request_type", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `default_request_type` INT( 11 ) NOT NULL DEFAULT 1";
        $DB->queryOrDie($query, "0.78 add default_request_type in glpi_configs");
    }
    if (!FieldExists("glpi_users", "default_request_type", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `default_request_type` INT( 11 ) NULL";
        $DB->queryOrDie($query, "0.78 add default_request_type in glpi_users");
    }
    if (!FieldExists("glpi_configs", "use_noright_users_add", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `use_noright_users_add` tinyint( 1 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.78 add use_noright_users_add in glpi_configs");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_budgets'));
    if (!FieldExists("glpi_profiles", "budget", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `budget` CHAR( 1 ) NULL ";
        $DB->queryOrDie($query, "0.78 add budget in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `budget` = `infocom`";
        $DB->queryOrDie($query, "0.78 update default budget rights");
    }
    if (!FieldExists("glpi_budgets", "is_recursive", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `is_recursive` tinyint(1) NOT NULL DEFAULT '0' AFTER `name`,\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add is_recursive field in glpi_budgets");
        // budgets in 0.72 were global
        $query = "UPDATE `glpi_budgets`\n                SET `is_recursive` = '1';";
        $DB->queryOrDie($query, "0.78 set is_recursive to true in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "entities_id", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                   ADD `entities_id` int(11) NOT NULL default '0' AFTER `name`,\n                   ADD INDEX `entities_id` (`entities_id`);";
        $DB->queryOrDie($query, "0.78 add entities_id field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "is_deleted", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                ADD INDEX `is_deleted` (`is_deleted`)";
        $DB->queryOrDie($query, "0.78 add is_deleted field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "begin_date", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `begin_date` DATE NULL,\n                ADD INDEX `begin_date` (`begin_date`)";
        $DB->queryOrDie($query, "0.78 add begin_date field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "end_date", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `end_date` DATE NULL,\n                ADD INDEX `end_date` (`begin_date`)";
        $DB->queryOrDie($query, "0.78 add end_date field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "value", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `value` DECIMAL( 20, 4 )  NOT NULL default '0.0000'";
        $DB->queryOrDie($query, "0.78 add value field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "is_template", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `is_template` tinyint(1) NOT NULL default '0',\n                ADD INDEX `is_template` (`is_template`);";
        $DB->queryOrDie($query, "0.78 add is_template field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "template_name", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `template_name` varchar(255) default NULL";
        $DB->queryOrDie($query, "0.78 add template_name field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `date_mod`  DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "notepad", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `notepad` LONGTEXT NULL collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add notepad field in glpi_budgets");
    }
    // Change budget search pref : date_mod
    $ADDTODISPLAYPREF['Budget'] = array(2, 3, 4, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), __('Automatic action')));
    if (!TableExists('glpi_crontasks')) {
        $query = "CREATE TABLE `glpi_crontasks` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                 `name` varchar(150) COLLATE utf8_unicode_ci NOT NULL COMMENT 'task name',\n                 `frequency` int(11) NOT NULL COMMENT 'second between launch',\n                 `param` int(11) DEFAULT NULL COMMENT 'task specify parameter',\n                 `state` int(11) NOT NULL DEFAULT '1' COMMENT '0:disabled, 1:waiting, 2:running',\n                 `mode` int(11) NOT NULL DEFAULT '1' COMMENT '1:internal, 2:external',\n                 `allowmode` int(11) NOT NULL DEFAULT '3' COMMENT '1:internal, 2:external, 3:both',\n                 `hourmin` int(11) NOT NULL DEFAULT '0',\n                 `hourmax` int(11) NOT NULL DEFAULT '24',\n                 `logs_lifetime` int(11) NOT NULL DEFAULT '30' COMMENT 'number of days',\n                 `lastrun` datetime DEFAULT NULL COMMENT 'last run date',\n                 `lastcode` int(11) DEFAULT NULL COMMENT 'last run return code',\n                 `comment` text COLLATE utf8_unicode_ci,\n                 PRIMARY KEY (`id`),\n                 UNIQUE KEY `unicity` (`itemtype`,`name`),\n                 KEY `mode` (`mode`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\n                 COMMENT='Task run by internal / external cron.';";
        $DB->queryOrDie($query, "0.78 create glpi_crontasks");
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('OcsServer', 'ocsng', 300, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CartridgeItem', 'cartridge', 86400, 10, 0, 1, 3, 0, 24, 30, NULL, NULL,\n                        NULL),\n                       ('ConsumableItem', 'consumable', 86400, 10, 0, 1, 3, 0, 24, 30, NULL, NULL,\n                        NULL),\n                       ('SoftwareLicense', 'software', 86400, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL,\n                        NULL),\n                       ('Contract', 'contract', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('InfoCom', 'infocom', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'logs', 86400, 10, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'optimize', 604800, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('MailCollector', 'mailgate', 600, 10, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('DBconnection', 'checkdbreplicate', 300, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'checkupdate', 604800, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'session', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'graph', 3600, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('ReservationItem', 'reservation', 3600, NULL, 1, 1, 3, 0, 24, 30, NULL,\n                        NULL, NULL),\n                       ('Ticket', 'closeticket', '43200', NULL, '1', '1', '3', '0', '24', '30',\n                        NULL, NULL, NULL),\n                       ('Ticket', 'alertnotclosed', '43200', NULL, '1', '1', '3', '0', '24', '30',\n                        NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.78 populate glpi_crontasks");
    }
    $ADDTODISPLAYPREF['Crontask'] = array(8, 3, 4, 7);
    if (!TableExists('glpi_crontasklogs')) {
        $query = "CREATE TABLE `glpi_crontasklogs` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `crontasks_id` int(11) NOT NULL,\n                 `crontasklogs_id` int(11) NOT NULL COMMENT 'id of ''start'' event',\n                 `date` datetime NOT NULL,\n                 `state` int(11) NOT NULL COMMENT '0:start, 1:run, 2:stop',\n                 `elapsed` float NOT NULL COMMENT 'time elapsed since start',\n                 `volume` int(11) NOT NULL COMMENT 'for statistics',\n                 `content` varchar(255) COLLATE utf8_unicode_ci NULL COMMENT 'message',\n                 PRIMARY KEY (`id`),\n                 KEY `date` (`date`),\n                 KEY `crontasks_id` (`crontasks_id`),\n                 KEY `crontasklogs_id_state` (`crontasklogs_id`,`state`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;";
        $DB->queryOrDie($query, "0.78 create glpi_crontasklogs");
    }
    // Retrieve core task lastrun date
    $tasks = array('ocsng', 'cartridge', 'consumable', 'software', 'contract', 'infocom', 'logs', 'optimize', 'mailgate', 'DBConnection', 'check_update', 'session');
    foreach ($tasks as $task) {
        $lock = GLPI_CRON_DIR . '/' . $task . '.lock';
        if (is_readable($lock) && ($stat = stat($lock))) {
            $DB->query("UPDATE `glpi_crontasks`\n                     SET `lastrun` = '" . date('Y-m-d H:i:s', $stat['mtime']) . "'\n                     WHERE `name` = '{$task}'");
            unlink($lock);
        }
    }
    // Clean plugin lock
    foreach (glob(GLPI_CRON_DIR . '/*.lock') as $lock) {
        unlink($lock);
    }
    // disable ocsng cron if not activate
    if (FieldExists('glpi_configs', 'use_ocs_mode', false)) {
        $query = "SELECT `use_ocs_mode`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                if ($value == 0) {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state`='0'\n                         WHERE `name` = 'ocsng'";
                    $DB->query($query);
                }
            }
        }
    }
    // Move glpi_config.expire_events to glpi_crontasks.param
    if (FieldExists('glpi_configs', 'expire_events', false)) {
        $query = "SELECT `expire_events`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                if ($value > 0) {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '1',\n                             `param` = '{$value}'\n                         WHERE `name` = 'logs'";
                } else {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '0'\n                         WHERE `name` = 'logs'";
                }
                $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_configs`\n                DROP `expire_events`";
        $DB->queryOrDie($query, "0.78 drop expire_events in glpi_configs");
    }
    // Move glpi_config.auto_update_check to glpi_crontasks.state
    if (FieldExists('glpi_configs', 'auto_update_check', false)) {
        $query = "SELECT `auto_update_check`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                if ($value > 0) {
                    $value *= DAY_TIMESTAMP;
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '1',\n                             `frequency` = '{$value}'\n                         WHERE `name` = 'check_update'";
                } else {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '0'\n                         WHERE `name` = 'logs'";
                }
                $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_configs`\n                DROP `auto_update_check`";
        $DB->queryOrDie($query, "0.78 drop auto_update_check in check_update");
    }
    if (FieldExists('glpi_configs', 'dbreplicate_maxdelay', false)) {
        $query = "SELECT `dbreplicate_maxdelay`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                $value = intval($value / 60);
                $query = "UPDATE `glpi_crontasks`\n                      SET `state` = '1',\n                          `frequency` = '{$value}'\n                      WHERE `name` = 'check_dbreplicate'";
                $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_configs`\n                DROP `dbreplicate_maxdelay`";
        $DB->queryOrDie($query, "0.78 drop dbreplicate_maxdelay in check_update");
    }
    if (FieldExists('glpi_configs', 'dbreplicate_notify_desynchronization', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `dbreplicate_notify_desynchronization`";
        $DB->queryOrDie($query, "0.78 drop dbreplicate_notify_desynchronization in check_update");
    }
    if (!FieldExists('glpi_configs', 'cron_limit', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `cron_limit` TINYINT NOT NULL DEFAULT '1'\n                                 COMMENT 'Number of tasks execute by external cron'";
        $DB->queryOrDie($query, "0.78 add cron_limit in glpi_configs");
    }
    if (!FieldExists('glpi_documents', 'sha1sum', false)) {
        $query = "ALTER TABLE `glpi_documents`\n                ADD `sha1sum` CHAR(40) NULL DEFAULT NULL ,\n                ADD INDEX `sha1sum` (`sha1sum`)";
        $DB->queryOrDie($query, "0.78 add sha1sum in glpi_documents");
    }
    if (FieldExists('glpi_documents', 'filename', false)) {
        $query = "ALTER TABLE `glpi_documents`\n                  CHANGE `filename` `filename` VARCHAR( 255 ) NULL DEFAULT NULL\n                  COMMENT 'for display and transfert'";
        $DB->queryOrDie($query, "0.78 alter filename in glpi_documents");
    }
    if (!FieldExists('glpi_documents', 'filepath', false)) {
        $query = "ALTER TABLE `glpi_documents`\n                ADD `filepath` VARCHAR( 255 ) NULL\n                COMMENT 'file storage path' AFTER `filename`";
        $DB->queryOrDie($query, "0.78 add filepath in glpi_documents");
        $query = "UPDATE `glpi_documents`\n                SET `filepath` = `filename`";
        $DB->queryOrDie($query, "0.78 set value of filepath in glpi_documents");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Category of tickets'));
    if (!FieldExists('glpi_tickets', 'solvedate', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `solvedate` datetime default NULL AFTER `closedate`,\n                ADD INDEX `solvedate` (`solvedate`)";
        $DB->queryOrDie($query, "0.78 add solvedate to glpi_tickets");
        $query = "UPDATE `glpi_tickets`\n                SET `solvedate` = `closedate`";
        $DB->queryOrDie($query, "0.78 update solvedate values in glpi_tickets");
    }
    if (!FieldExists('glpi_ticketcategories', 'entities_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `entities_id` INT NOT NULL DEFAULT '0' AFTER `id`,\n                ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `entities_id`,\n                ADD INDEX `entities_id` (`entities_id`),\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add entities_id,is_recursive in glpi_ticketcategories ");
        // Set existing categories recursive global
        $query = "UPDATE `glpi_ticketcategories`\n                SET `is_recursive` = '1'";
        $DB->queryOrDie($query, "0.78 set value of is_recursive in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'knowbaseitemcategories_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `knowbaseitemcategories_id` INT NOT NULL DEFAULT '0',\n                ADD INDEX `knowbaseitemcategories_id` ( `knowbaseitemcategories_id` )";
        $DB->queryOrDie($query, "0.78 add knowbaseitemcategories_id in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'users_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `users_id` INT NOT NULL DEFAULT '0',\n                ADD INDEX `users_id` ( `users_id` ) ";
        $DB->queryOrDie($query, "0.78 add users_id in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'groups_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `groups_id` INT NOT NULL DEFAULT '0',\n                ADD INDEX `groups_id` ( `groups_id` ) ";
        $DB->queryOrDie($query, "0.78 add groups_id in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'ancestors_cache', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `ancestors_cache` LONGTEXT NULL,\n                ADD `sons_cache` LONGTEXT NULL";
        $DB->queryOrDie($query, "0.78 add cache in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'is_helpdeskvisible', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `is_helpdeskvisible` TINYINT( 1 ) NOT NULL DEFAULT '1',\n                ADD INDEX `is_helpdeskvisible` (`is_helpdeskvisible`)";
        $DB->queryOrDie($query, "0.78 add cache in glpi_ticketcategories");
    }
    // change item type management for helpdesk
    if (FieldExists('glpi_profiles', 'helpdesk_hardware_type', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `helpdesk_item_type` TEXT NULL DEFAULT NULL AFTER `helpdesk_hardware_type`";
        $DB->queryOrDie($query, "0.78 add  helpdesk_item_type in glpi_profiles");
        $query = "SELECT `id`, `helpdesk_hardware_type`\n                FROM `glpi_profiles`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $types = $data['helpdesk_hardware_type'];
                    $CFG_GLPI["ticket_types"] = array(COMPUTER_TYPE, NETWORKING_TYPE, PRINTER_TYPE, MONITOR_TYPE, PERIPHERAL_TYPE, SOFTWARE_TYPE, PHONE_TYPE);
                    $tostore = array();
                    foreach ($CFG_GLPI["ticket_types"] as $itemtype) {
                        if (pow(2, $itemtype) & $types) {
                            $tostore[] = $typetoname[$itemtype];
                        }
                    }
                    $query = "UPDATE `glpi_profiles`\n                         SET `helpdesk_item_type` = '" . exportArrayToDB($tostore) . "'\n                         WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query, "0.78 populate helpdesk_item_type");
                }
            }
        }
        $query = "ALTER TABLE `glpi_profiles`\n                DROP `helpdesk_hardware_type`;";
        $DB->queryOrDie($query, "0.78 drop helpdesk_hardware_type in glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'helpdesk_status', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `helpdesk_status` TEXT NULL\n                                      COMMENT 'json encoded array of from/dest allowed status change'\n                                      AFTER `helpdesk_item_type`";
        $DB->queryOrDie($query, "0.78 add helpdesk_status in glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'update_priority', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `update_priority` CHAR( 1 ) NULL DEFAULT NULL AFTER `update_ticket`";
        $DB->queryOrDie($query, "0.78 add update_priority in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `update_priority` = `update_ticket`";
        $DB->queryOrDie($query, "0.78 set update_priority in glpi_profiles");
    }
    if (FieldExists('glpi_profiles', 'comment_ticket', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `comment_ticket` `add_followups` CHAR(1) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add add_followups in glpi_profiles");
    }
    if (FieldExists('glpi_profiles', 'comment_all_ticket', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `comment_all_ticket` `global_add_followups`  CHAR(1) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add add_followups in glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'update_tasks', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `global_add_tasks` CHAR( 1 ) NULL AFTER `global_add_followups`,\n                ADD `update_tasks` CHAR( 1 ) NULL AFTER `update_followups`";
        $DB->queryOrDie($query, "0.78 add global_add_tasks, update_tasks in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `update_tasks` = `update_followups`,\n                    `global_add_tasks` =  `global_add_followups`";
        $DB->queryOrDie($query, "0.78 set update_tasks, global_add_tasks in glpi_profiles");
    }
    if (!TableExists('glpi_taskcategories')) {
        $query = "CREATE TABLE `glpi_taskcategories` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `entities_id` int(11) NOT NULL default '0',\n                  `is_recursive` tinyint(1) NOT NULL default '0',\n                  `taskcategories_id` int(11) NOT NULL default '0',\n                  `name` varchar(255) default NULL,\n                  `completename` text,\n                  `comment` text,\n                  `level` int(11) NOT NULL default '0',\n                  `ancestors_cache` longtext,\n                  `sons_cache` longtext,\n                  `is_helpdeskvisible` tinyint(1) NOT NULL default '1',\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`),\n                  KEY `taskcategories_id` (`taskcategories_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_helpdeskvisible` (`is_helpdeskvisible`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_taskcategories");
    }
    if (!TableExists('glpi_ticketsolutiontypes')) {
        $query = "CREATE TABLE `glpi_ticketsolutiontypes` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) default NULL,\n                  `comment` text,\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_ticketsolutiontypes");
        // Populate only required for migration of ticket status
        $query = "INSERT INTO `glpi_ticketsolutiontypes`\n                       (`id` ,`name` ,`comment`)\n                VALUES ('1', 'Closed (solved)', NULL),\n                       ('2', 'Closed (not solved)', NULL)";
        $DB->queryOrDie($query, "0.78 populate glpi_ticketsolutiontypes");
    }
    if (!FieldExists('glpi_tickets', 'solution', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `ticketsolutiontypes_id` INT( 11 ) NOT NULL DEFAULT '0',\n                ADD `solution` TEXT NULL";
        $DB->queryOrDie($query, "0.78 create glpi_ticketsolutions");
        $query = "ALTER TABLE `glpi_tickets`\n                ADD INDEX `ticketsolutiontypes_id` ( `ticketsolutiontypes_id` ) ";
        $DB->queryOrDie($query, "0.78 add key for glpi_ticketsolutions");
        // Move old status "old_done"", "old_notdone" as solution
        // and change to new "solved" / "closed" status
        $query = "UPDATE `glpi_tickets`\n                SET `ticketsolutiontypes_id` = '2',\n                    `status` = 'closed'\n                WHERE `status` = 'old_done'";
        $DB->queryOrDie($query, "0.78 migration of glpi_tickets status");
        $query = "UPDATE `glpi_tickets`\n                SET `ticketsolutiontypes_id` = '1',\n                    `status` = 'closed'\n                WHERE `status` = 'old_notdone'";
        $DB->queryOrDie($query, "0.78 migration of glpi_tickets status");
    }
    if (!FieldExists('glpi_documenttypes', 'comment', false)) {
        $query = "ALTER TABLE `glpi_documenttypes`\n                ADD `comment` TEXT NULL ";
        $DB->queryOrDie($query, "0.78 add comment in glpi_documenttypes");
    }
    if (!FieldExists('glpi_locations', 'is_recursive', false)) {
        $query = "ALTER TABLE `glpi_locations`\n                ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `entities_id`,\n                ADD `ancestors_cache` LONGTEXT NULL,\n                ADD `sons_cache` LONGTEXT NULL,\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add recursive, cache in glpi_locations");
    }
    if (!FieldExists('glpi_locations', 'building', false)) {
        $query = "ALTER TABLE `glpi_locations`\n                ADD `building` VARCHAR( 255 ) NULL ,\n                ADD `room` VARCHAR( 255 ) NULL ";
        $DB->queryOrDie($query, "0.78 add building, room in glpi_locations");
    }
    if (!TableExists('glpi_requesttypes')) {
        $query = "CREATE TABLE `glpi_requesttypes` (\n              `id` int(11) NOT NULL AUTO_INCREMENT,\n              `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n              `is_helpdesk_default` tinyint(1) NOT NULL DEFAULT '0',\n              `is_mail_default` tinyint(1) NOT NULL DEFAULT '0',\n              `comment` text COLLATE utf8_unicode_ci,\n              PRIMARY KEY (`id`),\n              KEY `name` (`name`),\n              KEY `is_helpdesk_default` (`is_helpdesk_default`),\n              KEY `is_mail_default` (`is_mail_default`)\n            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_requesttypes");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(1, '" . addslashes(__('Simplified interface')) . "', 1, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(2, '" . addslashes(__('Email')) . "', 0, 1, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(3, '" . addslashes(__('Phone')) . "', 0, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(4, '" . addslashes(__('Direct')) . "', 0, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(5, '" . addslashes(__('Written')) . "', 0, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(6, '" . addslashes(__('Other')) . "', 0, 0, NULL)");
    }
    // Add default display
    $ADDTODISPLAYPREF['RequestType'] = array(14, 15);
    if (FieldExists('glpi_tickets', 'request_type', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                CHANGE `request_type` `requesttypes_id` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_tickets");
    }
    if (FieldExists('glpi_configs', 'default_request_type', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                CHANGE `default_request_type` `default_requesttypes_id` INT( 11 ) NOT NULL\n                                                                        DEFAULT '1'";
        $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_configs");
    }
    if (FieldExists('glpi_users', 'default_request_type', false)) {
        $query = "ALTER TABLE `glpi_users`\n                CHANGE `default_request_type` `default_requesttypes_id` INT( 11 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_users");
    }
    if (!FieldExists('glpi_groups', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_groups`\n                ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_groups");
    }
    if (!FieldExists("glpi_configs", "priority_matrix", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `priority_matrix` VARCHAR( 255 ) NULL\n                                      COMMENT 'json encoded array for Urgence / Impact to Protority'";
        $DB->queryOrDie($query, "0.78 add priority_matrix  in glpi_configs");
        $matrix = array(1 => array(1 => 1, 2 => 1, 3 => 2, 4 => 2, 4 => 2, 5 => 2), 2 => array(1 => 1, 2 => 2, 3 => 2, 4 => 3, 4 => 3, 5 => 3), 3 => array(1 => 2, 2 => 2, 3 => 3, 4 => 4, 4 => 4, 5 => 4), 4 => array(1 => 2, 2 => 3, 3 => 4, 4 => 4, 4 => 4, 5 => 5), 5 => array(1 => 2, 2 => 3, 3 => 4, 4 => 5, 4 => 5, 5 => 5));
        $matrix = exportArrayToDB($matrix);
        $query = "UPDATE `glpi_configs`\n                SET `priority_matrix` = '{$matrix}'\n                WHERE `id` = '1'";
        $DB->queryOrDie($query, "0.78 set default priority_matrix  in glpi_configs");
    }
    if (!FieldExists("glpi_configs", "urgency_mask", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `urgency_mask` INT( 11 ) NOT NULL DEFAULT '62',\n                ADD `impact_mask` INT( 11 ) NOT NULL DEFAULT '62'";
        $DB->queryOrDie($query, "0.78 add urgency/impact_mask  in glpi_configs");
    }
    if (!FieldExists("glpi_users", "priority_6", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `priority_6` CHAR( 20 ) NULL DEFAULT NULL AFTER `priority_5`";
        $DB->queryOrDie($query, "0.78 add priority_6  in glpi_users");
    }
    if (!FieldExists("glpi_configs", "priority_6", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `priority_6` CHAR( 20 ) NOT NULL DEFAULT '#ff5555' AFTER `priority_5`";
        $DB->queryOrDie($query, "0.78 add priority_6  in glpi_configs");
    }
    if (!FieldExists('glpi_tickets', 'urgency', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `urgency` INT NOT NULL DEFAULT '1' AFTER `content`,\n                ADD `impact` INT NOT NULL DEFAULT '1' AFTER `urgency`,\n                ADD INDEX `urgency` (`urgency`),\n                ADD INDEX `impact` (`impact`)";
        $DB->queryOrDie($query, "0.78 add urgency, impact to glpi_tickets");
        // set default trivial values for Impact and Urgence
        $query = "UPDATE `glpi_tickets`\n                SET `urgency` = `priority`,\n                    `impact` = `priority`";
        $DB->queryOrDie($query, "0.78 set urgency, impact in glpi_tickets");
        // Replace 'priority' (user choice un 0.72) by 'urgency' as criteria
        // Don't change "action" which is the result of user+tech evaluation.
        $query = "UPDATE `glpi_rulecriterias`\n                SET `criteria`='urgency'\n                WHERE `criteria`='priority'\n                      AND `rules_id` IN (SELECT `id`\n                                         FROM `glpi_rules`\n                                         WHERE `sub_type` = 'RuleTicket')";
        $DB->queryOrDie($query, "0.78 fix priority/urgency in business rules");
    }
    if (!TableExists('glpi_tickettasks')) {
        $query = "CREATE TABLE `glpi_tickettasks` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `tickets_id` int(11) NOT NULL default '0',\n                  `taskcategories_id` int(11) NOT NULL default '0',\n                  `date` datetime default NULL,\n                  `users_id` int(11) NOT NULL default '0',\n                  `content` longtext collate utf8_unicode_ci,\n                  `is_private` tinyint(1) NOT NULL default '0',\n                  `realtime` float NOT NULL default '0',\n                  PRIMARY KEY  (`id`),\n                  KEY `date` (`date`),\n                  KEY `users_id` (`users_id`),\n                  KEY `tickets_id` (`tickets_id`),\n                  KEY `is_private` (`is_private`),\n                  KEY `taskcategories_id` (`taskcategories_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_tickettasks");
        // Required for migration from ticketfollowups to tickettasks - planned followups
        $query = "INSERT INTO `glpi_tickettasks`\n                    (`id`, `tickets_id`, `date`, `users_id`, `content`, `is_private`, `realtime`)\n                   SELECT `glpi_ticketfollowups`.`id`,\n                          `glpi_ticketfollowups`.`tickets_id`,\n                          `glpi_ticketfollowups`.`date`,\n                          `glpi_ticketfollowups`.`users_id`,\n                          `glpi_ticketfollowups`.`content`,\n                          `glpi_ticketfollowups`.`is_private`,\n                          `glpi_ticketfollowups`.`realtime`\n                   FROM `glpi_ticketfollowups`\n                   INNER JOIN `glpi_ticketplannings`\n                     ON (`glpi_ticketplannings`.`ticketfollowups_id` = `glpi_ticketfollowups`.`id`)";
        $DB->queryOrDie($query, "0.78 populate glpi_tickettasks");
        // delete from ticketfollowups - planned followups, previously copied
        $query = "DELETE FROM `glpi_ticketfollowups`\n                WHERE `glpi_ticketfollowups`.`id`\n                        IN (SELECT `glpi_ticketplannings`.`ticketfollowups_id`\n                            FROM `glpi_ticketplannings`)";
        $DB->queryOrDie($query, "0.78 delete from glpi_ticketfollowups");
        // Required for migration from ticketfollowups to tickettasks - followups with a duration
        $query = "INSERT INTO `glpi_tickettasks`\n                    (`id`, `tickets_id`, `date`, `users_id`, `content`, `is_private`, `realtime`)\n                   SELECT `glpi_ticketfollowups`.`id`,\n                          `glpi_ticketfollowups`.`tickets_id`,\n                          `glpi_ticketfollowups`.`date`,\n                          `glpi_ticketfollowups`.`users_id`,\n                          `glpi_ticketfollowups`.`content`,\n                          `glpi_ticketfollowups`.`is_private`,\n                          `glpi_ticketfollowups`.`realtime`\n                   FROM `glpi_ticketfollowups`\n                   WHERE `realtime`>0";
        $DB->queryOrDie($query, "0.78 populate glpi_tickettasks");
        // delete from ticketfollowups - followups with duration, previously copied
        $query = "DELETE FROM `glpi_ticketfollowups`\n                WHERE `realtime` > 0";
        $DB->queryOrDie($query, "0.78 delete from glpi_ticketfollowups");
        // ticketplannings is for tickettasks
        $query = "ALTER TABLE `glpi_ticketplannings`\n                CHANGE `ticketfollowups_id` `tickettasks_id` int(11) NOT NULL default '0'";
        $DB->queryOrDie($query, "0.78 alter glpi_ticketplannings");
        // add requesttype for glpi_ticketfollowups
        $query = "ALTER TABLE `glpi_ticketfollowups`\n                DROP `realtime`,\n                ADD `requesttypes_id` int(11) NOT NULL default '0',\n                ADD INDEX `requesttypes_id` (`requesttypes_id`)";
        $DB->queryOrDie($query, "0.78 alter glpi_ticketplannings");
    }
    // Migrate devices
    if (TableExists('glpi_computer_device')) {
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), _n('Component', 'Components', 2)));
        foreach ($devtypetoname as $key => $itemtype) {
            $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $itemtype));
            $linktype = "Computer_{$itemtype}";
            $linktable = getTableForItemType($linktype);
            $itemtable = getTableForItemType($itemtype);
            $fkname = getForeignKeyFieldForTable($itemtable);
            $withspecifity = array(MOBOARD_DEVICE => false, PROCESSOR_DEVICE => 'int', RAM_DEVICE => 'int', HDD_DEVICE => 'int', NETWORK_DEVICE => 'varchar', DRIVE_DEVICE => false, CONTROL_DEVICE => false, GFX_DEVICE => 'int', SND_DEVICE => false, PCI_DEVICE => false, CASE_DEVICE => false, POWER_DEVICE => false);
            if (FieldExists($itemtable, 'specif_default', false)) {
                // Convert default specifity
                if ($withspecifity[$key]) {
                    // Convert data to int
                    if ($withspecifity[$key] == 'int') {
                        // clean non integer values
                        $query = "UPDATE `{$itemtable}`\n                            SET `specif_default` = 0\n                            WHERE `specif_default` NOT REGEXP '^[0-9]*\$'\n                                  OR `specif_default` = ''\n                                  OR `specif_default` IS NULL";
                        $DB->queryOrDie($query, "0.78 update specif_default in {$itemtable}");
                        $query = "ALTER TABLE `{$itemtable}`\n                            CHANGE `specif_default` `specif_default` INT(11) NOT NULL";
                        $DB->queryOrDie($query, "0.78 alter specif_default in {$itemtable}");
                    }
                } else {
                    // Drop default specificity
                    $query = "ALTER TABLE `{$itemtable}`\n                         DROP `specif_default`";
                    $DB->queryOrDie($query, "0.78 drop specif_default in {$itemtable}");
                }
            }
            if (!TableExists($linktable)) {
                // create table
                $query = "CREATE TABLE `{$linktable}` (\n                        `id` int(11) NOT NULL auto_increment,\n                        `computers_id` int(11) NOT NULL default '0',\n                        `{$fkname}` int(11) NOT NULL default '0',";
                if ($withspecifity[$key]) {
                    if ($withspecifity[$key] == 'int') {
                        $query .= "`specificity` int(11) NOT NULL,";
                    } else {
                        $query .= "`specificity` varchar(255) collate utf8_unicode_ci default NULL,";
                    }
                }
                $query .= "PRIMARY KEY  (`id`),\n                       KEY `computers_id` (`computers_id`),\n                       KEY `{$fkname}` (`{$fkname}`)";
                if ($withspecifity[$key]) {
                    $query .= ",KEY `specificity` (`specificity`)";
                }
                $query .= ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
                $DB->queryOrDie($query, "0.78 create {$linktable}");
                // Update data before copy
                if ($withspecifity[$key]) {
                    // Convert data to int
                    if ($withspecifity[$key] == 'int') {
                        // clean non integer values
                        $query = "UPDATE `glpi_computer_device`\n                            SET `specificity` = 0\n                            WHERE device_type = {$key}\n                                 AND `specificity` NOT REGEXP '^[0-9]*\$'\n                                     OR `specificity` = ''";
                        $DB->queryOrDie($query, "0.78 update specificity in glpi_computer_device for {$itemtype}");
                    }
                }
                // copy datas to new table : keep id for ocs sync
                $query = "INSERT INTO `{$linktable}` (`id`, `computers_id`, `{$fkname}`\n                                                " . ($withspecifity[$key] ? ", `specificity`" : '') . ")\n                        SELECT `ID`, `FK_computers`, `FK_device`\n                               " . ($withspecifity[$key] ? ", specificity" : '') . "\n                        FROM `glpi_computer_device`\n                        WHERE `device_type` = {$key}";
                $DB->queryOrDie($query, "0.78 populate {$linktable}");
            }
        }
        // Drop computer_device_table
        $query = "DROP TABLE `glpi_computer_device`";
        $DB->queryOrDie($query, "0.78 drop glpi_computer_device");
    }
    if (!FieldExists('glpi_users', 'task_private', false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `task_private` TINYINT(1) DEFAULT NULL AFTER `followup_private`";
        $DB->queryOrDie($query, "0.78 add task_private to glpi_users");
    }
    if (!FieldExists('glpi_configs', 'task_private', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `task_private` TINYINT(1) NOT NULL DEFAULT '0' AFTER `followup_private`";
        $DB->queryOrDie($query, "0.78 add task_private to glpi_users");
    }
    if (!FieldExists('glpi_rules', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_rules`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_rules");
    }
    if (!FieldExists('glpi_authldaps', 'entity_field', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `entity_field` VARCHAR( 255 ) DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add entity_field to glpi_authldaps");
    }
    if (!FieldExists('glpi_authldaps', 'entity_condition', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n               ADD `entity_condition`  TEXT NULL collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add entity_condition to glpi_authldaps");
    }
    if (!FieldExists('glpi_entitydatas', 'ldapservers_id', false)) {
        $query = "ALTER TABLE `glpi_entitydatas`\n               ADD `ldapservers_id` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add ldapservers_id to glpi_entitydatas");
    }
    if (!FieldExists('glpi_entitydatas', 'mail_domain', false)) {
        $query = "ALTER TABLE `glpi_entitydatas`\n                ADD `mail_domain` VARCHAR( 255 ) DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add mail_domain to glpi_entitydatas");
    }
    if (!FieldExists('glpi_entitydatas', 'entity_ldapfilter', false)) {
        $query = "ALTER TABLE `glpi_entitydatas`\n                ADD `entity_ldapfilter` TEXT NULL collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add entity_ldapfilter to glpi_entitydatas");
    }
    if (!FieldExists('glpi_profiles', 'import_externalauth_users', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `import_externalauth_users` CHAR( 1 ) NULL";
        $DB->queryOrDie($query, "0.78 add import_externalauth_users in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `import_externalauth_users` = 'w'\n                WHERE `user` ='w'";
        $DB->queryOrDie($query, "0.78 add import_externalauth_users right users which are able to write users");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Notifications'));
    $templates = array();
    if (!TableExists('glpi_notificationtemplates')) {
        $query = "CREATE TABLE `glpi_notificationtemplates` (\n                 `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n                 `name` VARCHAR( 255 ) default NULL ,\n                 `itemtype` VARCHAR( 100 ) NOT NULL,\n                 `date_mod` DATETIME DEFAULT NULL ,\n                 `comment` text collate utf8_unicode_ci,\n                 PRIMARY KEY ( `ID` ),\n                 KEY `itemtype` (`itemtype`),\n                 KEY `date_mod` (`date_mod`),\n                 KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_notificationtemplates");
        $queries['DBConnection'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'MySQL Synchronization', 'DBConnection', NOW(),'');";
        $queries['Reservation'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Reservations', 'Reservation', NOW(),'');";
        $queries['Reservation2'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Alert Reservation', 'Reservation', NOW(),'');";
        $queries['Ticket'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Tickets', 'Ticket', NOW(),'');";
        $queries['Ticket2'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Tickets (Simple)', 'Ticket', NOW(),'');";
        $queries['Ticket3'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Alert Tickets not closed', 'Ticket', NOW(),'');";
        $queries['TicketValidation'] = "INSERT INTO `glpi_notificationtemplates`\n                                    VALUES(NULL, 'Tickets Validation', 'Ticket', NOW(),'');";
        $queries['Cartridge'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Cartridges', 'Cartridge', NOW(),'');";
        $queries['Consumable'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Consumables', 'Consumable', NOW(),'');";
        $queries['Infocom'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Infocoms', 'Infocom', NOW(),'');";
        $queries['SoftwareLicense'] = "INSERT INTO `glpi_notificationtemplates`\n                                     VALUES(NULL, 'Licenses', 'SoftwareLicense', NOW(),'');";
        $queries['Contract'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Contracts', 'Contract', NOW(),'');";
        foreach ($queries as $itemtype => $query) {
            $DB->queryOrDie($query, "0.78 insert notification template for {$itemtype}");
            $templates[$itemtype] = $DB->insert_id();
        }
        $ADDTODISPLAYPREF['NotificationTemplate'] = array(4, 16);
        //There was a problem with GLPI < 0.78 : smtp_port field wans'nt used : migrate it
        $query = "SELECT `smtp_host`\n                FROM `glpi_configs`\n                WHERE `id` = '1'";
        $result = $DB->query($query);
        $host = $DB->result($result, 0, 'smtp_host');
        $results = array();
        preg_match("/(.*):([0-9]*)/", $host, $results);
        if (!empty($results)) {
            $query = "UPDATE `glpi_configs`\n                   SET `smtp_host` = '" . $results[1] . "' ,\n                       `smtp_port` = '" . $results[2] . "'\n                   WHERE `id` = '1'";
            $DB->query($query);
        }
    }
    if (!TableExists('glpi_notificationtemplatetranslations')) {
        $query = "CREATE TABLE `glpi_notificationtemplatetranslations` (\n                  `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n                  `notificationtemplates_id` INT( 11 ) NOT NULL DEFAULT '0',\n                  `language` CHAR ( 5 ) NOT NULL DEFAULT '',\n                  `subject` VARCHAR( 255 ) NOT NULL ,\n                  `content_text` TEXT NULL ,\n                  `content_html` TEXT NULL ,\n                  PRIMARY KEY ( `id` ),\n                  KEY `notificationtemplates_id` (`notificationtemplates_id`)\n                 )ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_notificationtemplatetranslations");
        $queries = array();
        $queries['DBConnection'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                  VALUES(NULL, " . $templates['DBConnection'] . ", '','##lang.dbconnection.title##',\n                        '##lang.dbconnection.delay## : ##dbconnection.delay##\r\n',\n                        '&lt;p&gt;##lang.dbconnection.delay## : ##dbconnection.delay##&lt;/p&gt;');";
        $content_text_reservation = "======================================================================\r\n" . "##lang.reservation.user##: ##reservation.user##\r\n" . "##lang.reservation.item.name##: ##reservation.itemtype## - ##reservation.item.name##\r\n" . "##IFreservation.tech## ##lang.reservation.tech## ##reservation.tech## ##ENDIFreservation.tech##\r\n" . "##lang.reservation.begin##: ##reservation.begin##\r\n" . "##lang.reservation.end##: ##reservation.end##\r\n" . "##lang.reservation.comment##: ##reservation.comment##\r\n" . "======================================================================\r\n";
        $content_html_reservation = "&lt;!-- description{ color: inherit; background: #ebebeb;" . "border-style: solid;border-color: #8d8d8d; border-width: 0px 1px 1px 0px; }" . " --&gt;\r\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.user##:&lt;/span&gt;##reservation.user##" . "&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.item.name##:&lt;/span&gt;" . "##reservation.itemtype## - ##reservation.item.name##&lt;br /&gt;" . "##IFreservation.tech## ##lang.reservation.tech## ##reservation.tech##" . "##ENDIFreservation.tech##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.begin##:&lt;/span&gt; ##reservation.begin##" . "&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.end##:&lt;/span&gt;" . "##reservation.end##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.comment##:&lt;/span&gt; ##reservation.comment##" . "&lt;/p&gt;";
        $queries['Reservation'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                 VALUES(NULL, " . $templates['Reservation'] . ", '',\n                                        '##reservation.action##', '{$content_text_reservation}',\n                                        '{$content_html_reservation}')";
        $queries['Reservation2'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                  VALUES(NULL, " . $templates['Reservation2'] . ", '',\n                                    '##reservation.action##  ##reservation.entity##',\n                                    '##lang.reservation.entity## : ##reservation.entity## \r\n\n \r\n##FOREACHreservations## \r\n##lang.reservation.itemtype## : ##reservation.itemtype##\r\n\n ##lang.reservation.item## : ##reservation.item##\r\n \r\n ##reservation.url## \r\n\n ##ENDFOREACHreservations##',\n '&lt;p&gt;##lang.reservation.entity## : ##reservation.entity## &lt;br /&gt; &lt;br /&gt;\n##FOREACHreservations## &lt;br /&gt;##lang.reservation.itemtype## : ##reservation.itemtype##&lt;br /&gt;\n ##lang.reservation.item## : ##reservation.item##&lt;br /&gt; &lt;br /&gt;\n &lt;a href=\"##reservation.url##\"&gt; ##reservation.url##&lt;/a&gt;&lt;br /&gt;\n ##ENDFOREACHreservations##&lt;/p&gt;');";
        $queries['Ticket'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                            VALUES(NULL, '" . $templates['Ticket'] . "', '',\n                            '##ticket.action## ##ticket.title##',\n' ##IFticket.storestatus=solved##\n ##lang.ticket.url## : ##ticket.urlapprove##\n ##lang.ticket.autoclosewarning##\n ##lang.ticket.solvedate## : ##ticket.solvedate##\n ##lang.ticket.solution.type## : ##ticket.solution.type##\n ##lang.ticket.solution.description## : ##ticket.solution.description## ##ENDIFticket.storestatus##\n ##ELSEticket.storestatus## ##lang.ticket.url## : ##ticket.url## ##ENDELSEticket.storestatus##\n\n ##lang.ticket.description##\n\n ##lang.ticket.title## : ##ticket.title##\n ##lang.ticket.author.name## : ##IFticket.author.name## ##ticket.author.name## ##ENDIFticket.author.name## ##ELSEticket.author.name##--##ENDELSEticket.author.name##\n ##lang.ticket.creationdate## : ##ticket.creationdate##\n ##lang.ticket.closedate## : ##ticket.closedate##\n ##lang.ticket.requesttype## : ##ticket.requesttype##\n ##IFticket.itemtype## ##lang.ticket.item.name## : ##ticket.itemtype## - ##ticket.item.name## ##IFticket.item.model## - ##ticket.item.model## ##ENDIFticket.item.model## ##IFticket.item.serial## - ##ticket.item.serial## ##ENDIFticket.item.serial##  ##IFticket.item.otherserial## -##ticket.item.otherserial## ##ENDIFticket.item.otherserial## ##ENDIFticket.itemtype##\n##IFticket.assigntouser## ##lang.ticket.assigntouser## : ##ticket.assigntouser## ##ENDIFticket.assigntouser##\n ##lang.ticket.status## : ##ticket.status##\n##IFticket.assigntogroup## ##lang.ticket.assigntogroup## : ##ticket.assigntogroup## ##ENDIFticket.assigntogroup##\n ##lang.ticket.urgency## : ##ticket.urgency##\n ##lang.ticket.impact## : ##ticket.impact##\n ##lang.ticket.priority## : ##ticket.priority##\n##IFticket.user.email## ##lang.ticket.user.email## : ##ticket.user.email ##ENDIFticket.user.email##\n##IFticket.category## ##lang.ticket.category## : ##ticket.category## ##ENDIFticket.category## ##ELSEticket.category## ##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n ##lang.ticket.content## : ##ticket.content##\n\n ##IFticket.storestatus=closed##\n\n ##lang.ticket.solvedate## : ##ticket.solvedate##\n ##lang.ticket.solution.type## : ##ticket.solution.type##\n ##lang.ticket.solution.description## : ##ticket.solution.description##\n ##ENDIFticket.storestatus##\n ##lang.ticket.numberoffollowups## : ##ticket.numberoffollowups##\n\n##FOREACHfollowups##\n\n [##followup.date##] ##lang.followup.isprivate## : ##followup.isprivate##\n ##lang.followup.author## ##followup.author##\n ##lang.followup.description## ##followup.description##\n ##lang.followup.date## ##followup.date##\n ##lang.followup.requesttype## ##followup.requesttype##\n\n##ENDFOREACHfollowups##\n ##lang.ticket.numberoftasks## : ##ticket.numberoftasks##\n\n##FOREACHtasks##\n\n [##task.date##] ##lang.task.isprivate## : ##task.isprivate##\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##',\n'<!-- description{ color: inherit; background: #ebebeb; border-style: solid;border-color: #8d8d8d; border-width: 0px 1px 1px 0px; }    -->\n<div>##IFticket.storestatus=solved##</div>\n<div>##lang.ticket.url## : <a href=\"##ticket.urlapprove##\">##ticket.urlapprove##</a> <span class=\"b\">&#160;</span></div>\n<div><span class=\"b\">##lang.ticket.autoclosewarning##</span> </div>\n<div><span style=\"color: #888888;\"><span class=\"b\"><span style=\"text-decoration: underline;\">##lang.ticket.solvedate##</span></span></span> : ##ticket.solvedate##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.type##</span></span> : ##ticket.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.description##</span></span> : ##ticket.solution.description## ##ENDIFticket.storestatus##</div>\n<div>##ELSEticket.storestatus## ##lang.ticket.url## : <a href=\"##ticket.url##\">##ticket.url##</a> ##ENDELSEticket.storestatus##</div>\n<div class=\"description b\"><span class=\"b\">##lang.ticket.description##</span></div>\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.title##</span>&#160;:##ticket.title## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.author.name##</span>&#160;:##IFticket.author.name## ##ticket.author.name## ##ENDIFticket.author.name##    ##ELSEticket.author.name##--##ENDELSEticket.author.name## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.creationdate##</span>&#160;:##ticket.creationdate## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.closedate##</span>&#160;:##ticket.closedate## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.requesttype##</span>&#160;:##ticket.requesttype##<br /> ##IFticket.itemtype## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.item.name##</span>&#160;: ##ticket.itemtype## - ##ticket.item.name##    ##IFticket.item.model## - ##ticket.item.model##    ##ENDIFticket.item.model## ##IFticket.item.serial## -##ticket.item.serial## ##ENDIFticket.item.serial##&#160; ##IFticket.item.otherserial## -##ticket.item.otherserial##  ##ENDIFticket.item.otherserial## ##ENDIFticket.itemtype## <br /> ##IFticket.assigntouser## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.assigntouser##</span>&#160;: ##ticket.assigntouser## ##ENDIFticket.assigntouser##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.ticket.status## </span>&#160;: ##ticket.status##<br /> ##IFticket.assigntogroup## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.assigntogroup##</span>&#160;: ##ticket.assigntogroup## ##ENDIFticket.assigntogroup##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.urgency##</span>&#160;: ##ticket.urgency##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.impact##</span>&#160;: ##ticket.impact##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.priority##</span>&#160;: ##ticket.priority## <br /> ##IFticket.user.email##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.user.email##</span>&#160;: ##ticket.user.email ##ENDIFticket.user.email##    <br /> ##IFticket.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.ticket.category## </span>&#160;:##ticket.category## ##ENDIFticket.category## ##ELSEticket.category## ##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##    <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.content##</span>&#160;: ##ticket.content##</p>\n<br />##IFticket.storestatus=closed##<br /><span style=\"text-decoration: underline;\"><span class=\"b\"><span style=\"color: #888888;\">##lang.ticket.solvedate##</span></span></span> : ##ticket.solvedate##<br /><span style=\"color: #888888;\"><span class=\"b\"><span style=\"text-decoration: underline;\">##lang.ticket.solution.type##</span></span></span> : ##ticket.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.description##</span></span> : ##ticket.solution.description##<br />##ENDIFticket.storestatus##</p>\n<div class=\"description b\">##lang.ticket.numberoffollowups##&#160;: ##ticket.numberoffollowups##</div>\n<p>##FOREACHfollowups##</p>\n<div class=\"description b\"><br /> <span class=\"b\"> [##followup.date##] <em>##lang.followup.isprivate## : ##followup.isprivate## </em></span><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.author## </span> ##followup.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.description## </span> ##followup.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.date## </span> ##followup.date##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.requesttype## </span> ##followup.requesttype##</div>\n<p>##ENDFOREACHfollowups##</p>\n<div class=\"description b\">##lang.ticket.numberoftasks##&#160;: ##ticket.numberoftasks##</div>\n<p>##FOREACHtasks##</p>\n<div class=\"description b\"><br /> <span class=\"b\"> [##task.date##] <em>##lang.task.isprivate## : ##task.isprivate## </em></span><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.author##</span> ##task.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.description##</span> ##task.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.time##</span> ##task.time##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.category##</span> ##task.category##</div>\n<p>##ENDFOREACHtasks##</p>');";
        $queries['Contract'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                              VALUES(NULL, " . $templates['Contract'] . ", '',\n                              '##contract.action##  ##contract.entity##',\n                              '##lang.contract.entity## : ##contract.entity##\r\n" . "\r\n##FOREACHcontracts##\r\n" . "##lang.contract.name## : ##contract.name##\r\n" . "##lang.contract.number## : ##contract.number##\r\n" . "##lang.contract.time## : ##contract.time##\r\n" . "##IFcontract.type####lang.contract.type## : ##contract.type##" . "##ENDIFcontract.type##\r\n" . "##contract.url##\r\n" . "##ENDFOREACHcontracts##',\n'&lt;p&gt;##lang.contract.entity## : ##contract.entity##&lt;br /&gt;\n&lt;br /&gt;##FOREACHcontracts##&lt;br /&gt;##lang.contract.name## :\n##contract.name##&lt;br /&gt;\n##lang.contract.number## : ##contract.number##&lt;br /&gt;\n##lang.contract.time## : ##contract.time##&lt;br /&gt;\n##IFcontract.type####lang.contract.type## : ##contract.type##\n##ENDIFcontract.type##&lt;br /&gt;\n&lt;a href=\"##contract.url##\"&gt;\n##contract.url##&lt;/a&gt;&lt;br /&gt;\n##ENDFOREACHcontracts##&lt;/p&gt;');";
        $queries['Ticket2'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                             VALUES(NULL, " . $templates['Ticket2'] . ", '',\n                            '##ticket.action## ##ticket.title##',\n'##lang.ticket.url## : ##ticket.url## \r\n\n##lang.ticket.description## \r\n\n\n##lang.ticket.title## &#160;:##ticket.title## \n\n##lang.ticket.author.name## &#160;:##IFticket.author.name##\n##ticket.author.name## ##ENDIFticket.author.name##\n##ELSEticket.author.name##--##ENDELSEticket.author.name## &#160; \n\n##IFticket.category## ##lang.ticket.category## &#160;:##ticket.category##\n##ENDIFticket.category## ##ELSEticket.category##\n##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n\n##lang.ticket.content## &#160;: ##ticket.content##\n##IFticket.itemtype##\n##lang.ticket.item.name## &#160;: ##ticket.itemtype## - ##ticket.item.name##\n##ENDIFticket.itemtype##',\n'&lt;div&gt;##lang.ticket.url## : &lt;a href=\"##ticket.url##\"&gt;\n##ticket.url##&lt;/a&gt;&lt;/div&gt;\r\n&lt;div class=\"description b\"&gt;\n##lang.ticket.description##&lt;/div&gt;\r\n&lt;p&gt;&lt;span\nstyle=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.title##&lt;/span&gt;&#160;:##ticket.title##\n&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.author.name##&lt;/span&gt;\n##IFticket.author.name## ##ticket.author.name##\n##ENDIFticket.author.name##\n##ELSEticket.author.name##--##ENDELSEticket.author.name##\n&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;&#160\n;&lt;/span&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; &lt;/span&gt;\n##IFticket.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.category## &lt;/span&gt;&#160;:##ticket.category##\n##ENDIFticket.category## ##ELSEticket.category##\n##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.content##&lt;/span&gt;&#160;:\n##ticket.content##&lt;br /&gt;##IFticket.itemtype##\n&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.item.name##&lt;/span&gt;&#160;:\n##ticket.itemtype## - ##ticket.item.name##\n##ENDIFticket.itemtype##&lt;/p&gt;');";
        $queries['TicketValidation'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                             VALUES(NULL, " . $templates['TicketValidation'] . ", '',\n                            '##ticket.action## ##ticket.title##',\n'##FOREACHvalidations##\n\n##IFvalidation.storestatus=waiting##\n##validation.submission.title##\n##lang.validation.commentsubmission## : ##validation.commentsubmission##\n##ENDIFvalidation.storestatus##\n##ELSEvalidation.storestatus## ##validation.answer.title## ##ENDELSEvalidation.storestatus##\n\n##lang.ticket.url## : ##ticket.urlvalidation##\n\n##IFvalidation.status## ##lang.validation.validationstatus## ##ENDIFvalidation.status##\n##IFvalidation.commentvalidation##\n##lang.validation.commentvalidation## : ##validation.commentvalidation##\n##ENDIFvalidation.commentvalidation##\n##ENDFOREACHvalidations##',\n'&lt;div&gt;##FOREACHvalidations##&lt;/div&gt;\n&lt;p&gt;##IFvalidation.storestatus=waiting##&lt;/p&gt;\n&lt;div&gt;##validation.submission.title##&lt;/div&gt;\n&lt;div&gt;##lang.validation.commentsubmission## : ##validation.commentsubmission##&lt;/div&gt;\n&lt;div&gt;##ENDIFvalidation.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEvalidation.storestatus## ##validation.answer.title## ##ENDELSEvalidation.storestatus##&lt;/div&gt;\n&lt;div&gt;&lt;/div&gt;\n&lt;div&gt;\n&lt;div&gt;##lang.ticket.url## : &lt;a href=\"##ticket.urlvalidation##\"&gt; ##ticket.urlvalidation## &lt;/a&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;p&gt;##IFvalidation.status## ##lang.validation.validationstatus## ##ENDIFvalidation.status##\n&lt;br /&gt; ##IFvalidation.commentvalidation##&lt;br /&gt; ##lang.validation.commentvalidation## :\n&#160; ##validation.commentvalidation##&lt;br /&gt; ##ENDIFvalidation.commentvalidation##\n&lt;br /&gt;##ENDFOREACHvalidations##&lt;/p&gt;');";
        $queries['Ticket3'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                             VALUES(NULL, " . $templates['Ticket3'] . ", '',\n                             '##ticket.action## ##ticket.entity##',\n'##lang.ticket.entity## : ##ticket.entity##\n \n##FOREACHtickets##\n\n##lang.ticket.title## : ##ticket.title##\n ##lang.ticket.status## : ##ticket.status##\n\n ##ticket.url## \n ##ENDFOREACHtickets##',\n'&lt;table class=\"tab_cadre\" border=\"1\" cellspacing=\"2\" cellpadding=\"3\"&gt;\n&lt;tbody&gt;\n&lt;tr&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.author.name##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.title##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.priority##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.status##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.attribution##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.creationdate##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.content##&lt;/span&gt;&lt;/td&gt;\n&lt;/tr&gt;\n##FOREACHtickets##\n&lt;tr&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.author.name##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;&lt;a href=\"##ticket.url##\"&gt;##ticket.title##&lt;/a&gt;&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.priority##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.status##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##IFticket.assigntouser####ticket.assigntouser##&lt;br /&gt;##ENDIFticket.assigntouser####IFticket.assigntogroup##&lt;br /&gt;##ticket.assigntogroup## ##ENDIFticket.assigntogroup####IFticket.assigntosupplier##&lt;br /&gt;##ticket.assigntosupplier## ##ENDIFticket.assigntosupplier##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.creationdate##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.content##&lt;/span&gt;&lt;/td&gt;\n&lt;/tr&gt;\n##ENDFOREACHtickets##\n&lt;/tbody&gt;\n&lt;/table&gt;');";
        $queries['Consumable'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                           VALUES(NULL, " . $templates['Consumable'] . ", '',\n                           '##consumable.action##  ##consumable.entity##',\n'##lang.consumable.entity## : ##consumable.entity##\n \n\n##FOREACHconsumables##\n##lang.consumable.item## : ##consumable.item##\n \n\n##lang.consumable.reference## : ##consumable.reference##\n\n##lang.consumable.remaining## : ##consumable.remaining##\n\n##consumable.url## \n\n##ENDFOREACHconsumables##', '&lt;p&gt;\n##lang.consumable.entity## : ##consumable.entity##\n&lt;br /&gt; &lt;br /&gt;##FOREACHconsumables##\n&lt;br /&gt;##lang.consumable.item## : ##consumable.item##&lt;br /&gt;\n&lt;br /&gt;##lang.consumable.reference## : ##consumable.reference##&lt;br /&gt;\n##lang.consumable.remaining## : ##consumable.remaining##&lt;br /&gt;\n&lt;a href=\"##consumable.url##\"&gt; ##consumable.url##&lt;/a&gt;&lt;br /&gt;\n   ##ENDFOREACHconsumables##&lt;/p&gt;');";
        $queries['Cartridge'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                               VALUES(NULL, " . $templates['Cartridge'] . ", '',\n                               '##cartridge.action##  ##cartridge.entity##',\n'##lang.cartridge.entity## : ##cartridge.entity##\n \n\n##FOREACHcartridges##\n##lang.cartridge.item## : ##cartridge.item##\n \n\n##lang.cartridge.reference## : ##cartridge.reference##\n\n##lang.cartridge.remaining## : ##cartridge.remaining##\n\n##cartridge.url## \n ##ENDFOREACHcartridges##',\n'&lt;p&gt;##lang.cartridge.entity## :##cartridge.entity##\n&lt;br /&gt; &lt;br /&gt;##FOREACHcartridges##\n&lt;br /&gt;##lang.cartridge.item## :\n##cartridge.item##&lt;br /&gt; &lt;br /&gt;\n##lang.cartridge.reference## :\n##cartridge.reference##&lt;br /&gt;\n##lang.cartridge.remaining## :\n##cartridge.remaining##&lt;br /&gt;\n&lt;a href=\"##cartridge.url##\"&gt;\n##cartridge.url##&lt;/a&gt;&lt;br /&gt;\n##ENDFOREACHcartridges##&lt;/p&gt;');";
        $queries['Infocom'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                              VALUES(NULL, " . $templates['Infocom'] . ", '',\n                             '##infocom.action##  ##infocom.entity##',\n'##lang.infocom.entity## : ##infocom.entity## \n \n\n##FOREACHinfocoms## \n\n##lang.infocom.itemtype## : ##infocom.itemtype##\n\n##lang.infocom.item## : ##infocom.item##\n \n\n##lang.infocom.expirationdate## : ##infocom.expirationdate##\n\n##infocom.url## \n ##ENDFOREACHinfocoms##',\n'&lt;p&gt;##lang.infocom.entity## : ##infocom.entity##\n&lt;br /&gt; &lt;br /&gt;##FOREACHinfocoms##\n&lt;br /&gt;##lang.infocom.itemtype## : ##infocom.itemtype##&lt;br /&gt;\n##lang.infocom.item## : ##infocom.item##&lt;br /&gt; &lt;br /&gt;\n##lang.infocom.expirationdate## : ##infocom.expirationdate##\n&lt;br /&gt; &lt;a href=\"##infocom.url##\"&gt;\n##infocom.url##&lt;/a&gt;&lt;br /&gt;\n##ENDFOREACHinfocoms##&lt;/p&gt;');";
        $queries['SoftwareLicense'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                     VALUES(NULL, " . $templates['SoftwareLicense'] . ", '',\n                                    '##license.action##  ##license.entity##',\n'##lang.license.entity## : ##license.entity##\r\n\n##FOREACHlicenses## \r\n\n##lang.license.item## : ##license.item##\r\n\n##lang.license.serial## : ##license.serial##\r\n\n##lang.license.expirationdate## : ##license.expirationdate##\r\n\n##license.url## \r\n ##ENDFOREACHlicenses##', '&lt;p&gt;\n##lang.license.entity## : ##license.entity##&lt;br /&gt;\n##FOREACHlicenses##\n&lt;br /&gt;##lang.license.item## : ##license.item##&lt;br /&gt;\n##lang.license.serial## : ##license.serial##&lt;br /&gt;\n##lang.license.expirationdate## : ##license.expirationdate##\n&lt;br /&gt; &lt;a href=\"##license.url##\"&gt; ##license.url##\n&lt;/a&gt;&lt;br /&gt; ##ENDFOREACHlicenses##&lt;/p&gt;');";
        foreach ($queries as $itemtype => $query) {
            $DB->queryOrDie($query, "0.78 insert notification template default translation for {$itemtype}");
        }
        unset($queries);
    }
    $notifications = array();
    if (!TableExists('glpi_notifications')) {
        $query = "CREATE TABLE `glpi_notifications` (\n                 `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n                 `name` VARCHAR( 255 ) DEFAULT NULL ,\n                 `entities_id` INT( 11 ) NOT NULL DEFAULT '0',\n                 `itemtype` VARCHAR( 100 ) NOT NULL ,\n                 `event` VARCHAR( 255 ) NOT NULL ,\n                 `mode` VARCHAR( 255 ) NOT NULL ,\n                 `notificationtemplates_id` INT( 11 ) NOT NULL DEFAULT '0',\n                 `comment` TEXT DEFAULT NULL ,\n                 `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                 `is_active` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                 `date_mod` DATETIME DEFAULT NULL ,\n                  PRIMARY KEY ( `id` ),\n                  KEY `name` (`name`),\n                  KEY `itemtype` (`itemtype`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_active` (`is_active`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `notificationtemplates_id` (`notificationtemplates_id`)\n                  ) ENGINE = MYISAM CHARSET utf8 COLLATE utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.78 create glpi_notifications");
        $queries = array();
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Alert Tickets not closed', 0, 'Ticket', 'alertnotclosed',\n                            'mail'," . $templates['Ticket3'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'New Ticket', 0, 'Ticket', 'new', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Ticket', 0, 'Ticket', 'update', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Close Ticket', 0, 'Ticket', 'closed', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Add Followup', 0, 'Ticket', 'add_followup', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Add Task', 0, 'Ticket', 'add_task', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Followup', 0, 'Ticket', 'update_followup', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Task', 0, 'Ticket', 'update_task', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Delete Followup', 0, 'Ticket', 'delete_followup', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Delete Task', 0, 'Ticket', 'delete_task', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Resolve ticket', 0, 'Ticket', 'solved', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Ticket Validation', 0, 'Ticket', 'validation', 'mail',\n                            " . $templates['TicketValidation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'New Reservation', 0, 'Reservation', 'new', 'mail',\n                            " . $templates['Reservation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Reservation', 0, 'Reservation', 'update', 'mail',\n                            " . $templates['Reservation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Delete Reservation', 0, 'Reservation', 'delete', 'mail',\n                            " . $templates['Reservation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Alert Reservation', 0, 'Reservation', 'alert', 'mail',\n                            " . $templates['Reservation2'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Contract Notice', 0, 'Contract', 'notice', 'mail',\n                            " . $templates['Contract'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Contract End', 0, 'Contract', 'end', 'mail',\n                            " . $templates['Contract'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'MySQL Synchronization', 0, 'DBConnection', 'desynchronization',\n                            'mail'," . $templates['DBConnection'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Cartridges', 0, 'Cartridge', 'alert', 'mail',\n                            " . $templates['Cartridge'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Consumables', 0, 'Consumable', 'alert', 'mail',\n                            " . $templates['Consumable'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Infocoms', 0, 'Infocom', 'alert', 'mail',\n                            " . $templates['Infocom'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Software Licenses', 0, 'SoftwareLicense', 'alert', 'mail',\n                            " . $templates['SoftwareLicense'] . ", '', 1, 1, NOW())";
        foreach ($queries as $query) {
            $DB->queryOrDie($query, "0.78 insert notification");
        }
        $ADDTODISPLAYPREF['Notification'] = array(5, 6, 2, 4, 80, 86);
        unset($queries);
    }
    if (!TableExists('glpi_notificationtargets') && TableExists('glpi_mailingsettings')) {
        $query = "RENAME TABLE `glpi_mailingsettings` TO `glpi_notificationtargets`;";
        $DB->queryOrDie($query, "0.78 rename table glpi_mailingsettings in glpi_notificationtargets");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                ADD `notifications_id` INT( 11 ) NOT NULL DEFAULT '0',\n                ADD INDEX `notifications_id` (`notifications_id`)";
        $DB->queryOrDie($query, "0.78 add field notifications_id to glpi_notificationtargets");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                CHANGE `type` `oldtype` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci\n                                        NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 change field type in oldtype");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                CHANGE `mailingtype` `type` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 change field mailingtype in type");
        $fields = array('new' => array('itemtype' => 'Ticket', 'newaction' => 'new'), 'update' => array('itemtype' => 'Ticket', 'newaction' => 'update'), 'finish' => array('itemtype' => 'Ticket', 'newaction' => 'closed'), 'resa' => array('itemtype' => 'Reservation', 'newaction' => 'new'), 'followup' => array('itemtype' => 'Ticket', 'newaction' => 'add_followup'), 'alertconsumable' => array('itemtype' => 'Consumable', 'newaction' => 'alert'), 'alertcartridge' => array('itemtype' => 'Cartridge', 'newaction' => 'alert'), 'alertlicense' => array('itemtype' => 'SoftwareLicense', 'newaction' => 'alert'), 'alertinfocom' => array('itemtype' => 'Infocom', 'newaction' => 'alert'), 'alertcontract' => array('itemtype' => 'Contract', 'newaction' => 'end'));
        $query = "SELECT `oldtype`\n                FROM `glpi_notificationtargets`\n                GROUP BY `oldtype`";
        foreach ($DB->request($query) as $data) {
            $infos = $fields[$data['oldtype']];
            $query_type = "SELECT `id`\n                        FROM `glpi_notifications`\n                        WHERE `itemtype`='" . $infos['itemtype'] . "'\n                              AND `event`='" . $infos['newaction'] . "'";
            $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id");
            if ($DB->numrows($result)) {
                $id = $DB->result($result, 0, 'id');
                $query_update = "UPDATE `glpi_notificationtargets`\n                             SET `notifications_id` = '{$id}'\n                             WHERE `oldtype` = '" . $data['oldtype'] . "'";
                $DB->queryOrDie($query_update, "0.78 set notificationtargets_id");
            }
        }
        $query = "ALTER TABLE `glpi_notificationtargets`\n               DROP INDEX `unicity` ";
        $DB->queryOrDie($query, "0.78 drop index unicity from glpi_notificationtargets");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                DROP `oldtype`";
        $DB->queryOrDie($query, "0.78 drop field oldtype in glpi_notificationtargets");
        //Add administrator as target for MySQL Synchronization notification
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'DBConnection'";
        $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id");
        if ($DB->numrows($result)) {
            $id = $DB->result($result, 0, 'id');
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                   VALUES (NULL, " . $id . ", 1, 1)";
            $DB->queryOrDie($query, "0.78 add target for dbsynchronization");
        }
        //Add validator as target for Ticket Validation
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Ticket'\n                           AND `event` = 'validation'";
        $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id");
        if ($DB->numrows($result)) {
            $id = $DB->result($result, 0, 'id');
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                     VALUES (NULL, " . $id . ", 1, 14);";
            $DB->queryOrDie($query, "0.78 add target for Ticket Validation");
        }
        //Manage Reservation update & delete
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Reservation'\n                           AND `event` IN ('update', 'delete')";
        foreach ($DB->request($query_type) as $data_resa) {
            $query_targets = "SELECT `glpi_notificationtargets` . *\n                          FROM `glpi_notifications` ,\n                               `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Reservation'\n                               AND `glpi_notifications`.`event` = 'new'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_resa['id'] . ", " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ");";
                $DB->queryOrDie($query_insert, "0.78 add target for reservations");
            }
        }
        //Manage contract notice
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Contract'\n                           AND `event` = 'notice'";
        foreach ($DB->request($query_type) as $data_contract) {
            $query_targets = "SELECT `glpi_notificationtargets`.*\n                          FROM `glpi_notifications` , `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Contract'\n                               AND `glpi_notifications`.`event` = 'end'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_contract['id'] . ", " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ")";
                $DB->queryOrDie($query_insert, "0.78 add target for contract");
            }
        }
        //Manage ticket tasks & followups
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype`='Ticket'\n                           AND `event` IN ('add_task', 'update_task', 'update_followup',\n                                           'delete_task', 'delete_followup')";
        foreach ($DB->request($query_type) as $data_ticket) {
            $query_targets = "SELECT `glpi_notificationtargets`.*\n                          FROM `glpi_notifications` ,\n                               `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                               AND `glpi_notifications`.`event` = 'add_followup'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_ticket['id'] . ",  " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ");";
                $DB->queryOrDie($query_insert, "0.78 add target for tickets");
            }
        }
        //Manage ticket solved
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Ticket'\n                           AND `event` = 'solved'";
        foreach ($DB->request($query_type) as $data_ticket) {
            $query_targets = "SELECT `glpi_notificationtargets`.*\n                          FROM `glpi_notifications` ,\n                               `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                               AND `glpi_notifications`.`event` = 'closed'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_ticket['id'] . ", " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ")";
                $DB->queryOrDie($query_insert, "0.78 add target for tickets action solved");
            }
        }
    }
    if (!FieldExists('glpi_profiles', 'notification', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `notification` CHAR( 1 ) NULL";
        $DB->queryOrDie($query, "0.78 add notification in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `notification` = 'w'\n                WHERE `config` ='w'";
        $DB->queryOrDie($query, "0.78 add notification write right user which have config right");
    }
    if (!FieldExists('glpi_entitydatas', 'mailing_signature', false)) {
        $query = "ALTER TABLE `glpi_entitydatas` ADD `mailing_signature` TEXT DEFAULT NULL ,\n                ADD `cartridges_alert_repeat` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `consumables_alert_repeat` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `use_licenses_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n                ADD `use_contracts_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n                ADD `use_infocoms_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n                ADD `use_reservations_alert` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `autoclose_delay` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `notclosed_delay` INT( 11 ) NOT NULL DEFAULT '-1'";
        $DB->queryOrDie($query, "0.78 add notifications fields in glpi_entitydatas");
    }
    if (!FieldExists('glpi_configs', 'use_reservations_alert', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `use_infocoms_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD `use_contracts_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD `use_reservations_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD `autoclose_delay` INT( 11 ) NOT NULL DEFAULT '0',\n                ADD `notclosed_delay` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add notifications fields in glpi_configs");
    }
    if (TableExists('glpi_mailingsettings')) {
        $query = "DROP TABLE `glpi_mailingsettings`;";
        $DB->queryOrDie($query, "0.78 drop table glpi_mailingsettings");
    }
    $tables = array('glpi_infocoms' => __('Financial and administrative information'), 'glpi_reservationitems' => _n('Reservation', 'Reservations', 2), 'glpi_networkports' => _n('Network port', 'Network ports', 2));
    foreach ($tables as $table => $label) {
        // Migrate infocoms entity information
        if (!FieldExists($table, 'entities_id', false)) {
            $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $label));
            $query = "ALTER TABLE `{$table}`\n                   ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `itemtype`,\n                   ADD `is_recursive` tinyint(1) NOT NULL DEFAULT 0 AFTER `entities_id`,\n                   ADD INDEX `entities_id` ( `entities_id` ),\n                   ADD INDEX `is_recursive` (`is_recursive`)";
            $DB->queryOrDie($query, "0.78 add entities_id and is_recursive in {$table}");
            $entities = getAllDatasFromTable('glpi_entities');
            $entities[0] = "Root";
            $query = "SELECT DISTINCT `itemtype`\n                   FROM `{$table}`";
            if ($result = $DB->query($query)) {
                if ($DB->numrows($result) > 0) {
                    while ($data = $DB->fetch_assoc($result)) {
                        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), sprintf(__('%1$s - %2$s'), $label, $data['itemtype'])));
                        $itemtable = getTableForItemType($data['itemtype']);
                        // ajout d'un contrôle pour voir si la table existe ( cas migration plugin non fait)
                        if (!TableExists($itemtable)) {
                            $migration->displayWarning("*** Skip : no table {$itemtable} ***", true);
                            continue;
                        }
                        $do_recursive = false;
                        if (FieldExists($itemtable, 'is_recursive', false)) {
                            $do_recursive = true;
                        }
                        // This is duplicated in Plugin::migrateItemType() for plugin object
                        foreach ($entities as $entID => $val) {
                            if ($do_recursive) {
                                // Non recursive ones
                                $query3 = "UPDATE `{$table}`\n                                   SET `entities_id` = {$entID},\n                                       `is_recursive` = 0\n                                   WHERE `itemtype` = '" . $data['itemtype'] . "'\n                                         AND `items_id` IN (SELECT `id`\n                                                            FROM `{$itemtable}`\n                                                            WHERE `entities_id` = {$entID}\n                                                                  AND `is_recursive` = 0)";
                                $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=0 in {$table} for " . $data['itemtype']);
                                // Recursive ones
                                $query3 = "UPDATE `{$table}`\n                                   SET `entities_id` = {$entID},\n                                       `is_recursive` = 1\n                                   WHERE `itemtype` = '" . $data['itemtype'] . "'\n                                         AND `items_id` IN (SELECT `id`\n                                                            FROM `{$itemtable}`\n                                                            WHERE `entities_id` = {$entID}\n                                                                  AND `is_recursive` = 1)";
                                $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=1 in {$table} for " . $data['itemtype']);
                            } else {
                                $query3 = "UPDATE `{$table}`\n                                   SET `entities_id` = {$entID}\n                                   WHERE `itemtype` = '" . $data['itemtype'] . "'\n                                         AND `items_id` IN (SELECT `id`\n                                                            FROM `{$itemtable}`\n                                                            WHERE `entities_id` = {$entID})";
                                $DB->queryOrDie($query3, "0.78 update entities_id in {$table} for " . $data['itemtype']);
                            }
                        }
                    }
                }
            }
        }
    }
    // Migrate consumable and cartridge and computerdisks entity information
    $items = array('glpi_cartridges' => 'glpi_cartridgeitems', 'glpi_consumables' => 'glpi_consumableitems', 'glpi_computerdisks' => 'glpi_computers');
    foreach ($items as $linkitem => $sourceitem) {
        if (!FieldExists($linkitem, 'entities_id', false)) {
            $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $linkitem));
            $query = "ALTER TABLE `{$linkitem}`\n                   ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `id`,\n                   ADD INDEX `entities_id` ( `entities_id` )";
            $DB->queryOrDie($query, "0.78 add entities_id in {$linkitem}");
            $entities = getAllDatasFromTable('glpi_entities');
            $entities[0] = "Root";
            foreach ($entities as $entID => $val) {
                $query3 = "UPDATE `{$linkitem}`\n                       SET `entities_id` = '{$entID}'\n                       WHERE " . getForeignKeyFieldForTable($sourceitem) . "\n                              IN (SELECT `id`\n                                  FROM `{$sourceitem}`\n                                  WHERE `entities_id` = '{$entID}' )";
                $DB->queryOrDie($query3, "0.78 update entities_id in {$linkitem}");
            }
        }
    }
    // Migrate softwareversions entity information
    if (!FieldExists('glpi_softwareversions', 'entities_id', false)) {
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_softwareversions'));
        $query = "ALTER TABLE `glpi_softwareversions`\n                ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `id`,\n                ADD INDEX `entities_id` ( `entities_id` ),\n                ADD `is_recursive` tinyint(1) NOT NULL DEFAULT 0 AFTER `entities_id`,\n                ADD INDEX `is_recursive` ( `is_recursive` )";
        $DB->queryOrDie($query, "0.78 add entities_id in glpi_softwareversion");
        $entities = getAllDatasFromTable('glpi_entities');
        $entities[0] = "Root";
        foreach ($entities as $entID => $val) {
            // Non recursive ones
            $query3 = "UPDATE `glpi_softwareversions`\n                    SET `entities_id` = {$entID},\n                        `is_recursive` = 0\n                    WHERE `softwares_id` IN (SELECT `id`\n                                             FROM `glpi_softwares`\n                                             WHERE `entities_id` = {$entID}\n                                                   AND `is_recursive` = 0)";
            $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=0 in glpi_softwareversions");
            // Recursive ones
            $query3 = "UPDATE `glpi_softwareversions`\n                    SET `entities_id` = {$entID},\n                        `is_recursive` = 1\n                    WHERE `softwares_id` IN (SELECT `id`\n                                             FROM `glpi_softwares`\n                                             WHERE `entities_id` = {$entID}\n                                                   AND `is_recursive` = 1)";
            $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=1 in glpi_softwareversions");
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_mailcollectors'));
    if (!FieldExists("glpi_mailcollectors", "is_active", false)) {
        $query = "ALTER TABLE `glpi_mailcollectors`\n                ADD `is_active` tinyint( 1 ) NOT NULL DEFAULT '1',\n                ADD INDEX `is_active` (`is_active`) ";
        $DB->queryOrDie($query, "0.78 add is_active in glpi_mailcollectors");
    }
    if (!FieldExists('glpi_mailcollectors', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_mailcollectors`\n                ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_mailcollectors");
    }
    if (!FieldExists('glpi_mailcollectors', 'comment', false)) {
        $query = "ALTER TABLE `glpi_mailcollectors`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_mailcollectors");
    }
    if (!FieldExists('glpi_profiles', 'rule_mailcollector', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `rule_mailcollector` CHAR( 1 ) NULL ";
        $DB->queryOrDie($query, "0.78 add rule_mailcollector to glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_mailcollector` = `rule_ticket`";
        $DB->queryOrDie($query, "0.78 set default rule_mailcollector same as rule_ticket");
    }
    // Change search pref : add active / date_mod
    $ADDTODISPLAYPREF['MailCollector'] = array(2, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_authldaps'));
    if (!FieldExists('glpi_authldaps', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_authldaps");
    }
    if (!FieldExists('glpi_authldaps', 'comment', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_authldaps");
    }
    // Change search pref : host, date_mod
    $ADDTODISPLAYPREF['AuthLDAP'] = array(3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_authldaps'));
    if (!FieldExists('glpi_authmails', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_authmails`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_authmails");
    }
    if (!FieldExists('glpi_authmails', 'comment', false)) {
        $query = "ALTER TABLE `glpi_authmails`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_authmails");
    }
    // Change search pref : host, date_mod
    $ADDTODISPLAYPREF['AuthMail'] = array(3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_ocsservers'));
    if (!FieldExists('glpi_ocsservers', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_ocsservers`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_ocsservers");
    }
    if (!FieldExists('glpi_ocsservers', 'comment', false)) {
        $query = "ALTER TABLE `glpi_ocsservers`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_ocsservers");
    }
    // Change search pref : date_mod / host
    $ADDTODISPLAYPREF['OcsServer'] = array(3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_profiles'));
    if (!FieldExists('glpi_profiles', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'comment', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_profiles");
    }
    // Change search pref : date_mod / host
    $ADDTODISPLAYPREF['Profile'] = array(2, 3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_printers'));
    if (!FieldExists('glpi_printers', 'have_ethernet', false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `have_ethernet` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `have_usb`";
        $DB->queryOrDie($query, "0.78 add have_ethernet to glpi_printers");
    }
    if (!FieldExists('glpi_printers', 'have_wifi', false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `have_wifi` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `have_usb`";
        $DB->queryOrDie($query, "0.78 add have_wifi to glpi_printers");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_profiles'));
    if (!FieldExists('glpi_transfers', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_transfers`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_transfers");
    }
    if (!FieldExists('glpi_transfers', 'comment', false)) {
        $query = "ALTER TABLE `glpi_transfers`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_transfers");
    }
    // Change search pref : date_mod
    $ADDTODISPLAYPREF['Transfer'] = array(19);
    // Convert events
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_events'));
    $convert_types = array('tracking' => 'ticket', 'networking' => 'networkequipment', 'knowbase' => 'knowbaseitem', 'typedocs' => 'documenttype', 'mailgate' => 'mailcollector');
    foreach ($convert_types as $from => $to) {
        $query2 = "UPDATE `glpi_events`\n                 SET `type` = '{$to}'\n                WHERE `type` = '{$from}'";
        $DB->queryOrDie($query2, "0.78 update events data");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticket bookmarks'));
    $query = "SELECT *\n             FROM `glpi_bookmarks`\n             WHERE `itemtype` = 'Ticket'\n                   AND `type` = '" . Bookmark::SEARCH . "'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                $newoptions = array();
                foreach ($options as $key => $val) {
                    switch ($key) {
                        case "status":
                            $newoptions['field'][$num] = 12;
                            $newoptions['searchtype'][$num] = 'equals';
                            $newoptions['link'][$num] = 'AND';
                            if ($val == 'old_done' || $val == 'old_notdone') {
                                $newoptions['contains'][$num] = 'closed';
                            } else {
                                $newoptions['contains'][$num] = $val;
                            }
                            $num++;
                            break;
                        case "priority":
                            if ($val != 0) {
                                $newoptions['field'][$num] = 3;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "category":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 7;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "request_type":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 9;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "type":
                            if ($val > 0 && isset($data['item']) && $data['item'] > 0) {
                                $newoptions['itemtype2'][$num2] = $typetoname[$val];
                                $newoptions['field2'][$num2] = 1;
                                $newoptions['searchtype2'][$num2] = 'equals';
                                $newoptions['contains2'][$num2] = $data['item'];
                                $newoptions['link2'][$num2] = 'AND';
                                $num2++;
                            }
                            break;
                        case "author":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 4;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "group":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 71;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "assign":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 5;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "assign_group":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 8;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "assign_ent":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 6;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "recipient":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 22;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "date1":
                            // begin from
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 15;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&gt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "date2":
                            // begin to
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 15;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&lt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "enddate1":
                            // end from
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 16;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&gt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "enddate2":
                            // end to
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 16;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&lt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "datemod1":
                            // mod from
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 19;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&gt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "datemod2":
                            // mod to
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 19;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&lt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "tosearch":
                            if (isset($data['search'])) {
                                $search = trim($data['search']);
                                if (strlen($search) > 0) {
                                    $first = false;
                                    if (strstr($data['search'], 'name')) {
                                        $newoptions['field'][$num] = 1;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = $first ? 'AND' : 'OR';
                                        $first = false;
                                        $num++;
                                    }
                                    if (strstr($data['search'], 'contents')) {
                                        $newoptions['field'][$num] = 21;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = $first ? 'AND' : 'OR';
                                        $first = false;
                                        $num++;
                                    }
                                    if (strstr($data['search'], 'followup')) {
                                        $newoptions['field'][$num] = 25;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = $first ? 'AND' : 'OR';
                                        $first = false;
                                        $num++;
                                    }
                                    if (strstr($data['search'], 'ID')) {
                                        $newoptions['field'][$num] = 2;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = 'AND';
                                        $first = false;
                                        $num++;
                                    }
                                }
                            }
                            break;
                    }
                }
                if ($num > 0 || $num2 > 0) {
                    $newoptions['glpisearchcount'] = $num;
                    $newoptions['glpisearchcount2'] = $num2;
                    $newoptions['itemtype'] = 'Ticket';
                    $query2 = "UPDATE `glpi_bookmarks`\n                          SET `query` = '" . addslashes(Toolbox::append_params($newoptions)) . "'\n                          WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query2, "0.78 update ticket bookmarks");
                } else {
                    $query2 = "DELETE\n                          FROM `glpi_bookmarks`\n                          WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query2, "0.78 delete ticket bookmarks : cannot convert");
                }
                // Lost paramaters
                //only_computers=1&contains=dddd&field=moboard.designation&
            }
        }
    }
    if (!TableExists('glpi_ticketvalidations')) {
        $query = "CREATE TABLE `glpi_ticketvalidations` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `entities_id` int(11) NOT NULL default '0',\n                  `users_id` int(11) NOT NULL default '0',\n                  `tickets_id` int(11) NOT NULL default '0',\n                  `users_id_validate` int(11) NOT NULL default '0',\n                  `comment_submission` text collate utf8_unicode_ci,\n                  `comment_validation` text collate utf8_unicode_ci,\n                  `status` varchar(255) collate utf8_unicode_ci default 'waiting',\n                  `submission_date` datetime default NULL,\n                  `validation_date` datetime default NULL,\n                  PRIMARY KEY  (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `users_id_validate` (`users_id_validate`),\n                  KEY `tickets_id` (`tickets_id`),\n                  KEY `submission_date` (`submission_date`),\n                  KEY `validation_date` (`validation_date`),\n                  KEY `status` (`status`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_ticketvalidations");
        $ADDTODISPLAYPREF['TicketValidation'] = array(3, 2, 8, 4, 9, 7);
    }
    if (!FieldExists('glpi_tickets', 'global_validation', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `global_validation` varchar(255) collate utf8_unicode_ci default 'accepted',\n                ADD INDEX `global_validation` (`global_validation`)";
        $DB->queryOrDie($query, "0.78 add global_validation to glpi_tickets");
    }
    if (!FieldExists('glpi_profiles', 'validate_ticket', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `validate_ticket` char(1) collate utf8_unicode_ci default NULL";
        $DB->queryOrDie($query, "0.78 add validate_ticket to glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `validate_ticket` = '1'\n                WHERE `interface` = 'central' ";
        $DB->queryOrDie($query, "0.78 add validate_ticket write right to super-admin and admin profiles");
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `create_validation` char(1) collate utf8_unicode_ci default NULL";
        $DB->queryOrDie($query, "0.78 add create_validation to glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `create_validation` = `own_ticket`";
        $DB->queryOrDie($query, "0.78 add create_validation right if can own ticket");
    }
    if (FieldExists('glpi_mailcollectors', 'entities_id', false)) {
        $ranking = 1;
        // No mailcollector : set a default rule
        if (countElementsInTable('glpi_mailcollectors') == 0) {
            $query = "INSERT INTO `glpi_rules`\n                      VALUES (NULL, -1, 'RuleMailCollector', {$ranking}, 'Root', '', 'OR', 1, NULL,\n                              NULL)";
            $DB->queryOrDie($query, "0.78 error inserting new default maigate rule");
            if ($newID = $DB->insert_id()) {
                $query = "INSERT INTO `glpi_rulecriterias`\n                         VALUES (NULL, {$newID}, 'subject', 6, '/.*/')";
                $DB->queryOrDie($query, "0.78 error getting new criteria for rule");
                $query = "INSERT INTO `glpi_ruleactions`\n                         VALUES (NULL, {$newID}, 'assign', 'entities_id', '0')";
                $DB->queryOrDie($query, "0.78 error getting new action for rule");
            }
        } else {
            foreach (getAllDatasFromTable('glpi_mailcollectors') as $collector) {
                $query = "INSERT INTO `glpi_rules`\n                      VALUES (NULL, -1, 'RuleMailCollector', {$ranking}, '" . $collector['name'] . "', '',\n                              'AND', 1, NULL, NULL)";
                $DB->queryOrDie($query, "0.78 error inserting new maigate rule " . $collector['name']);
                if ($newID = $DB->insert_id()) {
                    $query = "INSERT INTO `glpi_rulecriterias`\n                         VALUES (NULL, {$newID}, 'mailcollector', 0, '" . $collector['id'] . "')";
                    $DB->queryOrDie($query, "0.78 error getting new criteria for rule " . $collector['name']);
                    $query = "INSERT INTO `glpi_ruleactions`\n                         VALUES (NULL, {$newID}, 'assign', 'entities_id',\n                                 '" . $collector['entities_id'] . "')";
                    $DB->queryOrDie($query, "0.78 error getting new action for rule " . $collector['name']);
                }
                $ranking++;
            }
        }
        $query = "ALTER TABLE `glpi_mailcollectors`\n                DROP INDEX `entities_id` ";
        $DB->queryOrDie($query, "0.78 drop index entities_id from glpi_mailcollectors");
        $query = "ALTER TABLE `glpi_mailcollectors`\n                DROP `entities_id` ";
        $DB->queryOrDie($query, "0.78 drop entities_id from glpi_mailcollectors");
        $query = "DELETE\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = 'MailCollector'\n                      AND `num` = '80'";
        $DB->queryOrDie($query, "0.78 drop entities_id from collectors display preferences");
    }
    if (!TableExists('glpi_notimportedemails')) {
        $query = "CREATE TABLE `glpi_notimportedemails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `from` varchar(255) NOT NULL,\n                  `to` varchar(255) NOT NULL,\n                  `mailcollectors_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime NOT NULL,\n                  `subject` text,\n                  `messageid` varchar(255) NOT NULL,\n                  `reason` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `mailcollectors_id` (`mailcollectors_id`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;";
        $DB->queryOrDie($query, "0.78 add table glpi_notimportedemails");
        $ADDTODISPLAYPREF['NotImportedEmail'] = array(2, 5, 4, 6, 16, 19);
    }
    if (!FieldExists("glpi_profiles", "entity_rule_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `entity_rule_ticket` CHAR( 1 ) NULL AFTER `rule_ticket`";
        $DB->queryOrDie($query, "0.78 add entity_rule_ldap in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `entity_rule_ticket` = `rule_ticket`";
        $DB->queryOrDie($query, "0.78 update default entity_rule_ticket rights");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_ticket` = 'r'\n                WHERE `rule_ticket` = 'w'";
        $DB->queryOrDie($query, "0.78 update rule_ticket rights");
    }
    if (!FieldExists('glpi_authldaps', 'is_default', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `is_default` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD INDEX `is_default` (`is_default`)";
        $DB->queryOrDie($query, "0.78 add is_default to glpi_authldaps");
        $query = "SELECT COUNT(*) AS cpt\n                FROM `glpi_authldaps`";
        $result = $DB->query($query);
        $number_servers = $DB->result($result, 0, 'cpt');
        if ($number_servers >= 1) {
            //If only one server defined
            if ($number_servers == 1) {
                $query = "SELECT `id`\n                       FROM `glpi_authldaps`";
                $result = $DB->query($query);
                $ldapservers_id = $DB->result($result, 0, 'id');
            } else {
                $query = "SELECT `auths_id`, COUNT(`auths_id`) AS cpt\n                      FROM `glpi_users`\n                      WHERE `authtype` = '3'\n                      GROUP BY `auths_id`\n                      ORDER BY `cpt` DESC";
                $result = $DB->query($query);
                $ldapservers_id = $DB->result($result, 0, 'auths_id');
            }
            $query = "UPDATE `glpi_authldaps`\n                   SET `is_default` = '1'\n                   WHERE `id` = '" . $ldapservers_id . "'";
            $DB->queryOrDie($query, "0.78 set default directory");
        }
    }
    if (TableExists('glpi_rulerightparameters')) {
        $query = "ALTER TABLE `glpi_rulerightparameters`\n                ADD `comment` TEXT NOT NULL ";
        $DB->queryOrDie($query, "0.78 add comment to glpi_rulerightparameters");
        $ADDTODISPLAYPREF['RuleRightParameter'] = array(11);
    }
    if (!FieldExists('glpi_rules', 'is_recursive', false)) {
        $query = "ALTER TABLE `glpi_rules`\n                ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add is_recursive to glpi_rules");
        $query = "UPDATE `glpi_rules`\n                SET `entities_id` = '0'\n                WHERE `entities_id` = '-1'";
        $DB->queryOrDie($query, "0.78 set entities_id to 0 where value is -1 in glpi_rules");
        $query = "UPDATE `glpi_rules`\n                SET `is_recursive`='1'\n                WHERE `sub_type` = 'RuleTicket'";
        $DB->queryOrDie($query, "0.78 set is_recursive to 1 for RuleTicket in glpi_rules");
    }
    if (!FieldExists('glpi_configs', 'user_deleted_ldap', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `user_deleted_ldap` TINYINT( 1 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add user_deleted_ldap to glpi_configs");
    }
    if (!FieldExists("glpi_profiles", "group_add_followup", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `group_add_followups` CHAR(1) NULL AFTER `add_followups`";
        $DB->queryOrDie($query, "0.78 add budget in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `group_add_followups`=`global_add_followups`";
        $DB->queryOrDie($query, "0.78 update default budget rights");
    }
    if (!FieldExists("glpi_groups_users", "is_dynamic", false)) {
        $query = "ALTER TABLE `glpi_groups_users`\n               ADD `is_dynamic` TINYINT( 1 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add is_dynamic in glpi_groups_users");
        //If group comes from an LDAP directory, then update users belonging to it
        //by setting is_dynamic to 1
        $query = "UPDATE `glpi_groups_users` SET `is_dynamic`='1'\n               WHERE groups_id IN (SELECT `id`\n                                   FROM `glpi_groups`\n                                   WHERE (`ldap_group_dn` IS NOT NULL AND `ldap_group_dn` <> '')\n                                          OR ((`ldap_field` IS NOT NULL AND `ldap_field` <> '')\n                                              AND (`ldap_value` IS NOT NULL AND `ldap_value` <> '')))";
        $DB->queryOrDie($query, "0.78 update is_dynamic in glpi_groups_users");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Add search values for tickets
    $ADDTODISPLAYPREF['Ticket'] = array(12, 19, 15, 3, 4, 5, 7);
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT max(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // must always be at the end (only for end message)
    $migration->executeMigration();
    return $updateresult;
}
Esempio n. 21
0
 /**
  * Print the HTML array for Items linked to current contract
  *
  * @since version 0.84
  *
  * @param $contract   Contract object
  *
  * @return Nothing (display)
  **/
 static function showForContract(Contract $contract)
 {
     global $DB, $CFG_GLPI;
     $instID = $contract->fields['id'];
     if (!$contract->can($instID, READ)) {
         return false;
     }
     $canedit = $contract->can($instID, UPDATE);
     $rand = mt_rand();
     $query = "SELECT DISTINCT `itemtype`\n                FROM `glpi_contracts_items`\n                WHERE `glpi_contracts_items`.`contracts_id` = '{$instID}'\n                ORDER BY `itemtype`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     $data = array();
     $totalnb = 0;
     $used = array();
     for ($i = 0; $i < $number; $i++) {
         $itemtype = $DB->result($result, $i, "itemtype");
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         if ($item->canView()) {
             $itemtable = getTableForItemType($itemtype);
             $query = "SELECT `{$itemtable}`.*,\n                                 `glpi_contracts_items`.`id` AS IDD,\n                                 `glpi_entities`.`id` AS entity\n                          FROM `glpi_contracts_items`,\n                               `{$itemtable}`";
             if ($itemtype != 'Entity') {
                 $query .= " LEFT JOIN `glpi_entities`\n                                 ON (`{$itemtable}`.`entities_id`=`glpi_entities`.`id`) ";
             }
             $query .= " WHERE `{$itemtable}`.`id` = `glpi_contracts_items`.`items_id`\n                              AND `glpi_contracts_items`.`itemtype` = '{$itemtype}'\n                              AND `glpi_contracts_items`.`contracts_id` = '{$instID}'";
             if ($item->maybeTemplate()) {
                 $query .= " AND `{$itemtable}`.`is_template` = '0'";
             }
             $query .= getEntitiesRestrictRequest(" AND", $itemtable, '', '', $item->maybeRecursive()) . "\n                      ORDER BY `glpi_entities`.`completename`, `{$itemtable}`.`name`";
             $result_linked = $DB->query($query);
             $nb = $DB->numrows($result_linked);
             if ($nb > $_SESSION['glpilist_limit']) {
                 $opt = array('order' => 'ASC', 'is_deleted' => 0, 'reset' => 'reset', 'start' => 0, 'sort' => 80, 'criteria' => array(0 => array('value' => '$$$$' . $instID, 'searchtype' => 'contains', 'field' => 29)));
                 $url = $item::getSearchURL();
                 $url .= strpos($url, '?') ? '&' : '?';
                 $url .= Toolbox::append_params($opt);
                 $link = "<a href='{$url}'>" . __('Device list') . "</a>";
                 $data[$itemtype] = array('longlist' => true, 'name' => sprintf(__('%1$s: %2$s'), $item->getTypeName($nb), $nb), 'link' => $link);
             } else {
                 if ($nb > 0) {
                     $data[$itemtype] = array();
                     while ($objdata = $DB->fetch_assoc($result_linked)) {
                         $data[$itemtype][$objdata['id']] = $objdata;
                         $used[$itemtype][$objdata['id']] = $objdata['id'];
                     }
                 }
             }
             $totalnb += $nb;
         }
     }
     if ($canedit && ($contract->fields['max_links_allowed'] == 0 || $contract->fields['max_links_allowed'] > $totalnb)) {
         echo "<div class='firstbloc'>";
         echo "<form name='contract_form{$rand}' id='contract_form{$rand}' method='post'\n                action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='2'>" . __('Add an item') . "</th></tr>";
         echo "<tr class='tab_bg_1'><td class='right'>";
         Dropdown::showSelectItemFromItemtypes(array('itemtypes' => $CFG_GLPI["contract_types"], 'entity_restrict' => $contract->fields['is_recursive'] ? getSonsOf('glpi_entities', $contract->fields['entities_id']) : $contract->fields['entities_id'], 'checkright' => true, 'used' => $used));
         echo "</td><td class='center'>";
         echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         echo "<input type='hidden' name='contracts_id' value='{$instID}'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
         echo "</div>";
     }
     echo "<div class='spaced'>";
     if ($canedit && $totalnb) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('container' => 'mass' . __CLASS__ . $rand);
         Html::showMassiveActions($massiveactionparams);
     }
     echo "<table class='tab_cadre_fixehov'>";
     $header_begin = "<tr>";
     $header_top = '';
     $header_bottom = '';
     $header_end = '';
     if ($canedit && $totalnb) {
         $header_top .= "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_top .= "</th>";
         $header_bottom .= "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_bottom .= "</th>";
     }
     $header_end .= "<th>" . __('Type') . "</th>";
     $header_end .= "<th>" . __('Entity') . "</th>";
     $header_end .= "<th>" . __('Name') . "</th>";
     $header_end .= "<th>" . __('Serial number') . "</th>";
     $header_end .= "<th>" . __('Inventory number') . "</th>";
     $header_end .= "<th>" . __('Status') . "</th>";
     $header_end .= "</tr>";
     echo $header_begin . $header_top . $header_end;
     $totalnb = 0;
     foreach ($data as $itemtype => $datas) {
         if (isset($datas['longlist'])) {
             echo "<tr class='tab_bg_1'>";
             if ($canedit) {
                 echo "<td>&nbsp;</td>";
             }
             echo "<td class='center'>" . $datas['name'] . "</td>";
             echo "<td class='center' colspan='2'>" . $datas['link'] . "</td>";
             echo "<td class='center'>-</td><td class='center'>-</td></tr>";
         } else {
             $prem = true;
             $nb = count($datas);
             foreach ($datas as $id => $objdata) {
                 $name = $objdata["name"];
                 if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) {
                     $name = sprintf(__('%1$s (%2$s)'), $name, $objdata["id"]);
                 }
                 $link = $itemtype::getFormURLWithID($objdata["id"]);
                 $name = "<a href=\"" . $link . "\">" . $name . "</a>";
                 echo "<tr class='tab_bg_1'>";
                 if ($canedit) {
                     echo "<td width='10'>";
                     Html::showMassiveActionCheckBox(__CLASS__, $objdata["IDD"]);
                     echo "</td>";
                 }
                 if ($prem) {
                     $item = new $itemtype();
                     $typename = $item->getTypeName($nb);
                     echo "<td class='center top' rowspan='{$nb}'>" . ($nb > 1 ? sprintf(__('%1$s: %2$s'), $typename, $nb) : $typename) . "</td>";
                     $prem = false;
                 }
                 echo "<td class='center'>";
                 echo Dropdown::getDropdownName("glpi_entities", $objdata['entity']) . "</td>";
                 echo "<td class='center" . (isset($objdata['is_deleted']) && $objdata['is_deleted'] ? " tab_bg_2_2'" : "'");
                 echo ">" . $name . "</td>";
                 echo "<td class='center'>" . (isset($objdata["serial"]) ? "" . $objdata["serial"] . "" : "-") . "</td>";
                 echo "<td class='center'>" . (isset($objdata["otherserial"]) ? "" . $objdata["otherserial"] . "" : "-") . "</td>";
                 echo "<td class='center'>";
                 if (isset($objdata["states_id"])) {
                     echo Dropdown::getDropdownName("glpi_states", $objdata['states_id']);
                 } else {
                     echo '&nbsp;';
                 }
                 echo "</td></tr>";
             }
         }
     }
     if ($number) {
         echo $header_begin . $header_bottom . $header_end;
     }
     echo "</table>";
     if ($canedit && $number) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
         Html::closeForm();
     }
     echo "</div>";
 }
Esempio n. 22
0
 /**
  * Show tabs
  *
  * @param $options array of parameters to add to URLs and ajax
  *     - withtemplate is a template view ?
  *
  * @return Nothing ()
  **/
 function showNavigationHeader($options = array())
 {
     global $CFG_GLPI;
     // for objects not in table like central
     if (isset($this->fields['id'])) {
         $ID = $this->fields['id'];
     } else {
         if (isset($options['id'])) {
             $ID = $options['id'];
         } else {
             $ID = 0;
         }
     }
     $target = $_SERVER['PHP_SELF'];
     $extraparamhtml = "";
     $extraparam = "";
     $withtemplate = "";
     if (is_array($options) && count($options)) {
         $cleanoptions = $options;
         if (isset($options['withtemplate'])) {
             $withtemplate = $options['withtemplate'];
             unset($cleanoptions['withtemplate']);
         }
         foreach ($cleanoptions as $key => $val) {
             // Do not include id options
             if ($key[0] == '_' || $key == 'id') {
                 unset($cleanoptions[$key]);
             }
         }
         $extraparamhtml = "&amp;" . Toolbox::append_params($cleanoptions, '&amp;');
         $extraparam = "&" . Toolbox::append_params($cleanoptions);
     }
     if (empty($withtemplate) && !$this->isNewID($ID) && $this->getType() && $this->displaylist) {
         $glpilistitems =& $_SESSION['glpilistitems'][$this->getType()];
         $glpilisttitle =& $_SESSION['glpilisttitle'][$this->getType()];
         $glpilisturl =& $_SESSION['glpilisturl'][$this->getType()];
         if (empty($glpilisturl)) {
             $glpilisturl = $this->getSearchURL();
         }
         //          echo "<div id='menu_navigate'>";
         $next = $prev = $first = $last = -1;
         $current = false;
         if (is_array($glpilistitems)) {
             $current = array_search($ID, $glpilistitems);
             if ($current !== false) {
                 if (isset($glpilistitems[$current + 1])) {
                     $next = $glpilistitems[$current + 1];
                 }
                 if (isset($glpilistitems[$current - 1])) {
                     $prev = $glpilistitems[$current - 1];
                 }
                 $first = $glpilistitems[0];
                 if ($first == $ID) {
                     $first = -1;
                 }
                 $last = $glpilistitems[count($glpilistitems) - 1];
                 if ($last == $ID) {
                     $last = -1;
                 }
             }
         }
         $cleantarget = HTML::cleanParametersURL($target);
         echo "<div class='navigationheader'><table class='tab_cadre_pager'>";
         echo "<tr class='tab_bg_2'>";
         if ($first >= 0) {
             echo "<td class='left' width='16px'><a href='{$cleantarget}?id={$first}{$extraparamhtml}'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/first.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\" class='pointer'></a></td>";
         } else {
             echo "<td class='left' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/first_off.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\"></td>";
         }
         if ($prev >= 0) {
             echo "<td class='left' width='16px'><a href='{$cleantarget}?id={$prev}{$extraparamhtml}' id='previouspage'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/left.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\" class='pointer'></a></td>";
             $js = '$("body").keydown(function(e) {
                    if ($("input, textarea").is(":focus") === false) {
                       if(e.keyCode == 37 && e.ctrlKey) {
                         window.location = $("#previouspage").attr("href");
                       }
                    }
               });';
             echo Html::scriptBlock($js);
         } else {
             echo "<td class='left' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/left_off.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\"></td>";
         }
         echo "<td width='200px'><a href=\"" . $glpilisturl . "\">";
         if ($glpilisttitle) {
             echo $glpilisttitle;
         } else {
             _e('List');
         }
         echo "</a></td>";
         $name = $this->getTypeName(1);
         if (isset($this->fields['id']) && $this instanceof CommonDBTM) {
             $name = sprintf(__('%1$s - %2$s'), $name, sprintf(__('%1$s - ID %2$d'), $this->getName(), $this->fields['id']));
         }
         if (isset($this->fields["entities_id"]) && Session::isMultiEntitiesMode() && $this->isEntityAssign()) {
             $entname = Dropdown::getDropdownName("glpi_entities", $this->fields["entities_id"]);
             if ($this->isRecursive()) {
                 $entname = sprintf(__('%1$s + %2$s'), $entname, __('Child entities'));
             }
             $name = sprintf(__('%1$s (%2$s)'), $name, $entname);
         }
         echo "<td class='b big'>";
         if (!self::isLayoutWithMain() || self::isLayoutExcludedPage()) {
             echo $name;
         }
         echo "</td>";
         if ($current !== false) {
             echo "<td width='40px'>" . ($current + 1) . "/" . count($glpilistitems) . "</td>";
         }
         if ($next >= 0) {
             echo "<td class='right' width='16px'><a href='{$cleantarget}?id={$next}{$extraparamhtml}' id='nextpage'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/right.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\" class='pointer'></a></td>";
             $js = '$("body").keydown(function(e) {
                    if ($("input, textarea").is(":focus") === false) {
                       if(e.keyCode == 39 && e.ctrlKey) {
                         window.location = $("#nextpage").attr("href");
                       }
                    }
               });';
             echo Html::scriptBlock($js);
         } else {
             echo "<td class='right' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/right_off.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\"></td>";
         }
         if ($last >= 0) {
             echo "<td class='right' width='16px'><a href='{$cleantarget}?id={$last}{$extraparamhtml}'>" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/last.png\" alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\" class='pointer'></a></td>";
         } else {
             echo "<td class='right' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/last_off.png' alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\"></td>";
         }
         //          echo "</ul></div>";
         // End pager
         echo "</tr></table></div>";
         //          echo "<div class='sep'></div>";
     }
 }
Esempio n. 23
0
 static function showSummary()
 {
     global $DB, $CFG_GLPI;
     $state_type = $CFG_GLPI["state_types"];
     $states = array();
     foreach ($state_type as $key => $itemtype) {
         if ($item = getItemForItemtype($itemtype)) {
             if (!$item->canView()) {
                 unset($state_type[$key]);
             } else {
                 $table = getTableForItemType($itemtype);
                 $query = "SELECT `states_id`, COUNT(*) AS cpt\n                         FROM `{$table}` " . getEntitiesRestrictRequest("WHERE", $table) . "\n                              AND `is_deleted` = '0'\n                              AND `is_template` = '0'\n                         GROUP BY `states_id`";
                 if ($result = $DB->query($query)) {
                     if ($DB->numrows($result) > 0) {
                         while ($data = $DB->fetch_assoc($result)) {
                             $states[$data["states_id"]][$itemtype] = $data["cpt"];
                         }
                     }
                 }
             }
         }
     }
     if (count($states)) {
         // Produce headline
         echo "<div class='center'><table class='tab_cadrehov'><tr>";
         // Type
         echo "<th>" . __('Status') . "</th>";
         foreach ($state_type as $key => $itemtype) {
             if ($item = getItemForItemtype($itemtype)) {
                 echo "<th>" . $item->getTypeName(Session::getPluralNumber()) . "</th>";
                 $total[$itemtype] = 0;
             } else {
                 unset($state_type[$key]);
             }
         }
         echo "<th>" . __('Total') . "</th>";
         echo "</tr>";
         $query = "SELECT *\n                   FROM `glpi_states` " . getEntitiesRestrictRequest("WHERE", "glpi_states", '', '', true) . "\n                   ORDER BY `completename`";
         $result = $DB->query($query);
         // No state
         $tot = 0;
         echo "<tr class='tab_bg_2'><td>---</td>";
         foreach ($state_type as $itemtype) {
             echo "<td class='numeric'>";
             if (isset($states[0][$itemtype])) {
                 echo $states[0][$itemtype];
                 $total[$itemtype] += $states[0][$itemtype];
                 $tot += $states[0][$itemtype];
             } else {
                 echo "&nbsp;";
             }
             echo "</td>";
         }
         echo "<td class='numeric b'>{$tot}</td></tr>";
         while ($data = $DB->fetch_assoc($result)) {
             $tot = 0;
             echo "<tr class='tab_bg_2'><td class='b'>";
             $opt = array('reset' => 'reset', 'sort' => 1, 'start' => 0, 'criteria' => array('0' => array('value' => '$$$$' . $data['id'], 'searchtype' => 'contains', 'field' => 31)));
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/allassets.php?" . Toolbox::append_params($opt, '&amp;') . "'>" . $data["completename"] . "</a></td>";
             foreach ($state_type as $itemtype) {
                 echo "<td class='numeric'>";
                 if (isset($states[$data["id"]][$itemtype])) {
                     echo $states[$data["id"]][$itemtype];
                     $total[$itemtype] += $states[$data["id"]][$itemtype];
                     $tot += $states[$data["id"]][$itemtype];
                 } else {
                     echo "&nbsp;";
                 }
                 echo "</td>";
             }
             echo "<td class='numeric b'>{$tot}</td>";
             echo "</tr>";
         }
         echo "<tr class='tab_bg_2'><td class='center b'>" . __('Total') . "</td>";
         $tot = 0;
         foreach ($state_type as $itemtype) {
             echo "<td class='numeric b'>" . $total[$itemtype] . "</td>";
             $tot += $total[$itemtype];
         }
         echo "<td class='numeric b'>{$tot}</td></tr>";
         echo "</table></div>";
     } else {
         echo "<div class='center b'>" . __('No item found') . "</div>";
     }
 }
Esempio n. 24
0
/**
 * 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;
}
Esempio n. 25
0
 /**
  * Print a nice HTML head for help page
  *
  * @param $title  title of the page
  * @param $url    not used anymore (default '')
  **/
 static function helpHeader($title, $url = '')
 {
     global $CFG_GLPI, $HEADER_LOADED, $PLUGIN_HOOKS;
     // Print a nice HTML-head for help page
     if ($HEADER_LOADED) {
         return;
     }
     $HEADER_LOADED = true;
     self::includeHeader($title);
     // Body
     echo "<body>";
     // Main Headline
     echo "<div id='header'>";
     echo "<div id='c_logo' >";
     echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/helpdesk.public.php' accesskey='1' title=\"" . __s('Home') . "\"><span class='invisible'>Logo</span></a></div>";
     // Les préférences + lien déconnexion
     echo "<div id='c_preference' >";
     echo "<ul><li id='deconnexion'><a href='" . $CFG_GLPI["root_doc"] . "/logout.php' title=\"" . __s('Logout') . "\">" . __('Logout') . "</a>";
     // check user id : header used for display messages when session logout
     if (Session::getLoginUserID()) {
         echo "&nbsp;(";
         echo formatUserName(0, $_SESSION["glpiname"], $_SESSION["glpirealname"], $_SESSION["glpifirstname"], 0, 20);
         echo ")";
     }
     echo "</li>\n";
     echo "<li><a href='" . (empty($CFG_GLPI["helpdesk_doc_url"]) ? "http://glpi-project.org/help-helpdesk" : $CFG_GLPI["helpdesk_doc_url"]) . "' target='_blank' title=\"" . __s('Help') . "\"> " . __('Help') . "</a></li>";
     echo "<li><a href='" . $CFG_GLPI["root_doc"] . "/front/preference.php' title=\"" . __s('Settings') . "\">" . __('Settings') . "</a></li>\n";
     echo "</ul>";
     echo "<div class='sep'></div>";
     echo "</div>";
     //-- Le moteur de recherche --
     echo "<div id='c_recherche'>";
     echo "<div class='sep'></div>";
     echo "</div>";
     //-- Le menu principal --
     echo "<div id='c_menu'>";
     echo "<ul id='menu'>";
     // Build the navigation-elements
     // Home
     echo "<li id='menu1'>";
     echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/helpdesk.public.php' title=\"" . __s('Home') . "\" class='itemP'>" . __('Home') . "</a>";
     echo "</li>";
     //  Create ticket
     if (Session::haveRight("create_ticket", "1")) {
         echo "<li id='menu2'>";
         echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/helpdesk.public.php?create_ticket=1' " . "title=\"" . __s('Create a ticket') . "\" class='itemP'>" . __('Create a ticket') . "</a>";
         echo "</li>";
     }
     //  Suivi ticket
     if (Session::haveRight("observe_ticket", "1") || Session::haveRight("create_ticket", "1")) {
         echo "<li id='menu3'>";
         echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.php' title=\"" . __s('Ticket followup') . "\" class='itemP'>" . _n('Ticket', 'Tickets', 2) . "</a>";
         echo "</li>";
     }
     // Reservation
     if (Session::haveRight("reservation_helpdesk", "1")) {
         echo "<li id='menu4'>";
         echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.php' title=\"" . _sn('Reservation', 'Reservations', 2) . "\" class='itemP'>" . _n('Reservation', 'Reservations', 2) . "</a>";
         echo "</li>";
     }
     // FAQ
     if (Session::haveRight("faq", "r")) {
         echo "<li id='menu5' >";
         echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/helpdesk.faq.php' title=\"" . __s('FAQ') . "\" class='itemP'>" . __('FAQ') . "</a>";
         echo "</li>";
     }
     // PLUGINS
     $plugins = array();
     if (isset($PLUGIN_HOOKS["helpdesk_menu_entry"]) && count($PLUGIN_HOOKS["helpdesk_menu_entry"])) {
         foreach ($PLUGIN_HOOKS["helpdesk_menu_entry"] as $plugin => $active) {
             if ($active) {
                 $plugins[$plugin] = Plugin::getInfo($plugin);
             }
         }
     }
     if (isset($plugins) && count($plugins) > 0) {
         $list = array();
         foreach ($plugins as $key => $val) {
             $list[$key] = $val["name"];
         }
         asort($list);
         echo "<li id='menu5' onmouseover=\"javascript:menuAff('menu5','menu');\">";
         echo "<a href='#' title=\"" . __s('Plugins') . "\" class='itemP'>" . __('Plugins') . "</a>";
         // default none
         echo "<ul class='ssmenu'>";
         // list menu item
         foreach ($list as $key => $val) {
             $link = "";
             if (is_string($PLUGIN_HOOKS["helpdesk_menu_entry"][$key])) {
                 $link = $PLUGIN_HOOKS["helpdesk_menu_entry"][$key];
             }
             echo "<li><a href='" . $CFG_GLPI["root_doc"] . "/plugins/" . $key . $link . "'>" . $plugins[$key]["name"] . "</a></li>\n";
         }
         echo "</ul></li>";
     }
     echo "</ul>";
     echo "<div class='sep'></div>";
     echo "</div>";
     // End navigation bar
     // End headline
     ///Le sous menu contextuel 1
     echo "<div id='c_ssmenu1'>&nbsp;</div>";
     //  Le fil d ariane
     echo "<div id='c_ssmenu2'>";
     echo "<ul>";
     echo "<li><a href='" . $CFG_GLPI["root_doc"] . "/front/helpdesk.public.php' title=\"" . __s('Home') . "\">" . __('Home') . "></a></li>";
     echo "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li>";
     if (Session::haveRight('validate_incident', 1) || Session::haveRight('validate_request', 1)) {
         $opt = array();
         $opt['reset'] = 'reset';
         $opt['field'][0] = 55;
         // validation status
         $opt['searchtype'][0] = 'equals';
         $opt['contains'][0] = 'waiting';
         $opt['link'][0] = 'AND';
         $opt['field'][1] = 59;
         // validation aprobator
         $opt['searchtype'][1] = 'equals';
         $opt['contains'][1] = Session::getLoginUserID();
         $opt['link'][1] = 'AND';
         $url_validate = $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($opt, '&amp;');
         $pic_validate = "<a href='{$url_validate}'>" . "<img title=\"" . __s('Ticket waiting for your approval') . "\" alt=\"" . __s('Ticket waiting for your approval') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/menu_showall.png'></a>";
         echo "<li>{$pic_validate}</li>\n";
     }
     echo "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li>";
     if (Session::haveRight('create_ticket', 1) && strpos($_SERVER['PHP_SELF'], "ticket")) {
         echo "<li><a href='" . $CFG_GLPI["root_doc"] . "/front/helpdesk.public.php?create_ticket=1'>";
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/menu_add.png' title=\"" . __s('Add') . "\" alt=\"" . __s('Add') . "\"></a></li>";
     }
     echo "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li>";
     /// Bookmark load
     echo "<li>";
     echo "<a href='#' onClick=\"var w=window.open('" . $CFG_GLPI["root_doc"] . "/front/popup.php?popup=load_bookmark' ,'glpibookmarks', 'height=400, width=600, " . "top=100, left=100, scrollbars=yes' );w.focus();\">";
     echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/bookmark.png' title=\"" . __s('Load a bookmark') . "\" alt=\"" . __s('Load a bookmark') . "\">";
     echo "</a></li>";
     // check user id : header used for display messages when session logout
     if (Session::getLoginUserID()) {
         self::showProfileSelecter($CFG_GLPI["root_doc"] . "/front/helpdesk.public.php");
     }
     echo "</ul></div>";
     echo "</div>";
     // fin header
     echo "<div id='page' >";
     // call static function callcron() every 5min
     CronTask::callCron();
     self::displayMessageAfterRedirect();
 }
Esempio n. 26
0
 /**
  * Generic Function to display Items
  *
  * @param $itemtype              item type
  * @param $ID                    ID of the SEARCH_OPTION item
  * @param $data            array containing data results
  * @param $num                   item num in the request
  * @param $meta                  is a meta item ? (default 0)
  * @param $addobjectparams array added parameters for union search
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI, $DB;
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) {
             return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']);
         }
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     if (count($addobjectparams)) {
         $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     //       if ($meta) {
     //          $NAME = "META_";
     //       }
     if (isset($searchopt[$ID]["table"])) {
         $table = $searchopt[$ID]["table"];
         $field = $searchopt[$ID]["field"];
         $linkfield = $searchopt[$ID]["linkfield"];
         /// TODO try to clean all specific cases using SpecificToDisplay
         switch ($table . '.' . $field) {
             case "glpi_users.name":
                 // USER search case
                 if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                     $out = "";
                     $count_display = 0;
                     $added = array();
                     $showuserlink = 0;
                     if (Session::haveRight('user', READ)) {
                         $showuserlink = 1;
                     }
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0 || isset($data[$num][$k][2]) && $data[$num][$k][2] != '') {
                             if ($count_display) {
                                 $out .= self::LBBR;
                             }
                             if ($itemtype == 'Ticket') {
                                 if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0) {
                                     $userdata = getUserName($data[$num][$k]['name'], 2);
                                     $tooltip = "";
                                     if (Session::haveRight('user', READ)) {
                                         $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                                     }
                                     $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);
                                     $count_display++;
                                 }
                             } else {
                                 $out .= getUserName($data[$num][$k]['name'], $showuserlink);
                                 $count_display++;
                             }
                             // Manage alternative_email for tickets_users
                             if ($itemtype == 'Ticket' && isset($data[$num][$k][2])) {
                                 $split = explode(self::LONGSEP, $data[$num][$k][2]);
                                 for ($l = 0; $l < count($split); $l++) {
                                     $split2 = explode(" ", $split[$l]);
                                     if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                                         if ($count_display) {
                                             $out .= self::LBBR;
                                         }
                                         $count_display++;
                                         $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                                     }
                                 }
                             }
                         }
                     }
                     return $out;
                 }
                 if ($itemtype != 'User') {
                     $toadd = '';
                     if ($itemtype == 'Ticket' && $data[$num][0]['id'] > 0) {
                         $userdata = getUserName($data[$num][0]['id'], 2);
                         $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                     }
                     $usernameformat = formatUserName($data[$num][0]['id'], $data[$num][0]['name'], $data[$num][0]['realname'], $data[$num][0]['firstname'], 1);
                     return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);
                 }
                 break;
             case "glpi_profiles.name":
                 if ($itemtype == 'User' && $ID == 20) {
                     $out = "";
                     $count_display = 0;
                     $added = array();
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (strlen(trim($data[$num][$k]['name'])) > 0) {
                             $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_entities', $data[$num][$k]['entities_id']));
                             $comp = '';
                             if ($data[$num][$k]['is_recursive']) {
                                 $comp = __('R');
                                 if ($data[$num][$k]['is_dynamic']) {
                                     $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                                 }
                             }
                             if ($data[$num][$k]['is_dynamic']) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                             }
                             if (!empty($comp)) {
                                 $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                             }
                             if (!in_array($text, $added)) {
                                 if ($count_display) {
                                     $out .= self::LBBR;
                                 }
                                 $count_display++;
                                 $out .= $text;
                                 $added[] = $text;
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "glpi_entities.completename":
                 if ($itemtype == 'User') {
                     $out = "";
                     $added = array();
                     $count_display = 0;
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (strlen(trim($data[$num][$k]['name'])) > 0) {
                             $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_profiles', $data[$num][$k]['profiles_id']));
                             $comp = '';
                             if ($data[$num][$k]['is_recursive']) {
                                 $comp = __('R');
                                 if ($data[$num][$k]['is_dynamic']) {
                                     $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                                 }
                             }
                             if ($data[$num][$k]['is_dynamic']) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                             }
                             if (!empty($comp)) {
                                 $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                             }
                             if (!in_array($text, $added)) {
                                 if ($count_display) {
                                     $out .= self::LBBR;
                                 }
                                 $count_display++;
                                 $out .= $text;
                                 $added[] = $text;
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "glpi_documenttypes.icon":
                 if (!empty($data[$num][0]['name'])) {
                     return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$num][0]['name'] . "'>";
                 }
                 return "&nbsp;";
             case "glpi_documents.filename":
                 $doc = new Document();
                 if ($doc->getFromDB($data['id'])) {
                     return $doc->getDownloadLink();
                 }
                 return NOT_AVAILABLE;
             case "glpi_tickets_tickets.tickets_id_1":
                 $out = "";
                 $displayed = array();
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     $linkid = $data[$num][$k]['tickets_id_2'] == $data['id'] ? $data[$num][$k]['name'] : $data[$num][$k]['tickets_id_2'];
                     if ($linkid > 0 && !isset($displayed[$linkid])) {
                         $text = "<a ";
                         $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">";
                         $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>";
                         if (count($displayed)) {
                             $out .= self::LBBR;
                         }
                         $displayed[$linkid] = $linkid;
                         $out .= $text;
                     }
                 }
                 return $out;
             case "glpi_problems.id":
                 if ($searchopt[$ID]["datatype"] == 'count') {
                     if ($data[$num][0]['name'] > 0 && Session::haveRight("problem", Problem::READALL)) {
                         if ($itemtype == 'ITILCategory') {
                             $options['criteria'][0]['field'] = 7;
                             $options['criteria'][0]['searchtype'] = 'equals';
                             $options['criteria'][0]['value'] = $data['id'];
                             $options['criteria'][0]['link'] = 'AND';
                         } else {
                             $options['criteria'][0]['field'] = 12;
                             $options['criteria'][0]['searchtype'] = 'equals';
                             $options['criteria'][0]['value'] = 'all';
                             $options['criteria'][0]['link'] = 'AND';
                             $options['metacriteria'][0]['itemtype'] = $itemtype;
                             $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name');
                             $options['metacriteria'][0]['searchtype'] = 'equals';
                             $options['metacriteria'][0]['value'] = $data['id'];
                             $options['metacriteria'][0]['link'] = 'AND';
                         }
                         $options['reset'] = 'reset';
                         $out = "<a id='problem{$itemtype}" . $data['id'] . "' ";
                         $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                         $out .= $data[$num][0]['name'] . "</a>";
                         return $out;
                     }
                 }
                 break;
             case "glpi_tickets.id":
                 if ($searchopt[$ID]["datatype"] == 'count') {
                     if ($data[$num][0]['name'] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                         if ($itemtype == 'User') {
                             // Requester
                             if ($ID == 60) {
                                 $options['criteria'][0]['field'] = 4;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                             // Writer
                             if ($ID == 61) {
                                 $options['criteria'][0]['field'] = 22;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                             // Assign
                             if ($ID == 64) {
                                 $options['criteria'][0]['field'] = 5;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                         } else {
                             if ($itemtype == 'ITILCategory') {
                                 $options['criteria'][0]['field'] = 7;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             } else {
                                 $options['criteria'][0]['field'] = 12;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = 'all';
                                 $options['criteria'][0]['link'] = 'AND';
                                 $options['metacriteria'][0]['itemtype'] = $itemtype;
                                 $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name');
                                 $options['metacriteria'][0]['searchtype'] = 'equals';
                                 $options['metacriteria'][0]['value'] = $data['id'];
                                 $options['metacriteria'][0]['link'] = 'AND';
                             }
                         }
                         $options['reset'] = 'reset';
                         $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                         $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                         $out .= $data[$num][0]['name'] . "</a>";
                         return $out;
                     }
                 }
                 break;
             case "glpi_tickets.due_date":
             case "glpi_problems.due_date":
             case "glpi_changes.due_date":
                 // Due date + progress
                 if ($ID == 151) {
                     $out = Html::convDate($data[$num][0]['name']);
                     // No due date in waiting status
                     if ($data[$num][0]['status'] == CommonITILObject::WAITING) {
                         return '';
                     }
                     if (empty($data[$num][0]['name'])) {
                         return '';
                     }
                     if ($data[$num][0]['status'] == Ticket::SOLVED || $data[$num][0]['status'] == Ticket::CLOSED) {
                         return $out;
                     }
                     $itemtype = getItemTypeForTable($table);
                     $item = new $itemtype();
                     $item->getFromDB($data['id']);
                     $percentage = 0;
                     $totaltime = 0;
                     $currenttime = 0;
                     if ($item->isField('slas_id') && $item->fields['slas_id'] != 0) {
                         // Have SLA
                         $sla = new SLA();
                         $sla->getFromDB($item->fields['slas_id']);
                         $currenttime = $sla->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $sla->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']);
                     } else {
                         $calendars_id = Entity::getUsedConfig('calendars_id', $item->fields['entities_id']);
                         if ($calendars_id != 0) {
                             // Ticket entity have calendar
                             $calendar = new Calendar();
                             $calendar->getFromDB($calendars_id);
                             $currenttime = $calendar->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                             $totaltime = $calendar->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']);
                         } else {
                             // No calendar
                             $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($item->fields['date']);
                             $totaltime = strtotime($data[$num][0]['name']) - strtotime($item->fields['date']);
                         }
                     }
                     if ($totaltime != 0) {
                         $percentage = round(100 * $currenttime / $totaltime);
                     } else {
                         // Total time is null : no active time
                         $percentage = 100;
                     }
                     if ($percentage > 100) {
                         $percentage = 100;
                     }
                     $percentage_text = $percentage;
                     if ($_SESSION['glpiduedatewarning_unit'] == '%') {
                         $less_warn_limit = $_SESSION['glpiduedatewarning_less'];
                         $less_warn = 100 - $percentage;
                     } else {
                         if ($_SESSION['glpiduedatewarning_unit'] == 'hour') {
                             $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;
                             $less_warn = $totaltime - $currenttime;
                         } else {
                             if ($_SESSION['glpiduedatewarning_unit'] == 'day') {
                                 $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;
                                 $less_warn = $totaltime - $currenttime;
                             }
                         }
                     }
                     if ($_SESSION['glpiduedatecritical_unit'] == '%') {
                         $less_crit_limit = $_SESSION['glpiduedatecritical_less'];
                         $less_crit = 100 - $percentage;
                     } else {
                         if ($_SESSION['glpiduedatecritical_unit'] == 'hour') {
                             $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;
                             $less_crit = $totaltime - $currenttime;
                         } else {
                             if ($_SESSION['glpiduedatecritical_unit'] == 'day') {
                                 $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;
                                 $less_crit = $totaltime - $currenttime;
                             }
                         }
                     }
                     $color = $_SESSION['glpiduedateok_color'];
                     if ($less_crit < $less_crit_limit) {
                         $color = $_SESSION['glpiduedatecritical_color'];
                     } else {
                         if ($less_warn < $less_warn_limit) {
                             $color = $_SESSION['glpiduedatewarning_color'];
                         }
                     }
                     //Calculate bar progress
                     $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n                            border: 1px solid #9BA563; position: relative;' >";
                     $out .= "<div style='position:absolute;'>&nbsp;" . $percentage_text . "%</div>";
                     $out .= "<div class='center' style='background-color: " . $color . ";\n                            width: " . $percentage . "%; height: 12px' ></div>";
                     $out .= "</div>";
                     return $out;
                 }
                 break;
             case "glpi_softwarelicenses.number":
                 if ($data[$num][0]['min'] == -1) {
                     return __('Unlimited');
                 }
                 if (empty($data[$num][0]['name'])) {
                     return 0;
                 }
                 return $data[$num][0]['name'];
             case "glpi_auth_tables.name":
                 return Auth::getMethodName($data[$num][0]['name'], $data[$num][0]['auths_id'], 1, $data[$num][0]['ldapname'] . $data[$num][0]['mailname']);
             case "glpi_reservationitems.comment":
                 if (empty($data[$num][0]['name'])) {
                     return "<a title=\"" . __s('Modify the comment') . "\"\n                           href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>";
                 }
                 return "<a title=\"" . __s('Modify the comment') . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$num][0]['name']) . "</a>";
             case 'glpi_crontasks.description':
                 $tmp = new CronTask();
                 return $tmp->getDescription($data[$num][0]['name']);
             case 'glpi_changes.status':
                 $status = Change::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Change::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_problems.status':
                 $status = Problem::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Problem::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_tickets.status':
                 $status = Ticket::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Ticket::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_projectstates.name':
                 $out = '';
                 $query = "SELECT `color`\n                         FROM `glpi_projectstates`\n                         WHERE `name` = '" . $data[$num][0]['name'] . "'";
                 foreach ($DB->request($query) as $color) {
                     $color = $color['color'];
                     $out = "<div style=\"background-color:" . $color . ";\">";
                     $name = $data[$num][0]['name'];
                     if (isset($data[$num][0]['trans'])) {
                         $name = $data[$num][0]['trans'];
                     }
                     if ($itemtype == 'ProjectState') {
                         $out .= "<a href='" . $CFG_GLPI["root_doc"] . "/front/projectstate.form.php?id=" . $data[$num][0]["id"] . "'>" . $name . "</a></div>";
                     } else {
                         $out .= $name . "</div>";
                     }
                 }
                 return $out;
             case 'glpi_items_tickets.items_id':
             case 'glpi_items_problems.items_id':
                 if (!empty($data[$num])) {
                     $items = array();
                     foreach ($data[$num] as $key => $val) {
                         if (is_numeric($key)) {
                             if (!empty($val['itemtype']) && ($item = getItemForItemtype($val['itemtype']))) {
                                 if ($item->getFromDB($val['name'])) {
                                     $items[] = $item->getLink(array('comments' => true));
                                 }
                             }
                         }
                     }
                     if (!empty($items)) {
                         return implode("<br>", $items);
                     }
                 }
                 return '&nbsp;';
             case 'glpi_items_tickets.itemtype':
             case 'glpi_items_problems.itemtype':
                 if (!empty($data[$num])) {
                     $itemtypes = array();
                     foreach ($data[$num] as $key => $val) {
                         if (is_numeric($key)) {
                             if (!empty($val['name'])) {
                                 if (substr($val['name'], 0, 6) == 'Plugin') {
                                     $plug = new $val['name']();
                                     $name = $plug->getTypeName();
                                     $itemtypes[] = __($name);
                                 } else {
                                     $itemtypes[] = __($val['name']);
                                 }
                             }
                         }
                     }
                     if (!empty($itemtypes)) {
                         return implode("<br>", $itemtypes);
                     }
                 }
                 return '&nbsp;';
             case 'glpi_tickets.name':
             case 'glpi_problems.name':
             case 'glpi_changes.name':
                 if (isset($data[$num][0]['content']) && isset($data[$num][0]['id']) && isset($data[$num][0]['status'])) {
                     $link = Toolbox::getItemTypeFormURL($itemtype);
                     $out = "<a id='{$itemtype}" . $data[$num][0]['id'] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$num][0]['id'];
                     // Force solution tab if solved
                     if ($item = getItemForItemtype($itemtype)) {
                         if (in_array($data[$num][0]['status'], $item->getSolvedStatusArray())) {
                             $out .= "&amp;forcetab={$itemtype}\$2";
                         }
                     }
                     $out .= "\">";
                     $name = $data[$num][0]['name'];
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][0]['name'])) {
                         $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][0]['id']);
                     }
                     $out .= $name . "</a>";
                     $hdecode = Html::entity_decode_deep($data[$num][0]['content']);
                     $content = Toolbox::unclean_cross_side_scripting_deep($hdecode);
                     $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => $itemtype . $data[$num][0]['id'], 'display' => false)));
                     return $out;
                 }
             case 'glpi_ticketvalidations.status':
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if ($data[$num][$k]['name']) {
                         $status = TicketValidation::getStatus($data[$num][$k]['name']);
                         $bgcolor = TicketValidation::getStatusColor($data[$num][$k]['name']);
                         $out .= (empty($out) ? '' : self::LBBR) . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
                     }
                 }
                 return $out;
             case 'glpi_ticketsatisfactions.satisfaction':
                 if (self::$output_type == self::HTML_OUTPUT) {
                     return TicketSatisfaction::displaySatisfaction($data[$num][0]['name']);
                 }
                 break;
             case 'glpi_projects._virtual_planned_duration':
                 return Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($data["id"]), false);
             case 'glpi_projects._virtual_effective_duration':
                 return Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($data["id"]), false);
             case 'glpi_cartridgeitems._virtual':
                 return Cartridge::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_printers._virtual':
                 return Cartridge::getCountForPrinter($data["id"], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_consumableitems._virtual':
                 return Consumable::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_links._virtual':
                 $out = '';
                 $link = new Link();
                 if (($item = getItemForItemtype($itemtype)) && $item->getFromDB($data['id']) && $link->getfromDB($data[$num][0]['id']) && $item->fields['entities_id'] == $link->fields['entities_id']) {
                     if (count($data[$num])) {
                         $count_display = 0;
                         foreach ($data[$num] as $val) {
                             if (is_array($val)) {
                                 $links = Link::getAllLinksFor($item, $val);
                                 foreach ($links as $link) {
                                     if ($count_display) {
                                         $out .= self::LBBR;
                                     }
                                     $out .= $link;
                                     $count_display++;
                                 }
                             }
                         }
                     }
                 }
                 return $out;
             case 'glpi_reservationitems._virtual':
                 if ($data[$num][0]['is_active']) {
                     return "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>";
                 } else {
                     return "&nbsp;";
                 }
         }
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (isset($table)) {
         if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
             if (count($matches) == 2) {
                 $plug = $matches[1];
                 $function = 'plugin_' . $plug . '_giveItem';
                 if (function_exists($function)) {
                     $out = $function($itemtype, $ID, $data, $num);
                     if (!empty($out)) {
                         return $out;
                     }
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]);
                 $out = "";
                 $count_display = 0;
                 $separate = self::LBBR;
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = self::LBHR;
                 }
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (isset($data[$num][$k]['id'])) {
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         $page = $linkitemtype::getFormUrl();
                         $page .= strpos($page, '?') ? '&id' : '?id';
                         $name = Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit);
                         if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][$k]['name'])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][$k]['id']);
                         }
                         $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $data[$num][$k]['id'] . "' href='{$page}=" . $data[$num][$k]['id'] . "'>" . $name . "</a>";
                     }
                 }
                 return $out;
             case "text":
                 $separate = self::LBBR;
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = self::LBHR;
                 }
                 $out = '';
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         $text = "";
                         if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                             $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($data[$num][$k]['name'])));
                         } else {
                             $text = nl2br($data[$num][$k]['name']);
                         }
                         if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) {
                             $rand = mt_rand();
                             $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false)));
                         } else {
                             $out .= $text;
                         }
                     }
                 }
                 return $out;
             case "date":
             case "date_delay":
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) {
                         $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel'];
                     } else {
                         $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$num][$k]['name']);
                     }
                 }
                 return $out;
             case "datetime":
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) {
                         $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel'];
                     } else {
                         $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$num][$k]['name']);
                     }
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 $withdays = true;
                 if (isset($searchopt[$ID]['withdays'])) {
                     $withdays = $searchopt[$ID]['withdays'];
                 }
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($data[$num][$k]['name'], $withseconds, $withdays);
                 }
                 return $out;
             case "email":
                 $out = '';
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if ($count_display) {
                         $out .= self::LBBR;
                     }
                     $count_display++;
                     if (!empty($data[$num][$k]['name'])) {
                         $out .= empty($out) ? '' : self::LBBR;
                         $out .= "<a href='mailto:" . $data[$num][$k]['name'] . "'>" . $data[$num][$k]['name'];
                         $out .= "</a>";
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "weblink":
                 $orig_link = trim($data[$num][0]['name']);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "count":
             case "number":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                             $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                         } else {
                             $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$num][$k]['name'], false, 0));
                             $out .= Dropdown::getValueWithUnit($number, $unit);
                         }
                     }
                 }
                 return $out;
             case "decimal":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                             $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                         } else {
                             $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$num][$k]['name']));
                             $out .= Dropdown::getValueWithUnit($number, $unit);
                         }
                     }
                 }
                 return $out;
             case "bool":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$num][$k]['name']), $unit);
                     }
                 }
                 return $out;
             case "itemtypename":
                 if ($obj = getItemForItemtype($data[$num][0]['name'])) {
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$num][0]['name']])) {
                     return $CFG_GLPI['languages'][$data[$num][0]['name']][0];
                 }
                 return __('Default value');
         }
     }
     // Manage items with need group by / group_concat
     $out = "";
     $count_display = 0;
     $separate = self::LBBR;
     if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
         $separate = self::LBHR;
     }
     for ($k = 0; $k < $data[$num]['count']; $k++) {
         if (strlen(trim($data[$num][$k]['name'])) > 0) {
             if ($count_display) {
                 $out .= $separate;
             }
             $count_display++;
             // Get specific display if available
             $itemtype = getItemTypeForTable($table);
             if ($item = getItemForItemtype($itemtype)) {
                 $tmpdata = $data[$num][$k];
                 // Copy name to real field
                 $tmpdata[$field] = $data[$num][$k]['name'];
                 $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true, 'searchopt' => $searchopt[$ID]));
             }
             if (!empty($specific)) {
                 $out .= $specific;
             } else {
                 if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                     $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                 } else {
                     // Empty is 0 or empty
                     if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) {
                         $out .= $searchopt[$ID]['emptylabel'];
                     } else {
                         // Trans field exists
                         if (isset($data[$num][$k]['trans']) && !empty($data[$num][$k]['trans'])) {
                             $out .= Dropdown::getValueWithUnit($data[$num][$k]['trans'], $unit);
                         } else {
                             $out .= Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit);
                         }
                     }
                 }
             }
         }
     }
     return $out;
     // Trans in group concat
     if (count($split) == 3 && !empty($split[1])) {
         return Dropdown::getValueWithUnit($split[1], $unit);
     }
     return Dropdown::getValueWithUnit($split[0], $unit);
 }
Esempio n. 27
0
 /**
  * Print the HTML array for infocoms linked
  *
  *@return Nothing (display)
  *
  **/
 function showInfocoms()
 {
     global $DB, $CFG_GLPI;
     $instID = $this->fields['id'];
     if (!$this->can($instID, READ)) {
         return false;
     }
     $query = "SELECT DISTINCT `itemtype`\n                FROM `glpi_infocoms`\n                WHERE `suppliers_id` = '{$instID}'\n                      AND `itemtype` NOT IN ('ConsumableItem', 'CartridgeItem', 'Software')\n                ORDER BY `itemtype`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     echo "<div class='spaced'><table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='2'>";
     Html::printPagerForm();
     echo "</th><th colspan='3'>";
     if ($DB->numrows($result) == 0) {
         _e('No associated item');
     } else {
         echo _n('Associated item', 'Associated items', $DB->numrows($result));
     }
     echo "</th></tr>";
     echo "<tr><th>" . __('Type') . "</th>";
     echo "<th>" . __('Entity') . "</th>";
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Serial number') . "</th>";
     echo "<th>" . __('Inventory number') . "</th>";
     echo "</tr>";
     $num = 0;
     for ($i = 0; $i < $number; $i++) {
         $itemtype = $DB->result($result, $i, "itemtype");
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         if ($item->canView()) {
             $linktype = $itemtype;
             $linkfield = 'id';
             $itemtable = getTableForItemType($itemtype);
             $query = "SELECT `glpi_infocoms`.`entities_id`, `name`, `{$itemtable}`.*\n                      FROM `glpi_infocoms`\n                      INNER JOIN `{$itemtable}` ON (`{$itemtable}`.`id` = `glpi_infocoms`.`items_id`) ";
             // Set $linktype for entity restriction AND link to search engine
             if ($itemtype == 'Cartridge') {
                 $query .= "INNER JOIN `glpi_cartridgeitems`\n                            ON (`glpi_cartridgeitems`.`id`=`glpi_cartridges`.`cartridgeitems_id`) ";
                 $linktype = 'CartridgeItem';
                 $linkfield = 'cartridgeitems_id';
             }
             if ($itemtype == 'Consumable') {
                 $query .= "INNER JOIN `glpi_consumableitems`\n                            ON (`glpi_consumableitems`.`id`=`glpi_consumables`.`consumableitems_id`) ";
                 $linktype = 'ConsumableItem';
                 $linkfield = 'consumableitems_id';
             }
             $linktable = getTableForItemType($linktype);
             $query .= "WHERE `glpi_infocoms`.`itemtype` = '{$itemtype}'\n                             AND `glpi_infocoms`.`suppliers_id` = '{$instID}'" . getEntitiesRestrictRequest(" AND", $linktable) . "\n                       ORDER BY `glpi_infocoms`.`entities_id`,\n                                `{$linktable}`.`name`";
             $result_linked = $DB->query($query);
             $nb = $DB->numrows($result_linked);
             // Set $linktype for link to search engine pnly
             if ($itemtype == 'SoftwareLicense' && $nb > $_SESSION['glpilist_limit']) {
                 $linktype = 'Software';
                 $linkfield = 'softwares_id';
             }
             $link_item = new $linktype();
             if ($nb > $_SESSION['glpilist_limit']) {
                 echo "<tr class='tab_bg_1'>";
                 $title = $item->getTypeName($nb);
                 if ($nb > 0) {
                     $title = sprintf(__('%1$s: %2$s'), $title, $nb);
                 }
                 echo "<td class='center'>" . $title . "</td>";
                 echo "<td class='center' colspan='2'>";
                 $opt = array('order' => 'ASC', 'is_deleted' => 0, 'reset' => 'reset', 'start' => 0, 'sort' => 80, 'criteria' => array(0 => array('value' => '$$$$' . $instID, 'searchtype' => 'contains', 'field' => 53)));
                 $link = $linktype::getSearchURL();
                 $link .= strpos($link, '?') ? '&amp;' : '?';
                 echo "<a href='{$link}" . Toolbox::append_params($opt) . "'>" . __('Device list') . "</a></td>";
                 echo "<td class='center'>-</td><td class='center'>-</td></tr>";
             } else {
                 if ($nb) {
                     for ($prem = true; $data = $DB->fetch_assoc($result_linked); $prem = false) {
                         $name = $data["name"];
                         if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]);
                         }
                         $link = $link_item->getFormURLWithID($data[$linkfield]);
                         $name = "<a href='{$link}'>" . $name . "</a>";
                         echo "<tr class='tab_bg_1'>";
                         if ($prem) {
                             $title = $item->getTypeName($nb);
                             if ($nb > 0) {
                                 $title = sprintf(__('%1$s: %2$s'), $title, $nb);
                             }
                             echo "<td class='center top' rowspan='{$nb}'>" . $title . "</td>";
                         }
                         echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data["entities_id"]) . "</td>";
                         echo "<td class='center";
                         echo (isset($data['is_deleted']) && $data['is_deleted'] ? " tab_bg_2_2'" : "'") . ">";
                         echo $name . "</td>";
                         echo "<td class='center'>" . (isset($data["serial"]) ? "" . $data["serial"] . "" : "-") . "</td>";
                         echo "<td class='center'>" . (isset($data["otherserial"]) ? "" . $data["otherserial"] . "" : "-") . "</td>";
                         echo "</tr>";
                     }
                 }
             }
             $num += $nb;
         }
     }
     echo "<tr class='tab_bg_2'>";
     echo "<td class='center'>" . ($num > 0 ? sprintf(__('%1$s = %2$s'), __('Total'), $num) : "&nbsp;") . "</td>";
     echo "<td colspan='4'>&nbsp;</td></tr> ";
     echo "</table></div>";
 }
Esempio n. 28
0
 /**
  * Show div with auto completion
  *
  * @param $item            item object used for create dropdown
  * @param $field           field to search for autocompletion
  * @param $options   array of possible options:
  *    - name    : string / name of the select (default is field parameter)
  *    - value   : integer / preselected value (default value of the item object)
  *    - size    : integer / size of the text field
  *    - entity  : integer / restrict to a defined entity (default entity of the object if define)
  *                set to -1 not to take into account
  *    - user    : integer / restrict to a defined user (default -1 : no restriction)
  *    - option  : string / options to add to text field
  *    - display : boolean / if false get string
  *
  * @return nothing (print out an HTML div)
  **/
 static function autocompletionTextField(CommonDBTM $item, $field, $options = array())
 {
     global $CFG_GLPI;
     $params['name'] = $field;
     $params['value'] = '';
     if (array_key_exists($field, $item->fields)) {
         $params['value'] = $item->fields[$field];
     }
     $params['size'] = 40;
     $params['entity'] = -1;
     if (array_key_exists('entities_id', $item->fields)) {
         $params['entity'] = $item->fields['entities_id'];
     }
     $params['user'] = -1;
     $params['option'] = '';
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     $output = '';
     if ($CFG_GLPI["use_ajax_autocompletion"]) {
         $rand = mt_rand();
         $name = "field_" . $params['name'] . $rand;
         $output .= "<input " . $params['option'] . " id='text{$name}' type='text' name='" . $params['name'] . "' value=\"" . self::cleanInputText($params['value']) . "\" size='" . $params['size'] . "'>\n";
         $parameters['itemtype'] = $item->getType();
         $parameters['field'] = $field;
         if ($params['entity'] >= 0) {
             $parameters['entity_restrict'] = $params['entity'];
         }
         if ($params['user'] >= 0) {
             $parameters['user_restrict'] = $params['user'];
         }
         $js = "  \$( '#text{$name}' ).autocomplete({\n                        source: '" . $CFG_GLPI["root_doc"] . "/ajax/autocompletion.php?" . Toolbox::append_params($parameters, '&') . "',\n                        minLength: 3,\n                        });";
         $output .= Html::scriptBlock($js);
     } else {
         $output .= "<input " . $params['option'] . " type='text' name='" . $params['name'] . "'\n                value=\"" . self::cleanInputText($params['value']) . "\" size='" . $params['size'] . "'>\n";
     }
     if (!isset($options['display']) || $options['display']) {
         echo $output;
     } else {
         return $output;
     }
 }
            Html::redirect($CFG_GLPI['root_doc'] . "/plugins/monitoring/front/componentscatalog.form.php?id=" . $_POST['plugin_monitoring_componentscalalog_id']);
        } else {
            if (isset($_GET['criteria']) or isset($_GET['reset'])) {
                //   if (isset($_SESSION['plugin_monitoring_rules'])) {
                //      unset($_SESSION['plugin_monitoring_rules']);
                //   }
                //   $_SESSION['plugin_monitoring_rules'] = $_POST;
                //   $_SESSION['plugin_monitoring_rules_REQUEST_URI'] = $_SERVER['REQUEST_URI'];
                //Html::back();
            } else {
                if (isset($_GET['id']) and !isset($_GET['itemtype'])) {
                    $pmComponentscatalog_rule->getFromDB($_GET['id']);
                    $val = importArrayFromDB($pmComponentscatalog_rule->fields['condition']);
                    $params = Search::manageParams($pmComponentscatalog_rule->fields['itemtype'], $val);
                    $url = str_replace("?id=" . $_GET['id'], "", $_SERVER['REQUEST_URI']);
                    $url .= "?" . Toolbox::append_params($params);
                    $url .= "&plugin_monitoring_componentscalalog_id=" . $pmComponentscatalog_rule->fields['plugin_monitoring_componentscalalog_id'];
                    $url .= "&name=" . $pmComponentscatalog_rule->fields['name'];
                    $url .= "&id=" . $_GET['id'];
                    Html::redirect($url);
                }
            }
        }
    }
}
if (isset($_POST['name'])) {
    $a_construct = array();
    foreach ($_POST as $key => $value) {
        $a_construct[] = $key . "=" . $value;
    }
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . "?" . implode("&", $a_construct);