static function pdfMain(PluginPdfSimplePDF $pdf, SoftwareLicense $license, $main = true, $cpt = true)
 {
     global $DB;
     $ID = $license->getField('id');
     $pdf->setColumnsSize(100);
     $entity = '';
     if (Session::isMultiEntitiesMode() && !$main) {
         $entity = ' (' . Html::clean(Dropdown::getDropdownName('glpi_entities', $license->fields['entities_id'])) . ')';
     }
     $pdf->displayTitle('<b><i>' . sprintf(__('%1$s: %2$s'), __('ID') . "</i>", $ID . "</b>" . $entity));
     $pdf->setColumnsSize(50, 50);
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), Software::getTypeName(1) . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwares', $license->fields['softwares_id']))), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Type') . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwarelicensetypes', $license->fields['softwarelicensetypes_id']))));
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('Name') . '</i></b>', $license->fields['name']), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Serial number') . '</i></b>', $license->fields['serial']));
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('Purchase version') . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwareversions', $license->fields['softwareversions_id_buy']))), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Inventory number') . '</i></b>', $license->fields['otherserial']));
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('Version in use') . '</i></b>', Html::clean(Dropdown::getDropdownName('glpi_softwareversions', $license->fields['softwareversions_id_use']))), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Expiration') . '</i></b>', Html::convDate($license->fields['expire'])));
     $col2 = '';
     if ($cpt) {
         $col2 = '<b><i>' . sprintf(__('%1$s: %2$s'), __('Affected computers') . '</i></b>', Computer_SoftwareLicense::countForLicense($ID));
     }
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), _x('quantity', 'Number') . '</i></b>', $license->fields['number'] > 0 ? $license->fields['number'] : __('Unlimited')), $col2);
     $pdf->setColumnsSize(100);
     PluginPdfCommon::mainLine($pdf, $license, 'comment');
     if ($main) {
         $pdf->displaySpace();
     }
 }
 static function pdfForLicenseByEntity(PluginPdfSimplePDF $pdf, SoftwareLicense $license)
 {
     global $DB;
     $ID = $license->getField('id');
     $pdf->setColumnsSize(65, 35);
     $pdf->setColumnsAlign('left', 'right');
     $pdf->displayTitle('<b><i>' . __('Entity') . '</i></b>', '<b><i>' . __('Number of affected computers') . '</i></b>');
     $tot = 0;
     if (in_array(0, $_SESSION["glpiactiveentities"])) {
         $nb = Computer_SoftwareLicense::countForLicense($ID, 0);
         if ($nb > 0) {
             $pdf->displayLine(__('Root entity'), $nb);
             $tot += $nb;
         }
     }
     $sql = "SELECT `id`, `completename`\n              FROM `glpi_entities` " . getEntitiesRestrictRequest('WHERE', 'glpi_entities') . "\n              ORDER BY `completename`";
     foreach ($DB->request($sql) as $entity => $data) {
         $nb = Computer_SoftwareLicense::countForLicense($ID, $entity);
         if ($nb > 0) {
             $pdf->displayLine($data["completename"], $nb);
             $tot += $nb;
         }
     }
     if ($tot > 0) {
         $pdf->displayLine(__('Total'), $tot);
     } else {
         $pdf->setColumnsSize(100);
         $pdf->setColumnsAlign('center');
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
 static function pdfForItem(PluginPdfSimplePDF $pdf, CommonDBTM $item)
 {
     global $DB;
     $ID = $item->getField('id');
     $type = $item->getType();
     $crit = $type == 'Software' ? 'softwares_id' : 'id';
     if ($type == 'Software') {
         $crit = 'softwares_id';
         // Software ID
         $innerjoin = "INNER JOIN `glpi_softwareversions`\n                           ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                               = `glpi_softwareversions`.`id`)";
         $where = "WHERE `glpi_softwareversions`.`softwares_id` = '" . $ID . "'";
     } else {
         $crit = 'id';
         //SoftwareVersion ID
         $innerjoin = '';
         $where = "WHERE `glpi_computers_softwareversions`.`softwareversions_id` = '" . $ID . "'";
     }
     $query_number = "SELECT COUNT(*) AS cpt\n                       FROM `glpi_computers_softwareversions`\n                       {$innerjoin}\n                       INNER JOIN `glpi_computers`\n                           ON (`glpi_computers_softwareversions`.`computers_id` = `glpi_computers`.`id`)\n                       {$where}" . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                            AND `glpi_computers`.`is_deleted` = '0'\n                            AND `glpi_computers`.`is_template` = '0'";
     $total = 0;
     if ($result = $DB->query($query_number)) {
         $total = $DB->result($result, 0, 0);
     }
     $query = "SELECT DISTINCT `glpi_computers_softwareversions`.*,\n                          `glpi_computers`.`name` AS compname,\n                          `glpi_computers`.`id` AS cID,\n                          `glpi_computers`.`serial`,\n                          `glpi_computers`.`otherserial`,\n                          `glpi_users`.`name` AS username,\n                          `glpi_users`.`id` AS userid,\n                          `glpi_users`.`realname` AS userrealname,\n                          `glpi_users`.`firstname` AS userfirstname,\n                          `glpi_softwareversions`.`name` AS version,\n                          `glpi_softwareversions`.`id` AS vID,\n                          `glpi_softwareversions`.`softwares_id` AS sID,\n                          `glpi_softwareversions`.`name` AS vername,\n                          `glpi_entities`.`completename` AS entity,\n                          `glpi_locations`.`completename` AS location,\n                          `glpi_states`.`name` AS state,\n                          `glpi_groups`.`name` AS groupe\n                FROM `glpi_computers_softwareversions`\n                INNER JOIN `glpi_softwareversions`\n                     ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                              = `glpi_softwareversions`.`id`)\n                INNER JOIN `glpi_computers`\n                     ON (`glpi_computers_softwareversions`.`computers_id` = `glpi_computers`.`id`)\n                LEFT JOIN `glpi_entities` ON (`glpi_computers`.`entities_id` = `glpi_entities`.`id`)\n                LEFT JOIN `glpi_locations`\n                     ON (`glpi_computers`.`locations_id` = `glpi_locations`.`id`)\n                LEFT JOIN `glpi_states` ON (`glpi_computers`.`states_id` = `glpi_states`.`id`)\n                LEFT JOIN `glpi_groups` ON (`glpi_computers`.`groups_id` = `glpi_groups`.`id`)\n                LEFT JOIN `glpi_users` ON (`glpi_computers`.`users_id` = `glpi_users`.`id`)\n                WHERE (`glpi_softwareversions`.`{$crit}` = '{$ID}') " . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                      AND `glpi_computers`.`is_deleted` = '0'\n                      AND `glpi_computers`.`is_template` = '0'\n                ORDER BY version, compname\n                LIMIT 0," . intval($_SESSION['glpilist_limit']);
     $pdf->setColumnsSize(100);
     if (($result = $DB->query($query)) && ($number = $DB->numrows($result)) > 0) {
         if ($number == $total) {
             $pdf->displayTitle('<b>' . sprintf(__('%1$s: %2$s'), _n('Installation', 'Installations', 2), $number) . "</b>");
         } else {
             $pdf->displayTitle('<b>' . sprintf(__('%1$s: %2$s'), _n('Installation', 'Installations', 2), $number / $total) . "</b>");
         }
         $pdf->setColumnsSize(12, 16, 15, 15, 22, 20);
         $pdf->displayTitle('<b><i>' . _n('Version', 'Versions', 2), __('Name'), __('Serial number'), __('Inventory number'), __('Location'), _n('License', 'Licenses', 2) . '</i></b>');
         while ($data = $DB->fetch_assoc($result)) {
             $compname = $data['compname'];
             if (empty($compname) || $_SESSION['glpiis_ids_visible']) {
                 $compname = sprintf(__('%1$s (%2$s)'), $compname, $data['cID']);
             }
             $lics = Computer_SoftwareLicense::GetLicenseForInstallation($data['cID'], $data['vID']);
             $tmp = array();
             if (count($lics)) {
                 foreach ($lics as $lic) {
                     $licname = $lic['name'];
                     if (!empty($lic['type'])) {
                         $licname = sprintf(__('%1$s (%2$s)'), $licname, $lic['type']);
                     }
                     $tmp[] = $licname;
                 }
             }
             $pdf->displayLine($data['version'], $compname, $data['serial'], $data['otherserial'], $data['location'], implode(', ', $tmp));
         }
     } else {
         $pdf->displayTitle('<b>' . _n('Installation', 'Installations', 2) . '</b>');
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
 /**
  * Show installations of a software
  *
  * @param $searchID valeur to the ID to search
  * @param $crit to search : softwares_id (software) or id (version)
  *
  * @return nothing
  **/
 private static function showInstallations($searchID, $crit)
 {
     global $DB, $CFG_GLPI, $LANG;
     if (!haveRight("software", "r") || !$searchID) {
         return false;
     }
     $canedit = haveRight("software", "w");
     $canshowcomputer = haveRight("computer", "r");
     if (isset($_REQUEST["start"])) {
         $start = $_REQUEST["start"];
     } else {
         $start = 0;
     }
     if (isset($_REQUEST["order"]) && $_REQUEST["order"] == "DESC") {
         $order = "DESC";
     } else {
         $order = "ASC";
     }
     if (isset($_REQUEST["sort"]) && !empty($_REQUEST["sort"])) {
         // manage several param like location,compname :  order first
         $tmp = explode(",", $_REQUEST["sort"]);
         $sort = "`" . implode("` {$order},`", $tmp) . "`";
     } else {
         if ($crit == "softwares_id") {
             $sort = "`entity` {$order}, `version`, `compname`";
         } else {
             $sort = "`entity` {$order}, `compname`";
         }
     }
     // Total Number of events
     if ($crit == "softwares_id") {
         // Software ID
         $query_number = "SELECT COUNT(*) AS cpt\n                          FROM `glpi_computers_softwareversions`\n                          INNER JOIN `glpi_softwareversions`\n                              ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                                    = `glpi_softwareversions`.`id`)\n                          INNER JOIN `glpi_computers`\n                              ON (`glpi_computers_softwareversions`.`computers_id`\n                                    = `glpi_computers`.`id`)\n                          WHERE `glpi_softwareversions`.`softwares_id` = '{$searchID}'" . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                                AND `glpi_computers`.`is_deleted` = '0'\n                                AND `glpi_computers`.`is_template` = '0'";
     } else {
         //SoftwareVersion ID
         $query_number = "SELECT COUNT(*) AS cpt\n                          FROM `glpi_computers_softwareversions`\n                          INNER JOIN `glpi_computers`\n                              ON (`glpi_computers_softwareversions`.`computers_id`\n                                    = `glpi_computers`.`id`)\n                          WHERE `glpi_computers_softwareversions`.`softwareversions_id` = '{$searchID}'" . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                                AND `glpi_computers`.`is_deleted` = '0'\n                                AND `glpi_computers`.`is_template` = '0'";
     }
     $number = 0;
     if ($result = $DB->query($query_number)) {
         $number = $DB->result($result, 0, 0);
     }
     echo "<div class='center'>";
     if ($number < 1) {
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr><th>" . $LANG['search'][15] . "</th></tr>";
         echo "</table></div>\n";
         return;
     }
     // Display the pager
     printAjaxPager($LANG['software'][19], $start, $number);
     $query = "SELECT DISTINCT `glpi_computers_softwareversions`.*,\n                       `glpi_computers`.`name` AS compname,\n                       `glpi_computers`.`id` AS cID,\n                       `glpi_computers`.`serial`,\n                       `glpi_computers`.`otherserial`,\n                       `glpi_users`.`name` AS username,\n                       `glpi_users`.`id` AS userid,\n                       `glpi_users`.`realname` AS userrealname,\n                       `glpi_users`.`firstname` AS userfirstname,\n                       `glpi_softwareversions`.`name` AS version,\n                       `glpi_softwareversions`.`id` AS vID,\n                       `glpi_softwareversions`.`softwares_id` AS sID,\n                       `glpi_softwareversions`.`name` AS vername,\n                       `glpi_entities`.`completename` AS entity,\n                       `glpi_locations`.`completename` AS location,\n                       `glpi_states`.`name` AS state,\n                       `glpi_groups`.`name` AS groupe\n                FROM `glpi_computers_softwareversions`\n                INNER JOIN `glpi_softwareversions`\n                     ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                           = `glpi_softwareversions`.`id`)\n                INNER JOIN `glpi_computers`\n                     ON (`glpi_computers_softwareversions`.`computers_id` = `glpi_computers`.`id`)\n                LEFT JOIN `glpi_entities` ON (`glpi_computers`.`entities_id` = `glpi_entities`.`id`)\n                LEFT JOIN `glpi_locations`\n                     ON (`glpi_computers`.`locations_id` = `glpi_locations`.`id`)\n                LEFT JOIN `glpi_states` ON (`glpi_computers`.`states_id` = `glpi_states`.`id`)\n                LEFT JOIN `glpi_groups` ON (`glpi_computers`.`groups_id` = `glpi_groups`.`id`)\n                LEFT JOIN `glpi_users` ON (`glpi_computers`.`users_id` = `glpi_users`.`id`)\n                WHERE (`glpi_softwareversions`.`{$crit}` = '{$searchID}') " . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                       AND `glpi_computers`.`is_deleted` = '0'\n                       AND `glpi_computers`.`is_template` = '0'\n                ORDER BY {$sort} {$order}\n                LIMIT " . intval($start) . "," . intval($_SESSION['glpilist_limit']);
     $rand = mt_rand();
     if ($result = $DB->query($query)) {
         if ($data = $DB->fetch_assoc($result)) {
             $softwares_id = $data['sID'];
             $soft = new Software();
             $showEntity = $soft->getFromDB($softwares_id) && $soft->isRecursive();
             $linkUser = haveRight('user', 'r');
             $title = $LANG['help'][31] . " = " . $soft->fields["name"];
             if ($crit == "id") {
                 $title .= " - " . $data["vername"];
             }
             initNavigateListItems('Computer', $title);
             $sort_img = "<img src='" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "' alt='' title=''>";
             if ($canedit) {
                 echo "<form name='softinstall" . $rand . "' id='softinstall" . $rand . "' method='post'\n                      action='" . $CFG_GLPI["root_doc"] . "/front/computer_softwareversion.form.php'>";
                 echo "<input type='hidden' name='softwares_id' value='{$softwares_id}'>";
                 echo "<table class='tab_cadre_fixehov'><tr>";
                 echo "<th>&nbsp;</th>";
             } else {
                 echo "<table class='tab_cadre_fixehov'><tr>";
             }
             if ($crit == "softwares_id") {
                 echo "<th>" . ($sort == "`vername`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=vername&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['software'][5] . "</a></th>";
             }
             echo "<th>" . ($sort == "`compname`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=compname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][16] . "</a></th>";
             if ($showEntity) {
                 echo "<th>" . (strstr($sort, "entity") ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=entity,compname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['entity'][0] . "</a></th>";
             }
             echo "<th>" . ($sort == "`serial`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=serial&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][19] . "</a></th>";
             echo "<th>" . ($sort == "`otherserial`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=otherserial&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][20] . "</a></th>";
             echo "<th>" . (strstr($sort, "`location`") ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=location,compname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][15] . "</a></th>";
             echo "<th>" . (strstr($sort, "state") ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=state,compname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['state'][0] . "</a></th>";
             echo "<th>" . (strstr($sort, "groupe") ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=groupe,compname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][35] . "</a></th>";
             echo "<th>" . (strstr($sort, "username") ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=username,compname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][34] . "</a></th>";
             echo "<th>" . ($sort == "`lname`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=lname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['software'][11] . "</a></th>";
             echo "</tr>\n";
             do {
                 addToNavigateListItems('Computer', $data["cID"]);
                 echo "<tr class='tab_bg_2'>";
                 if ($canedit) {
                     echo "<td><input type='checkbox' name='item[" . $data["id"] . "]' value='1'></td>";
                 }
                 if ($crit == "softwares_id") {
                     echo "<td><a href='softwareversion.form.php?id=" . $data['vID'] . "'>" . $data['version'];
                     echo "</a></td>";
                 }
                 $compname = $data['compname'];
                 if (empty($compname) || $_SESSION['glpiis_ids_visible']) {
                     $compname .= " (" . $data['cID'] . ")";
                 }
                 if ($canshowcomputer) {
                     echo "<td><a href='computer.form.php?id=" . $data['cID'] . "'>{$compname}</a></td>";
                 } else {
                     echo "<td>" . $compname . "</td>";
                 }
                 if ($showEntity) {
                     echo "<td>" . (empty($data['entity']) ? $LANG['entity'][2] : $data['entity']) . "</td>";
                 }
                 echo "<td>" . $data['serial'] . "</td>";
                 echo "<td>" . $data['otherserial'] . "</td>";
                 echo "<td>" . $data['location'] . "</td>";
                 echo "<td>" . $data['state'] . "</td>";
                 echo "<td>" . $data['groupe'] . "</td>";
                 echo "<td>" . formatUserName($data['userid'], $data['username'], $data['userrealname'], $data['userfirstname'], $linkUser) . "</td>";
                 $lics = Computer_SoftwareLicense::GetLicenseForInstallation($data['cID'], $data['vID']);
                 echo "<td>";
                 if (count($lics)) {
                     foreach ($lics as $data) {
                         echo "<a href='softwarelicense.form.php?id=" . $data['id'] . "'>" . $data['name'];
                         echo "</a> - " . $data['serial'];
                         if (!empty($data['type'])) {
                             echo "&nbsp;(" . $data['type'] . ")";
                         }
                         echo "<br>";
                     }
                 }
                 echo "</td>";
                 echo "</tr>\n";
             } while ($data = $DB->fetch_assoc($result));
             echo "</table>\n";
             if ($canedit) {
                 openArrowMassive("softinstall" . $rand . "", true);
                 SoftwareVersion::dropdown(array('name' => 'versionID', 'softwares_id' => $softwares_id));
                 echo "&nbsp;<input type='submit' name='moveinstalls' value='" . $LANG['buttons'][20] . "' class='submit'>&nbsp;";
                 closeArrowMassive('deleteinstalls', $LANG['buttons'][6]);
                 echo "</form>";
             }
         } else {
             // Not found
             echo $LANG['search'][15];
         }
     }
     // Query
     echo "</div>\n";
 }
/** Generate bigdump : generate items for an entity
 *
 * @param $ID_entity entity ID
**/
function generate_entity($ID_entity) {
   global $MAX, $DB, $percent, $FIRST, $LAST, $MAX_KBITEMS_BY_CAT, $MAX_DISK,
         $DOCUMENTS, $NET_PORT, $NET_LOC;

   regenerateTreeCompleteName("glpi_entities");

   $current_year = date("Y");


   // DOMAIN
   $items = array("SP2MI", "CAMPUS"," IUT86", "PRESIDENCE", "CEAT", "D'omaine");
   $dp    = new Domain();
   $FIRST["domain"] = getMaxItem("glpi_domains")+1;

   for ($i=0 ; $i<$MAX['domain'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "domain $ID_entity '$i";
      }
      $dp->add(toolbox::addslashes_deep(array('name'         => $val,
                                              'entities_id'  => $ID_entity,
                                              'is_recursive' => 1,
                                              'comment'      => "comment $val")));
   }
   $LAST["domain"] = getMaxItem("glpi_domains");


   // STATUS
   $items = array("Reparation", "En stock", "En fonction", "Retour SAV", "En attente d'");
   $dp    = new State();
   $FIRST["state"] = getMaxItem("glpi_states")+1;
   for ($i=0 ; $i<$MAX['state'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "State $ID_entity '$i";
      }
      $state_id = $dp->add(toolbox::addslashes_deep(array('name'         => $val,
                                                          'entities_id'  => $ID_entity,
                                                          'is_recursive' => 1,
                                                          'comment'      => "comment $val")));

      // generate sub status
      for ($j=0 ; $j<$MAX['state'] ; $j++) {
         $val2 = "Sub $val $j";

         $dp->add(toolbox::addslashes_deep(array('name'         => $val2,
                                                 'entities_id'  => $ID_entity,
                                                 'is_recursive' => 1,
                                                 'states_id'    => $state_id,
                                                 'comment'      => "comment $val")));
      }

   }
   $LAST["state"]      = getMaxItem("glpi_states");


   // glpi_groups
   $FIRST["groups"] = getMaxItem("glpi_groups")+1;
   $group           = new Group();
   for ($i=0 ; $i<$MAX['groups'] ; $i++) {
      $gID = $group->add(toolbox::addslashes_deep(
                         array('entities_id'  => $ID_entity,
                               'name'         => "group d'$i",
                               'comment'      => "comment group d'$i",
                               'is_assign'    => 0)));

      // Generate sub group
      for ($j=0 ; $j<$MAX['groups'] ; $j++) {
         $group->add(toolbox::addslashes_deep(
                     array('entities_id'  => $ID_entity,
                           'name'         => "subgroup d'$j",
                           'comment'      => "comment subgroup d'$j of group $i",
                           'groups_id'    => $gID,
                           'is_assign'    => 0)));
      }
   }

   $LAST["groups"]      = getMaxItem("glpi_groups");

   $FIRST["techgroups"] = $LAST["groups"]+1;

   for ($i=0 ; $i<$MAX['groups'] ; $i++) {
         $group->add(toolbox::addslashes_deep(
                     array('entities_id'  => $ID_entity,
                           'name'         => "tech group d'$i",
                           'comment'      => "comment tech group d'$i")));
   }

   $LAST["techgroups"] = getMaxItem("glpi_groups");
   regenerateTreeCompleteName("glpi_groups");


   // glpi_users
   $FIRST["users_sadmin"] = getMaxItem("glpi_users")+1;
   $user                  = new User();
   $gu                    = new Group_User();
   for ($i=0 ; $i<$MAX['users_sadmin'] ; $i++) {
      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "sadmin$i-$ID_entity",
                                   'password'           => "sadmin'$i",
                                   'password2'          => "sadmin'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "sadmin '$i name",
                                   'firstname'          => "sadmin '$i firstname",
                                   'comment'            => "comment' $i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 4,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1
                                   )));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups'])));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['techgroups'], $LAST['techgroups'])));
   }
   $LAST["users_sadmin"] = getMaxItem("glpi_users");
   $FIRST["users_admin"] = getMaxItem("glpi_users")+1;

   for ($i=0 ; $i<$MAX['users_admin'] ; $i++) {

      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "admin$i-$ID_entity",
                                   'password'           => "admin'$i",
                                   'password2'          => "admin'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "admin$i 'name",
                                   'firstname'          => "admin$i 'firstname",
                                   'comment'            => "comment '$i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 3,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1)));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups']),
                     'is_manager'   => 1,
                     'is_delegate'  => 1));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['techgroups'], $LAST['techgroups']),
                     'is_manager'   => 1,
                     'is_delegate'  => 1));
   }

   $LAST["users_admin"]   = getMaxItem("glpi_users");
   $FIRST["users_normal"] = getMaxItem("glpi_users")+1;

   for ($i=0 ; $i<$MAX['users_normal'] ; $i++) {
      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "normal$i-$ID_entity",
                                   'password'           => "normal'$i",
                                   'password2'          => "normal'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "normal$i 'name",
                                   'firstname'          => "normal$i 'firstname",
                                   'comment'            => "comment '$i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 2,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1)));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups'])));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['techgroups'], $LAST['techgroups'])));
   }

   $LAST["users_normal"]    = getMaxItem("glpi_users");
   $FIRST["users_postonly"] = getMaxItem("glpi_users")+1;

   for ($i=0 ; $i<$MAX['users_postonly'] ; $i++) {
      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "postonly$i-$ID_entity",
                                   'password'           => "postonly'$i",
                                   'password2'          => "postonly'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "postonly$i 'name",
                                   'firstname'          => "postonly$i 'firstname",
                                   'comment'            => "comment' $i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 1,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1)));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups'])));
   }

   $LAST["users_postonly"] = getMaxItem("glpi_users");


   $FIRST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories")+1;
   $kbc                   = new KnowbaseItemCategory();

   for ($i=0 ; $i<max(1,pow($MAX['kbcategories'],1/3)) ; $i++) {
      $newID = $kbc->add(toolbox::addslashes_deep(
                         array('entities_id'     => $ID_entity,
                               'is_recursive'    => 1,
                               'name'            => "entity ' categorie $i",
                               'comment'         => "comment ' categorie $i")));

      for ($j=0 ; $j<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $j++) {
         $newID2 = $kbc->add(toolbox::addslashes_deep(
                             array('entities_id'                 => $ID_entity,
                                   'is_recursive'                => 1,
                                   'name'                        => "entity s-categorie '$j",
                                   'comment'                     => "comment s-categorie '$j",
                                   'knowbaseitemcategories_id'   => $newID)));

         for ($k=0 ; $k<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $k++) {
            $newID2 = $kbc->add(toolbox::addslashes_deep(
                                array('entities_id'               => $ID_entity,
                                      'is_recursive'              => 1,
                                      'name'                      => "entity ss-categorie' $k",
                                      'comment'                   => "comment ss-categorie' $k",
                                      'knowbaseitemcategories_id' => $newID2)));
         }
      }
   }

   $query = "OPTIMIZE TABLE `glpi_knowbaseitemcategories`";
   $DB->query($query) or die("PB REQUETE ".$query);

   regenerateTreeCompleteName("glpi_knowbaseitemcategories");
   $LAST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories");


   // LOCATIONS
   $added              = 0;
   $FIRST["locations"] = getMaxItem("glpi_locations")+1;
   $loc                = new Location();
   for ($i=0 ; $i<pow($MAX['locations'],1/5)&&$added<$MAX['locations'] ; $i++) {
      $added++;
      $newID = $loc->add(toolbox::addslashes_deep(
                         array('entities_id'     => $ID_entity,
                               'is_recursive'    => 1,
                               'name'            => "location' $i",
                               'comment'         => "comment 'location $i",
                               'building'        => "building $i")));

      for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) {
         $added++;
         $newID2 = $loc->add(toolbox::addslashes_deep(
                             array('entities_id'     => $ID_entity,
                                   'is_recursive'    => 1,
                                   'name'            => "s-location '$j",
                                   'comment'         => "comment s-location '$j",
                                   'building'        => "building $i",
                                   'room'            => "stage '$j",
                                   'locations_id'    => $newID)));

         for ($k=0 ; $k<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $k++) {
            $added++;
            $newID3 = $loc->add(toolbox::addslashes_deep(
                                array('entities_id'     => $ID_entity,
                                      'is_recursive'    => 1,
                                      'name'            => "ss-location '$k",
                                      'comment'         => "comment ss-location' $k",
                                      'building'        => "building $i",
                                      'room'            => "part' $k",
                                      'locations_id'    => $newID2)));

            for ($l=0 ; $l<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $l++) {
               $added++;
               $newID4 = $loc->add(toolbox::addslashes_deep(
                                   array('entities_id'     => $ID_entity,
                                         'is_recursive'    => 1,
                                         'name'            => "sss-location' $l",
                                         'comment'         => "comment sss-location' $l",
                                         'building'        => "building $i",
                                         'room'            => "room' $l",
                                         'locations_id'    => $newID3)));

               for ($m=0 ; $m<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $m++) {
                  $added++;
                  $newID5 = $loc->add(toolbox::addslashes_deep(
                                      array('entities_id'     => $ID_entity,
                                            'is_recursive'    => 1,
                                            'name'            => "ssss-location' $m",
                                            'comment'         => "comment ssss-location' $m",
                                            'building'        => "building $i",
                                            'room'            => "room' $l-$m",
                                            'locations_id'    => $newID4)));
               }
            }
         }
      }
   }

   $query = "OPTIMIZE TABLE `glpi_locations`";
   $DB->query($query) or die("PB REQUETE ".$query);

   regenerateTreeCompleteName("glpi_locations");
   $LAST["locations"]=getMaxItem("glpi_locations");


   // Task categories
   $added                 = 0;
   $FIRST["taskcategory"] = getMaxItem("glpi_taskcategories")+1;
   $tc                    = new TaskCategory();
   for ($i=0 ; $i<pow($MAX['taskcategory'],1/5)&&$added<$MAX['taskcategory'] ; $i++) {
      $added++;
      $newID = $tc->add(toolbox::addslashes_deep(
                        array('entities_id'     => $ID_entity,
                              'is_recursive'    => 1,
                              'name'            => "ent$ID_entity taskcategory' $i",
                              'comment'         => "comment ent$ID_entity taskcategory' $i")));

      for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) {
         $newID2 = $tc->add(toolbox::addslashes_deep(
                            array('entities_id'        => $ID_entity,
                                  'is_recursive'       => 1,
                                  'name'               => "ent$ID_entity taskcategory' $i",
                                  'comment'            => "comment ent$ID_entity taskcategory' $i",
                                  'taskcategories_id'  => $newID)));
         $added++;
      }
   }

   $query = "OPTIMIZE TABLE `glpi_taskcategories`";
   $DB->query($query) or die("PB REQUETE ".$query);

   regenerateTreeCompleteName("glpi_taskcategories");
   $LAST["taskcategory"] = getMaxItem("glpi_taskcategories");

   $ic = new ItilCategory();
   // Specific ticket categories
   $newID = $ic->add(toolbox::addslashes_deep(
                     array('entities_id'     => $ID_entity,
                           'is_recursive'    => 1,
                           'name'            => "category for entity' $ID_entity",
                           'comment'         => "comment category for entity' $ID_entity",
                           'users_id'        => mt_rand($FIRST['users_sadmin'],$LAST['users_admin']),
                           'groups_id'       => mt_rand($FIRST['techgroups'],$LAST['techgroups']),
                           'tickettemplates_id_incident' => 1,
                           'tickettemplates_id_demand'   => 1)));

   for ($i=0 ; $i<max(1,pow($MAX['tracking_category'],1/3)) ; $i++) {
      $ic->add(toolbox::addslashes_deep(
               array('entities_id'                 => $ID_entity,
                     'is_recursive'                => 1,
                     'name'                        => "scategory for entity' $ID_entity",
                     'comment'                     => "comment scategory for entity' $ID_entity",
                     'users_id'                    => mt_rand($FIRST['users_sadmin'],
                                                              $LAST['users_admin']),
                     'groups_id'                   => mt_rand($FIRST['techgroups'],
                                                              $LAST['techgroups']),
                     'tickettemplates_id_incident' => 1,
                     'tickettemplates_id_demand'   => 1,
                     'itilcategories_id'           => $newID)));
   }

   regenerateTreeCompleteName("glpi_itilcategories");

   $FIRST["solutiontypes"] = getMaxItem("glpi_solutiontypes")+1;

   $items = array("d'après KB");
   $st    = new SolutionType();
   for ($i=0 ; $i<$MAX['solutiontypes'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "type de solution ' $i";
      }
      $st->add(toolbox::addslashes_deep(array('name'         => $val,
                                              'comment'      => "comment $val",
                                              'entities_id'  => $ID_entity,
                                              'is_recursive' => 1)));
   }
   $LAST["solutiontypes"] = getMaxItem("glpi_solutiontypes");


   $FIRST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates")+1;
   $nb_items                   = mt_rand(0,$MAX['solutiontemplates']);
   $st                         = new SolutionTemplate();
   for ($i=0 ; $i<$nb_items ; $i++) {
      $st-> add(toolbox::addslashes_deep(
                array('entities_id'        => $ID_entity,
                      'is_recursive'       => 1,
                      'name'               => "solution' $i-$ID_entity",
                      'content'            => "content solution' $i-$ID_entity",
                      'solutiontypes_id'   => mt_rand(0,$MAX['solutiontypes']),
                      'comment'            => "comment solution' $i-$ID_entity")));
   }

   $LAST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates");

   // Add Specific questions
   $k                = 0;
   $FIRST["kbitems"] = getMaxItem("glpi_knowbaseitems")+1;
   $ki               = new KnowbaseItem();
   $eki              = new Entity_KnowbaseItem();
   for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) {
      $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT);
      for ($j=0 ; $j<$nb ; $j++) {
         $k++;
         $newID = $ki->add(toolbox::addslashes_deep(
                           array('knowbaseitemcategories_id'   => $i,
                                 'name'      => "Entity' $ID_entity Question $k",
                                 'answer'    => "Answer' $k".Toolbox::getRandomString(50),
                                 'is_faq'    => mt_rand(0,1),
                                 'users_id'  => mt_rand($FIRST['users_sadmin'],
                                                        $LAST['users_admin']))));

         $eki->add(array('entities_id'       => $ID_entity,
                        'knowbaseitems_id'   => $newID,
                        'is_recursive'       => 0));
      }
   }


   // Add global questions
   for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) {
      $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT);
      for ($j=0 ; $j<$nb ; $j++) {
         $k++;
         $newID = $ki->add(toolbox::addslashes_deep(
                           array('knowbaseitemcategories_id'   => $i,
                                 'name'      => "Entity' $ID_entity Recursive Question $k",
                                 'answer'    => "Answer' $k".Toolbox::getRandomString(50),
                                 'is_faq'    => mt_rand(0,1),
                                 'users_id'  => mt_rand($FIRST['users_sadmin'],
                                                        $LAST['users_admin']))));

         $eki->add(array('entities_id'       => $ID_entity,
                        'knowbaseitems_id'   => $newID,
                        'is_recursive'       => 1));
      }
   }

   $LAST["kbitems"] = getMaxItem("glpi_knowbaseitems");


   // Ajout documents  specific
   $FIRST["document"] = getMaxItem("glpi_documents")+1;
   $doc               = new Document();
   for ($i=0 ; $i<$MAX['document'] ; $i++) {
      $link = "";
      if (mt_rand(0,100)<50) {
         $link = "http://linktodoc/doc$i";
      }

      $docID = $doc->add(toolbox::addslashes_deep(
                         array('entities_id'           => $ID_entity,
                               'is_recursive'          => 0,
                               'name'                  => "document' $i-$ID_entity",
                               'documentcategories_id' => mt_rand(1,$MAX['rubdocs']),
                               'comment'               => "commen't $i",
                               'link'                  => $link,
                               'notepad'               => "notes document' $i")));

      $DOCUMENTS[$docID] = $ID_entity."-0";
   }


   // Global ones
   for ($i=0 ; $i<$MAX['document']/2 ; $i++) {
      $link = "";
      if (mt_rand(0,100)<50) {
         $link = "http://linktodoc/doc$i";
      }

      $docID = $doc->add(toolbox::addslashes_deep(
                         array('entities_id'           => $ID_entity,
                               'is_recursive'          => 1,
                               'name'                  => "Recursive document' $i-$ID_entity",
                               'documentcategories_id' => mt_rand(1,$MAX['rubdocs']),
                               'comment'               => "comment' $i",
                               'link'                  => $link,
                               'notepad'               => "notes document' $i")));

      $DOCUMENTS[$docID] = $ID_entity."-1";
   }

   $LAST["document"] = getMaxItem("glpi_documents");


   // Ajout budgets  specific
   $FIRST["budget"] = getMaxItem("glpi_budgets")+1;
   $b               = new Budget();
   for ($i=0 ; $i<$MAX['budget'] ; $i++) {
      $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
      $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans

      $b->add(toolbox::addslashes_deep(
              array('name'         => "budget' $i-$ID_entity",
                    'entities_id'  => $ID_entity,
                    'is_recusive'  => 0,
                    'comment'      => "comment' $i-$ID_entity",
                    'begin_date'   => date("Y-m-d",intval($date1)),
                    'end_date'     => date("Y-m-d",intval($date2)))));
   }
   $LAST["budget"] = getMaxItem("glpi_budgets");

   // GLobal ones
   for ($i=0 ; $i<$MAX['document']/2 ; $i++) {
      $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
      $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans

      $b->add(toolbox::addslashes_deep(
              array('name'         => "Recursive budget' $i-$ID_entity",
                    'entities_id'  => $ID_entity,
                    'is_recusive'  => 1,
                    'comment'      => "comment' $i-$ID_entity",
                    'begin_date'   => date("Y-m-d",intval($date1)),
                    'end_date'     => date("Y-m-d",intval($date2)))));

   }
   $LAST["document"] = getMaxItem("glpi_documents");


   // glpi_suppliers
   $items                = array("DELL", "IBM", "ACER", "Microsoft", "Epson", "Xerox",
                                 "Hewlett Packard", "Nikon", "Targus", "LG", "Samsung", "Lexmark");
   $FIRST["enterprises"] = getMaxItem("glpi_suppliers")+1;
   $ent                  = new Supplier();

   // Global ones
   for ($i=0 ; $i<$MAX['enterprises']/2 ; $i++) {
      if (isset($items[$i])) {
         $val = "Recursive ".$items[$i];
      } else {
         $val = "Recursive enterprise_".$i."_ID_entity";
      }
      $entID = $ent->add(toolbox::addslashes_deep(
                         array('entities_id'        => $ID_entity,
                               'is_recursive'       => 1,
                               'name'               => "Recursive' $val-$ID_entity",
                               'suppliertypes_id'   => mt_rand(1,$MAX['enttype']),
                               'address'            => "address' $i",
                               'postcode'           => "postcode $i",
                               'town'               => "town' $i",
                               'state'              => "state' $i",
                               'country'            => "country $i",
                               'website'            => "http://www.$val.com/",
                               'fax'                => "fax $i",
                               'email'              => "info@ent$i.com",
                               'notepad'            => "notes enterprises' $i")));

      addDocuments('Supplier', $entID);
   }


   // Specific ones
   for ($i=0 ; $i<$MAX['enterprises'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "enterprise_".$i."_ID_entity";
      }

      $entID = $ent->add(toolbox::addslashes_deep(
                         array('entities_id'        => $ID_entity,
                               'is_recursive'       => 0,
                               'name'               => "'$val-$ID_entity",
                               'suppliertypes_id'   => mt_rand(1,$MAX['enttype']),
                               'address'            => "address' $i",
                               'postcode'           => "postcode $i",
                               'town'               => "town' $i",
                               'state'              => "state' $i",
                               'country'            => "country $i",
                               'website'            => "http://www.$val.com/",
                               'fax'                => "fax $i",
                               'email'              => "info@ent$i.com",
                               'notepad'            => "notes supplier' $i",
                               'comment'            => "comment supplier' $i")));

      addDocuments('Supplier', $entID);
   }
   $LAST["enterprises"] = getMaxItem("glpi_suppliers");


   // Ajout contracts
   $FIRST["contract"] = getMaxItem("glpi_contracts")+1;
   $c                 = new Contract();
   $cs                = new Contract_Supplier();
   $cc                = new ContractCost();
   // Specific
   for ($i=0 ; $i<$MAX['contract'] ; $i++) {
      $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28);
      $contractID = $c->add(toolbox::addslashes_deep(
                            array('entities_id'        => $ID_entity,
                                  'is_recursive'       => 0,
                                  'name'               => "contract' $i-$ID_entity",
                                  'num'                => "num' $i",
                                  'contracttypes_id'   => mt_rand(1,$MAX['contract_type']),
                                  'begin_date'         => $date,
                                  'duration'           => mt_rand(1,36),
                                  'notice'             => mt_rand(1,3),
                                  'periodicity'        => mt_rand(1,36),
                                  'billing'            => mt_rand(1,36),
                                  'comment'            => "comment' $i",
                                  'accounting_number'  => "compta num' $i",
                                  'renewal'            => 1)));

      addDocuments('Contract', $contractID);

      // Add an enterprise
      $cs->add(array('contracts_id' => $contractID,
                     'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"])));
      // Add a cost
      $cc->add(toolbox::addslashes_deep(
               array('contracts_id' => $contractID,
                     'cost'         => mt_rand(100,10000),
                     'name'         => "Initial 'cost",
                     'begin_date'   => $date,
                     'budgets_id'   => mt_rand($FIRST['budget'], $LAST['budget']))));
   }

   for ($i=0 ; $i<$MAX['contract']/2 ; $i++) {
      $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28);

      $contractID = $c->add(toolbox::addslashes_deep(
                            array('entities_id'        => $ID_entity,
                                  'is_recursive'       => 1,
                                  'name'               => "Recursive contract' $i-$ID_entity",
                                  'num'                => "num' $i",
                                  'cost'               => mt_rand(100,10000),
                                  'contracttypes_id'   => mt_rand(1,$MAX['contract_type']),
                                  'begin_date'         => $date,
                                  'duration'           => mt_rand(1,36),
                                  'notice'             => mt_rand(1,3),
                                  'periodicity'        => mt_rand(1,36),
                                  'billing'            => mt_rand(1,36),
                                  'comment'            => "comment' $i",
                                  'accounting_number'  => "compta num' $i",
                                  'renewal'            => 1)));

      addDocuments('Contract', $contractID);

      // Add an enterprise
      $cs->add(array('contracts_id' => $contractID,
                     'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"])));
   }
   $LAST["contract"] = getMaxItem("glpi_contracts");


   // Ajout contacts
   $prenoms = array("Jean", "John", "Louis", "Pierre", "Auguste",
                    "Albert", "Julien", "Guillaume", "Bruno",
                    "Maurice", "Francois", "Laurent", "Richard",
                    "Henri", "Clement", "d'avy");
   $noms    = array("Dupont", "Smith", "Durand", "Martin", "Dubois",
                    "Dufour", "Dupin", "Duval", "Petit", "Grange",
                    "Bernard", "Bonnet", "Richard", "Leroy",
                    "Dumont", "Fontaine", "d'orleans");


   $FIRST["contacts"] = getMaxItem("glpi_contacts")+1;
   $c                 = new Contact();
   $cs                = new Contact_Supplier();
   for ($i=0 ; $i<$MAX['contacts'] ; $i++) {
      if (isset($noms[$i])) {
         $val = $noms[$i];
      } else {
         $val = "name $i";
      }
      if (isset($prenoms[$i])) {
         $val2 = $prenoms[$i];
      } else {
         $val2 = "firstname $i";
      }

      $contactID = $c->add(toolbox::addslashes_deep(
                           array('entities_id'        => $ID_entity,
                                 'is_recursive'       => 0,
                                 'name'               => "$val-$ID_entity",
                                 'firstname'          => $val2,
                                 'contacttypes_id'    => mt_rand(1,$MAX['contact_type']),
                                 'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                 'phone'              => "phone $i",
                                 'phone2'             => "phone2 $i",
                                 'mobile'             => "mobile $i",
                                 'fax'                => "fax $i",
                                 'email'              => "email $i",
                                 'address'            => "address' $i",
                                 'postcode'           => "postcode $i",
                                 'town'               => "town' $i",
                                 'state'              => "state' $i",
                                 'country'            => "country $i",
                                 'comment'            => "Comment' $i")));

      // Link with enterprise
      $cs->add(array('contacts_id'  => $contactID,
                     'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises'])));
   }

   for ($i=0 ; $i<$MAX['contacts']/2 ; $i++) {
      if (isset($items[$i])) {
         $val = "Recursive ".$items[$i];
      } else {
         $val = "Recursive contact $i";
      }
      $contactID = $c->add(toolbox::addslashes_deep(
                           array('entities_id'        => $ID_entity,
                                 'is_recursive'       => 0,
                                 'name'               => "$val'-$ID_entity",
                                 'contacttypes_id'    => mt_rand(1,$MAX['contact_type']),
                                 'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                 'phone'              => "phone $i",
                                 'phone2'             => "phone2 $i",
                                 'mobile'             => "mobile $i",
                                 'fax'                => "fax $i",
                                 'email'              => "email $i",
                                 'address'            => "address' $i",
                                 'postcode'           => "postcode $i",
                                 'town'               => "town' $i",
                                 'state'              => "state' $i",
                                 'country'            => "country $i",
                                 'comment'            => "Comment' $i")));

      // Link with enterprise
      $cs->add(array('contacts_id'  => $contactID,
                     'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises'])));
   }
   $LAST["contacts"] = getMaxItem("glpi_contacts");


   // TYPE DE CONSOMMABLES
   $FIRST["type_of_consumables"] = getMaxItem("glpi_consumableitems")+1;
   $ci                           = new Consumableitem();

   for ($i=0 ; $i<$MAX['type_of_consumables'] ; $i++) {
      $consID = $ci->add(toolbox::addslashes_deep(
                         array('entities_id'             => $ID_entity,
                               'is_recursive'            => mt_rand(0,1),
                               'name'                    => "consumable type' $i",
                               'ref'                     => "ref d' $i",
                               'locations_id'            => mt_rand($FIRST["locations"],
                                                                    $LAST['locations']),
                               'consumableitemtypes_id'  => mt_rand(0,$MAX['consumable_type']),
                               'manufacturers_id'        => mt_rand(1,$MAX['manufacturer']),
                               'users_id_tech'           => mt_rand($FIRST['users_sadmin'],
                                                                    $LAST['users_admin']),
                               'groups_id_tech'          => mt_rand($FIRST["groups"], $LAST["groups"]),
                               'comment'                 => "comment' $i",
                               'notepad'                 => "notes consumableitem' $i",
                               'alarm_threshold'         => mt_rand(0,10))));

      addDocuments('ConsumableItem', $consID);


      // AJOUT INFOCOMS
      addInfocoms('ConsumableItem', $consID, $ID_entity);

      // Ajout consommable en stock
      $c = new Consumable();
      for ($j=0 ; $j<mt_rand(0,$MAX['consumables_stock']) ; $j++) {
         $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28);

         $ID = $c->add(array('entities_id'        => $ID_entity,
                             'consumableitems_id' => $consID,
                             'date_in'            => $date));

         // AJOUT INFOCOMS
         addInfocoms('Consumable', $ID, $ID_entity);
      }


      // Ajout consommable donne
      for ($j=0 ; $j<mt_rand(0,$MAX['consumables_given']) ; $j++) {
         $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28);

         $ID = $c->add(array('entities_id'        => $ID_entity,
                             'consumableitems_id' => $consID,
                             'date_in'            => $date,
                             'date_out'           => date("Y-m-d")));

         // AJOUT INFOCOMS
         addInfocoms('Consumable', $ID, $ID_entity);

      }

   }
   $LAST["type_of_consumables"] = getMaxItem("glpi_consumableitems");


   // TYPE DE CARTOUCHES
   $FIRST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems")+1;
   $ct                          = new CartridgeItem();

   for ($i=0 ; $i<$MAX['type_of_cartridges'] ; $i++) {
      $cartID = $ct->add(toolbox::addslashes_deep(
                         array('entities_id'       => $ID_entity,
                               'is_recursive'      => mt_rand(0,1),
                               'name'              => "cartridge ' type $i",
                               'ref'               => "ref '$i",
                               'locations_id'      => mt_rand($FIRST["locations"], $LAST['locations']),
                               'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                               'users_id_tech'     => mt_rand($FIRST['users_sadmin'],
                                                              $LAST['users_admin']),
                               'groups_id_tech'    => mt_rand($FIRST["groups"], $LAST["groups"]),
                               'comment'           => "comment '$i",
                               'notepad'           => "notes cartridgeitem '$i",
                               'alarm_threshold'   => mt_rand(0,10))));

      addDocuments('CartridgeItem', $cartID);


      // AJOUT INFOCOMS
      addInfocoms('CartridgeItem', $cartID, $ID_entity);

      $c    = new Cartridge();
      $cipm = new CartridgeItem_PrinterModel();
      // Ajout cartouche en stock
      for ($j=0 ; $j<mt_rand(0,$MAX['cartridges_stock']) ; $j++) {
         $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28);

         $ID = $c->add(array('entities_id'         => $ID_entity,
                             'cartridgeitems_id'   => $cartID,
                             'date_in'             => $date));

         // AJOUT INFOCOMS
         addInfocoms('Cartridge', $ID, $ID_entity);

      }

      // Assoc printer type to cartridge type
      $cipm->add(array('cartridgeitems_id'  => $cartID,
                       'printermodels_id'   => mt_rand(1,$MAX['type_printers']),
                     ));
   }
   $LAST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems");


   // Networking
   $NET_LOC             = array();
   $FIRST["networking"] = getMaxItem("glpi_networkequipments")+1;
   $FIRST["printers"]   = getMaxItem("glpi_printers")+1;
   $ne                  = new NetworkEquipment();
   $p                   = new Printer();
   $np                  = new Netpoint();
   $c                   = new Cartridge();

   foreach ($DB->request('glpi_locations') as $data) {
      $i          = $data["id"];
      $techID     = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $gtechID    = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);
      $infoIP     = getNextIP();
      $domainID   = mt_rand($FIRST['domain'],$LAST['domain']);
      $networkID  = mt_rand(1,$MAX['network']);

      // insert networking

      $netwID = $ne->add(toolbox::addslashes_deep(
                         array('entities_id'                   => $ID_entity,
                               'name'                          => "networking '$i-$ID_entity",
                               'ram'                           => mt_rand(32,256),
                               'serial'                        => Toolbox::getRandomString(10),
                               'otherserial'                   => Toolbox::getRandomString(10),
                               'contact'                       => "contact '$i",
                               'contact_num'                   => "num '$i",
                               'users_id_tech'                 => $techID,
                               'groups_id_tech'                => $gtechID,
                               'comment'                       => "comment '$i",
                               'locations_id'                  => $i,
                               'domains_id'                    => $domainID,
                               'networks_id'                   => $networkID,
                               'networkequipmenttypes_id'      => mt_rand(1,$MAX['type_networking']),
                               'networkequipmentmodels_id'     => mt_rand(1,$MAX['model_networking']),
                               'networkequipmentfirmwares_id'  => mt_rand(1,$MAX['firmware']),
                               'manufacturers_id'              => mt_rand(1,$MAX['enterprises']),
                               'mac'                           => getNextMAC(),
                               'ip'                            => $infoIP["ip"],
                               'notepad'                       => "notes networking '$i",
                               'users_id'                      => mt_rand($FIRST['users_sadmin'],
                                                                          $LAST['users_admin']),
                               'groups_id'                     => mt_rand($FIRST["groups"],
                                                                          $LAST["groups"]),
                               'states_id'                     => (mt_rand(0,100)<$percent['state']
                                                                     ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));
      $NET_LOC[$data['id']] = $netwID;
      addDocuments('NetworkEquipment', $netwID);
      addContracts('NetworkEquipment', $netwID);

      // AJOUT INFOCOMS
      addInfocoms('NetworkEquipment', $netwID, $ID_entity);

      // Link with father
      addNetworkEthernetPort('NetworkEquipment', $netwID, $ID_entity, $i);

      // Ajout imprimantes reseaux : 1 par loc + connexion d un matos reseau + ajout de cartouches
      // Add trackings
      addTracking('NetworkEquipment', $netwID, $ID_entity);

      $typeID  = mt_rand(1,$MAX['type_printers']);
      $modelID = mt_rand(1,$MAX['model_printers']);
      $recur   = mt_rand(0,1);

      $printID = $p->add(toolbox::addslashes_deep(
                         array('entities_id'      => $ID_entity,
                                'is_recursive'     => $recur,
                                'name'             => "printer of loc '$i",
                                'serial'           => Toolbox::getRandomString(10),
                                'otherserial'      => Toolbox::getRandomString(10),
                                'contact'          => "contact '$i",
                                'contact_num'      => "num' $i",
                                'users_id_tech'    => $techID,
                                'groups_id_tech'   => $gtechID,
                                'have_serial'      => mt_rand(0,1),
                                'have_parallel'    => mt_rand(0,1),
                                'have_usb'         => mt_rand(0,1),
                                'have_wifi'        => mt_rand(0,1),
                                'have_ethernet'    => mt_rand(0,1),
                                'comment'          => "comment' $i",
                                'memory_size'      => mt_rand(0,128),
                                'locations_id'     => $i,
                                'domains_id'       => $domainID,
                                'networks_id'      => $networkID,
                                'printertypes_id'  => $typeID,
                                'printermodels_id' => $modelID,
                                'manufacturers_id' => mt_rand(1,$MAX['enterprises']),
                                'is_global'        => 1,
                                'notepad'          => "notes printers '$i",
                                'users_id'         => mt_rand($FIRST['users_sadmin'],
                                                              $LAST['users_admin']),
                                'groups_id'        => mt_rand($FIRST["groups"], $LAST["groups"]),
                                'states_id'        => (mt_rand(0,100)<$percent['state']
                                                         ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));

      addDocuments('Printer', $printID);
      addContracts('Printer', $printID);

      // Add trackings
      addTracking('Printer', $printID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Printer', $printID, $ID_entity, $recur);

      // Add Cartouches
      // Get compatible cartridge
      $query = "SELECT `cartridgeitems_id`
                FROM `glpi_cartridgeitems_printermodels`
                WHERE `printermodels_id` = '$typeID'";
      $result2 = $DB->query($query) or die("PB REQUETE ".$query);

      if ($DB->numrows($result2)>0) {
         $ctypeID = $DB->result($result2,0,0) or die (" PB RESULT ".$query);
         $printed = 0;
         $oldnb   = mt_rand(1,$MAX['cartridges_by_printer']);
         $date1   = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
         $date2   = time();
         $inter   = abs(round(($date2-$date1)/$oldnb));

         // Add old cartridges
         for ($j=0 ; $j<$oldnb ; $j++) {
            $printed += mt_rand(0,5000);
            $c->add(array('entities_id'        => $ID_entity,
                          'cartridgeitems_id'  => $ctypeID,
                          'printers_id'        => $printID,
                          'date_in'            => date("Y-m-d",$date1),
                          'date_use'           => date("Y-m-d",$date1+$j*$inter),
                          'date_out'           => date("Y-m-d",$date1+($j+1)*$inter),
                          'pages'              => $printed));
         }

         // Add current cartridges
         $c->add(array('entities_id'        => $ID_entity,
                       'cartridgeitems_id'  => $ctypeID,
                       'printers_id'        => $printID,
                       'date_in'            => $date,
                       'date_use'           => date("Y-m-d",$date2)));
      }

      $iface = mt_rand(1,$MAX['iface']);

      // Add networking ports
      addNetworkEthernetPort('Printer', $printID, $ID_entity, $i);
   }
   unset($NET_LOC);
   $LAST["networking"] = getMaxItem("glpi_networkequipments");


   //////////// INVENTORY

   // glpi_computers
   $FIRST["computers"]   = getMaxItem("glpi_computers")+1;
   $FIRST["monitors"]    = getMaxItem("glpi_monitors")+1;
   $FIRST["phones"]      = getMaxItem("glpi_phones")+1;
   $FIRST["peripherals"] = getMaxItem("glpi_peripherals")+1;
   $c       = new Computer();
   $mon     = new Monitor();

   $cdevmb    = new Item_DeviceMotherBoard();
   $cdevproc  = new Item_DeviceProcessor();
   $cdevmem   = new Item_DeviceMemory();
   $cdevhd    = new Item_DeviceHardDrive();
   $cdevnc    = new Item_DeviceNetworkCard();
   $cdevdr    = new Item_DeviceDrive();
   $cdevcon   = new Item_DeviceControl();
   $cdevgc    = new Item_DeviceGraphicCard();
   $cdevsc    = new Item_DeviceSoundCard();
   $cdevpci   = new Item_DevicePci();
   $cdevcase  = new Item_DeviceCase();
   $cdevps    = new Item_DevicePowerSupply();

   $cdisk   = new ComputerDisk();
   $np      = new Netpoint();
   $ci      = new Computer_Item();
   $phone   = new Phone();
   $print   = new Printer();
   $periph  = new Peripheral();
   $cart    = new Cartridge();
   for ($i=0 ; $i<$MAX['computers'] ; $i++) {
      $loc       = mt_rand($FIRST["locations"],$LAST['locations']);
      $techID    = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $userID    = mt_rand($FIRST['users_normal'],$LAST['users_postonly']);
      $groupID   = mt_rand($FIRST["groups"],$LAST["groups"]);
      $gtechID   = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);
      $domainID  = mt_rand($FIRST['domain'],$LAST['domain']);
      $networkID = mt_rand(1,$MAX['network']);

      $compID = $c->add(toolbox::addslashes_deep(
                        array('entities_id'                    => $ID_entity,
                              'name'                           => "computer ' $i-$ID_entity",
                              'serial'                         => Toolbox::getRandomString(10),
                              'otherserial'                    => Toolbox::getRandomString(10),
                              'contact'                        => "contact' $i",
                              'contact_num'                    => "num' $i",
                              'users_id_tech'                  => $techID,
                              'groups_id_tech'                 => $gtechID,
                              'comment'                        => "comment' $i",
                              'operatingsystems_id'            => mt_rand(1,$MAX['os']),
                              'operatingsystemversions_id'     => mt_rand(1,$MAX['os_version']),
                              'operatingsystemservicepacks_id' => mt_rand(1,$MAX['os_sp']),
                              'os_license_number'              => "os sn $i",
                              'os_licenseid'                   => "os id $i",
                              'autoupdatesystems_id'           => mt_rand(1,$MAX['os_sp']),
                              'locations_id'                   => $loc,
                              'domains_id'                     => $domainID,
                              'networks_id'                    => $networkID,
                              'computertypes_id'               => mt_rand(1,$MAX['type_computers']),
                              'computermodels_id'              => mt_rand(1,$MAX['model']),
                              'manufacturers_id'               => mt_rand(1,$MAX['manufacturer']),
                              'is_global'                      => 1,
                              'notepad'                        => "notes computer '$i",
                              'users_id'                       => $userID,
                              'groups_id'                      => $groupID,
                              'states_id'                      => (mt_rand(0,100)<$percent['state']
                                                                     ?mt_rand($FIRST['state'],$LAST['state']):0),
                              'uuid'                           => Toolbox::getRandomString(30)
                           )));

      addDocuments('Computer', $compID);
      addContracts('Computer', $compID);

      $NET_PORT['Computer'][$compID] = 0;

      // Add trackings
      addTracking('Computer', $compID, $ID_entity);

      // Add reservation
      addReservation('Computer', $compID, $ID_entity);


      // AJOUT INFOCOMS
      addInfocoms('Computer', $compID, $ID_entity);

      // ADD DEVICE
      $cdevmb->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $max   = mt_rand(1,4);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevproc->addDevices(1, 'Computer', $compID, $devid,
                               array('serial' => Toolbox::getRandomString(15)));
      }
      $max   = mt_rand(1,4);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevmem->addDevices(1, 'Computer', $compID, $devid,
                              array('serial' => Toolbox::getRandomString(15)));
      }

      $max = mt_rand(1,2);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevhd->addDevices(1, 'Computer', $compID, $devid,
                             array('serial' => Toolbox::getRandomString(15)));
      }

      $cdevnc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15),
                                'mac'    => getNextMAC()));

      $cdevdr->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $cdevcon->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                           array('serial' => Toolbox::getRandomString(15)));

      $cdevgc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $cdevsc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $max = mt_rand(1,4);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevpci->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                              array('serial' => Toolbox::getRandomString(15)));
      }

      $cdevcase->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                            array('serial'=> Toolbox::getRandomString(15)));

      $max   = mt_rand(1,2);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevps->addDevices(1, 'Computer', $compID, $devid,
                             array('serial' => Toolbox::getRandomString(15)));
      }

      // insert disk
      $nb_disk = mt_rand(1,$MAX_DISK);
      for ($j=1 ; $j<=$nb_disk ; $j++) {
         $totalsize = mt_rand(10000,1000000);
         $freesize  = mt_rand(0,$totalsize);

         $cdisk->add(toolbox::addslashes_deep(
                      array('entities_id'     => $ID_entity,
                            'computers_id'    => $compID,
                            'name'            => "disk '$j",
                            'device'          => "/dev/disk$j",
                            'mountpoint'      => "/mnt/disk$j",
                            'filesystems_id'  => mt_rand(1,10),
                            'totalsize'       => $totalsize,
                            'freesize'        => $freesize)));
      }


      // Add networking ports
      addNetworkEthernetPort('Computer', $compID, $ID_entity, $loc);

      // Ajout d'un ecran sur l'ordi
      $monID = $mon->add(toolbox::addslashes_deep(
                         array('entities_id'       => $ID_entity,
                               'name'              => "monitor' $i-$ID_entity",
                               'serial'            => Toolbox::getRandomString(10),
                               'otherserial'       => Toolbox::getRandomString(10),
                               'contact'           => "contact' $i",
                               'contact_num'       => "num' $i",
                               'users_id_tech'     => $techID,
                               'groups_id_tech'    => $gtechID,
                               'comment'           => "comment' $i",
                               'size'              => mt_rand(14,22),
                               'have_micro'        => mt_rand(0,1),
                               'have_speaker'      => mt_rand(0,1),
                               'have_subd'         => mt_rand(0,1),
                               'have_bnc'          => mt_rand(0,1),
                               'have_dvi'          => mt_rand(0,1),
                               'have_pivot'        => mt_rand(0,1),
                               'have_hdmi'         => mt_rand(0,1),
                               'have_displayport'  => mt_rand(0,1),
                               'locations_id'      => $loc,
                               'monitortypes_id'   => mt_rand(1,$MAX['type_monitors']),
                               'monitormodels_id'  => mt_rand(1,$MAX['model_monitors']),
                               'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                               'notepad'           => "notes monitor' $i",
                               'users_id'          => $userID,
                               'groups_id'         => $groupID,
                               'states_id'         => (mt_rand(0,100)<$percent['state']
                                                         ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));

      addDocuments('Monitor', $monID);
      addContracts('Monitor', $monID);

      // Add trackings
      addTracking('Monitor', $monID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Monitor', $monID, $ID_entity);

      $ci->add(array('itemtype'     => 'Monitor',
                     'items_id'     => $monID,
                     'computers_id' => $compID,
      ));

      // Ajout d'un telephhone avec l'ordi
      $telID = $phone->add(toolbox::addslashes_deep(
                           array('entities_id'           => $ID_entity,
                                 'name'                  => "phone' $i-$ID_entity",
                                 'serial'                => Toolbox::getRandomString(10),
                                 'otherserial'           => Toolbox::getRandomString(10),
                                 'contact'               => "contact' $i",
                                 'contact_num'           => "num' $i",
                                 'users_id_tech'         => $techID,
                                 'groups_id_tech'        => $gtechID,
                                 'comment'               => "comment' $i",
                                 'firmware'              => Toolbox::getRandomString(10),
                                 'brand'                 => "brand' $i",
                                 'phonepowersupplies_id' => mt_rand(0,$MAX['phone_power']),
                                 'number_line'           => Toolbox::getRandomString(10),
                                 'have_headset'          => mt_rand(0,1),
                                 'have_hp'               => mt_rand(0,1),
                                 'locations_id'          => $loc,
                                 'phonetypes_id'         => mt_rand(1,$MAX['type_phones']),
                                 'phonemodels_id'        => mt_rand(1,$MAX['model_phones']),
                                 'manufacturers_id'      => mt_rand(1,$MAX['manufacturer']),
                                 'notepad'               => "notes phone' $i",
                                 'users_id'              => $userID,
                                 'groups_id'             => $groupID,
                                 'states_id'             => (mt_rand(0,100)<$percent['state']
                                                               ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));

      addDocuments('Phone', $telID);
      addContracts('Phone', $telID);

      // Add trackings
      addTracking('Phone', $telID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Phone', $telID, $ID_entity);

      $ci->add(array('itemtype'     => 'Phone',
                     'items_id'     => $telID,
                     'computers_id' => $compID));

      // Ajout des periphs externes en connection directe
      while (mt_rand(0,100)<$percent['peripherals']) {

         $periphID = $periph->add(toolbox::addslashes_deep(
                                  array('entities_id'       => $ID_entity,
                                        'name'              => "periph of comp' $i-$ID_entity",
                                        'serial'            => Toolbox::getRandomString(10),
                                        'otherserial'       => Toolbox::getRandomString(10),
                                        'contact'           => "contact' $i",
                                        'contact_num'       => "num' $i",
                                        'users_id_tech'     => $techID,
                                        'groups_id_tech'    => $gtechID,
                                        'comment'           => "comment' $i",
                                        'brand'             => "brand' $i",
                                        'locations_id'      => $loc,
                                        'phonetypes_id'     => mt_rand(1,$MAX['type_peripherals']),
                                        'phonemodels_id'    => mt_rand(1,$MAX['model_peripherals']),
                                        'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                                        'notepad'           => "notes peripheral' $i",
                                        'users_id'          => $userID,
                                        'groups_id'         => $groupID,
                                        'states_id'         => (mt_rand(0,100)<$percent['state']
                                                                  ?mt_rand($FIRST['state'],$LAST['state']):0)
                                    )));

         addDocuments('Peripheral', $periphID);
         addContracts('Peripheral', $periphID);

         // Add trackings
         addTracking('Peripheral', $periphID, $ID_entity);

         // Add connection
         $ci->add(array('itemtype'     => 'Peripheral',
                        'items_id'     => $periphID,
                        'computers_id' => $compID));
      }


      // Ajout d'une imprimante connection directe pour X% des computers + ajout de cartouches
      if (mt_rand(0,100)<=$percent['printer']) {
         // Add printer
         $typeID  = mt_rand(1,$MAX['type_printers']);
         $modelID = mt_rand(1,$MAX['model_printers']);

         $printID = $p->add(toolbox::addslashes_deep(
                            array('entities_id'       => $ID_entity,
                                  'name'              => "printer of comp' $i-$ID_entity",
                                  'serial'            => Toolbox::getRandomString(10),
                                  'otherserial'       => Toolbox::getRandomString(10),
                                  'contact'           => "contact' $i",
                                  'contact_num'       => "num' $i",
                                  'users_id_tech'     => $techID,
                                  'groups_id_tech'    => $gtechID,
                                  'have_serial'       => mt_rand(0,1),
                                  'have_parallel'     => mt_rand(0,1),
                                  'have_usb'          => mt_rand(0,1),
                                  'have_wifi'         => mt_rand(0,1),
                                  'have_ethernet'     => mt_rand(0,1),
                                  'comment'           => "comment' $i",
                                  'memory_size'       => mt_rand(0,128),
                                  'locations_id'      => $loc,
                                  'domains_id'        => $domainID,
                                  'networks_id'       => $networkID,
                                  'printertypes_id'   => $typeID,
                                  'printermodels_id'  => $modelID,
                                  'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                                  'notepad'           => "notes printers '$i",
                                  'users_id'          => mt_rand($FIRST['users_postonly'],
                                                                 $LAST['users_postonly']),
                                  'groups_id'         => mt_rand($FIRST["groups"], $LAST["groups"]),
                                  'states_id'         => (mt_rand(0,100)<$percent['state']
                                                            ?mt_rand($FIRST['state'],$LAST['state']):0)
                              )));

         addDocuments('Printer', $printID);
         addContracts('Printer', $printID);

         // Add trackings
         addTracking('Printer', $printID, $ID_entity);

         // Add connection
         $ci->add(array('itemtype'     => 'Printer',
                        'items_id'     => $printID,
                        'computers_id' => $compID));

         // AJOUT INFOCOMS
         addInfocoms('Printer', $printID, $ID_entity);

         // Add Cartouches
         // Get compatible cartridge
         $query = "SELECT `cartridgeitems_id`
                   FROM `glpi_cartridgeitems_printermodels`
                   WHERE `printermodels_id` = '$typeID'";
         $result = $DB->query($query) or die("PB REQUETE ".$query);

         if ($DB->numrows($result)>0) {
            $ctypeID = $DB->result($result,0,0) or die (" PB RESULT ".$query);
            $printed = 0;
            $oldnb   = mt_rand(1,$MAX['cartridges_by_printer']);
            $date1   = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
            $date2   = time();
            $inter   = round(($date2-$date1)/$oldnb);

            // Add old cartridges
            for ($j=0 ; $j<$oldnb ; $j++) {
               $printed += mt_rand(0,5000);
               $cart->add(array('entities_id'        => $ID_entity,
                                'cartridgeitems_id'  => $ctypeID,
                                'printers_id'        => $printID,
                                'date_in'            => date("Y-m-d",$date1),
                                'date_use'           => date("Y-m-d",$date1+$j*$inter),
                                'date_out'           => date("Y-m-d",$date1+($j+1)*$inter),
                                'pages'              => $printed));
            }

            // Add current cartridges
            $cart->add(array('entities_id'        => $ID_entity,
                             'cartridgeitems_id'  => $ctypeID,
                             'printers_id'        => $printID,
                             'date_in'            => date("Y-m-d",$date1),
                             'date_use'           => date("Y-m-d",$date2)));
         }
      }
   }

   $LAST["computers"] = getMaxItem("glpi_computers");
   $LAST["monitors"]  = getMaxItem("glpi_monitors");
   $LAST["phones"]    = getMaxItem("glpi_phones");


   // Add global peripherals
   $periph = new Peripheral();
   $ci     = new Computer_Item();
   for ($i=0 ; $i<$MAX['global_peripherals'] ; $i++) {
      $techID  = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);

      $periphID = $periph->add(toolbox::addslashes_deep(
                               array('entities_id'       => $ID_entity,
                                     'name'              => "periph '$i-$ID_entity",
                                     'serial'            => Toolbox::getRandomString(10),
                                     'otherserial'       => Toolbox::getRandomString(10),
                                     'contact'           => "contact' $i",
                                     'contact_num'       => "num' $i",
                                     'users_id_tech'     => $techID,
                                     'groups_id_tech'    => $gtechID,
                                     'comment'           => "comment' $i",
                                     'brand'             => "brand' $i",
                                     'locations_id'      => $loc,
                                     'phonetypes_id'     => mt_rand(1,$MAX['type_peripherals']),
                                     'phonemodels_id'    => mt_rand(1,$MAX['model_peripherals']),
                                     'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                                     'is_global'         => 1,
                                     'notepad'           => "notes peripheral' $i",
                                     'users_id'          => mt_rand($FIRST['users_normal'],
                                                                    $LAST['users_normal']),
                                     'groups_id'         => mt_rand($FIRST["groups"], $LAST["groups"]),
                                     'states_id'         => (mt_rand(0,100)<$percent['state']
                                                               ?mt_rand($FIRST['state'],$LAST['state']):0)
                                 )));

      addDocuments('Peripheral', $periphID);
      addContracts('Peripheral', $periphID);

      // Add trackings
      addTracking('Peripheral', $periphID, $ID_entity);

      // Add reservation
      addReservation('Peripheral', $periphID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Peripheral', $periphID, $ID_entity);

      // Add connections
      $val = mt_rand(1,$MAX['connect_for_peripherals']);
      for ($j=1 ; $j<$val ; $j++) {
         $ci->add(array('itemtype'     => 'Peripheral',
                        'items_id'     => $periphID,
                        'computers_id' => mt_rand($FIRST["computers"],$LAST['computers'])));
      }
   }

   $LAST["peripherals"] = getMaxItem("glpi_peripherals");

   $FIRST["software"]   = getMaxItem("glpi_softwares")+1;

   // Ajout logiciels + licences associees a divers PCs
   $items = array(array("Open'Office", "1.1.4", "2.0", "2.0.1"),
                  array("Microsoft Office", "95", "97", "XP", "2000", "2003", "2007"),
                  array("Acrobat Reader", "6.0", "7.0", "7.04"),
                  array("Gimp", "2.0", "2.2"),
                  array("InkScape", "0.4"));
   $soft       = new Software();
   $softvers   = new SoftwareVersion();
   $softlic    = new SoftwareLicense();
   $csv        = new Computer_SoftwareVersion();
   $csl        = new Computer_SoftwareLicense();
   for ($i=0 ; $i<$MAX['software'] ; $i++) {

      if (isset($items[$i])) {
         $name = $items[$i][0];
      } else {
         $name = "software '$i";
      }

      $loc       = mt_rand(1,$MAX['locations']);
      $techID    = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $gtechID   = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);
      $recursive = mt_rand(0,1);

      $softID = $soft->add(toolbox::addslashes_deep(
                           array('entities_id'           => $ID_entity,
                                 'is_recursive'          => $recursive,
                                 'name'                  => $name,
                                 'comment'               => "comment '$i",
                                 'locations_id'          => $loc,
                                 'users_id_tech'         => $techID,
                                 'groups_id_tech'        => $gtechID,
                                 'manufacturers_id'      => mt_rand(1,$MAX['manufacturer']),
                                 'notepad'               => "notes software '$i",
                                 'users_id'              => mt_rand($FIRST['users_admin'],
                                                                    $LAST['users_admin']),
                                 'groups_id'             => mt_rand($FIRST["groups"], $LAST["groups"]),
                                 'is_helpdesk_visible'   => 1,
                                 'softwarecategories_id' => mt_rand(1,$MAX['softwarecategory'])
                              )));

      addDocuments('Software', $softID);
      addContracts('Software', $softID);

      // Add trackings
      addTracking('Software', $softID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Software', $softID, $ID_entity);

      // Add versions
      $FIRST["version"] = getMaxItem("glpi_softwareversions")+1;

      if (isset($items[$i])) {
         $val2 = count($items[$i]);
      } else {
         $val2 = mt_rand(1,$MAX['softwareversions']+1);
      }

      for ($j=1 ; $j<=$val2 ; $j++) {
         if (isset($items[$i])) {
            $version = $items[$i][mt_rand(1,count($items[$i])-1)];
         } else {
            $version = "$j.0";
         }
         $os = mt_rand(1,$MAX['os']);

         $versID = $softvers->add(toolbox::addslashes_deep(
                                  array('entities_id'          => $ID_entity,
                                        'is_recursive'         => $recursive,
                                        'softwares_id'         => $softID,
                                        'name'                 => $version,
                                        'comment'              => "comment '$version",
                                        'states_id'            => (mt_rand(0,100)<$percent['state']
                                                                     ?mt_rand($FIRST['state'],$LAST['state']):0),
                                        'operatingsystems_id'  => $os)));

         $val3    = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall']));
         $comp_id = mt_rand($FIRST["computers"], $LAST['computers']);

         for ($k=0 ; $k<$val3 ; $k++) {
            $comp_id++;
            if ($comp_id>$LAST["computers"]) {
               $comp_id = $FIRST["computers"];
            }
            $csv->add(array('computers_id'        => $comp_id,
                            'softwareversions_id' => $versID));
         }
      }
      $LAST["version"] = getMaxItem("glpi_softwareversions");


      // Add licenses
      $val2 = mt_rand(1,$MAX['softwarelicenses']);

      for ($j=0 ; $j<$val2 ; $j++) {
         $softwareversions_id_buy = mt_rand($FIRST["version"],$LAST["version"]);
         $softwareversions_id_use = mt_rand($softwareversions_id_buy,$LAST["version"]);

         $nbused = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall']));

         $licID = $softlic->add(toolbox::addslashes_deep(
                                array('entities_id'               => $ID_entity,
                                      'is_recursive'              => $recursive,
                                      'softwares_id'              => $softID,
                                      'number'                    => $nbused,
                                      'softwarelicensetypes_id'   => mt_rand(1,$MAX['licensetype']),
                                      'name'                      => "license '$j",
                                      'serial'                    => "serial $j",
                                      'otherserial'               => "otherserial $j",
                                      'comment'                   => "comment license '$j",
                                      'softwareversions_id_buy'   => $softwareversions_id_buy,
                                      'softwareversions_id_use'   => $softwareversions_id_use)));

         $comp_id = mt_rand($FIRST["computers"], $LAST['computers']);

         for ($k=0 ; $k<$nbused ; $k++) {
            $comp_id++;
            if ($comp_id>$LAST["computers"]) {
               $comp_id = $FIRST["computers"];
            }
            $csl->add(array('computers_id'          => $comp_id,
                            'softwarelicenses_id'   => $licID));
         }
      }
   }
   $LAST["software"] = getMaxItem("glpi_softwares");
}
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file: Remi Collet
// Purpose of file:
// ----------------------------------------------------------------------
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
$csl = new Computer_SoftwareLicense();
if (isset($_REQUEST["add"])) {
    checkRight("software", "w");
    if ($_REQUEST['softwarelicenses_id'] > 0) {
        $csl->add($_REQUEST);
        Event::log($_REQUEST['softwarelicenses_id'], "softwarelicense", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][116]);
    }
    glpi_header($_SERVER['HTTP_REFERER']);
    // From association list
} else {
    if (isset($_REQUEST["move"])) {
        checkRight("software", "w");
        if ($_REQUEST['softwarelicenses_id'] > 0) {
            foreach ($_REQUEST["item"] as $key => $val) {
                if ($val == 1) {
                    $csl->upgrade($key, $_REQUEST['softwarelicenses_id']);
 /**
  * Show Licenses of a software
  *
  * @param $software software object
  *
  * @return nothing
  **/
 static function showForSoftware($software)
 {
     global $DB, $CFG_GLPI, $LANG;
     $softwares_id = $software->getField('id');
     $license = new SoftwareLicense();
     $computer = new Computer();
     if (!$software->can($softwares_id, "r")) {
         return false;
     }
     if (isset($_REQUEST["start"])) {
         $start = $_REQUEST["start"];
     } else {
         $start = 0;
     }
     if (isset($_REQUEST["order"]) && $_REQUEST["order"] == "DESC") {
         $order = "DESC";
     } else {
         $order = "ASC";
     }
     if (isset($_REQUEST["sort"]) && !empty($_REQUEST["sort"])) {
         $sort = "`" . $_REQUEST["sort"] . "`";
     } else {
         $sort = "`entity` {$order}, `name`";
     }
     // Righ type is enough. Can add a License on a software we have Read access
     $canedit = haveRight("software", "w");
     // Total Number of events
     $number = countElementsInTable("glpi_softwarelicenses", "glpi_softwarelicenses.softwares_id = {$softwares_id} " . getEntitiesRestrictRequest('AND', 'glpi_softwarelicenses', '', '', true));
     echo "<div class='spaced'>";
     if ($number < 1) {
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr><th>" . $LANG['search'][15] . "</th></tr>\n";
         if ($canedit) {
             echo "<tr class='tab_bg_2'><td class='center'>";
             echo "<a href='softwarelicense.form.php?softwares_id={$softwares_id}'>" . $LANG['software'][8] . "</a>";
             echo "</td></tr>\n";
         }
         echo "</table></div>\n";
         return;
     }
     // Display the pager
     printAjaxPager($LANG['software'][11], $start, $number);
     $rand = mt_rand();
     $query = "SELECT `glpi_softwarelicenses`.*,\n                       `buyvers`.`name` AS buyname,\n                       `usevers`.`name` AS usename,\n                       `glpi_entities`.`completename` AS entity,\n                       `glpi_softwarelicensetypes`.`name` AS typename\n                FROM `glpi_softwarelicenses`\n                LEFT JOIN `glpi_softwareversions` AS buyvers\n                     ON (`buyvers`.`id` = `glpi_softwarelicenses`.`softwareversions_id_buy`)\n                LEFT JOIN `glpi_softwareversions` AS usevers\n                     ON (`usevers`.`id` = `glpi_softwarelicenses`.`softwareversions_id_use`)\n                LEFT JOIN `glpi_entities`\n                     ON (`glpi_entities`.`id` = `glpi_softwarelicenses`.`entities_id`)\n                LEFT JOIN `glpi_softwarelicensetypes`\n                     ON (`glpi_softwarelicensetypes`.`id`\n                          = `glpi_softwarelicenses`.`softwarelicensetypes_id`)\n                WHERE (`glpi_softwarelicenses`.`softwares_id` = '{$softwares_id}') " . getEntitiesRestrictRequest('AND', 'glpi_softwarelicenses', '', '', true) . "\n                ORDER BY {$sort} {$order}\n                LIMIT " . intval($start) . "," . intval($_SESSION['glpilist_limit']);
     initNavigateListItems('SoftwareLicense', $LANG['help'][31] . " = " . $software->fields["name"]);
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result)) {
             if ($canedit) {
                 echo "<form method='post' name='massiveactionlicense_form{$rand}' id='" . "massiveactionlicense_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/front/massiveaction.php\">";
             }
             $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>";
             echo "<table class='tab_cadre_fixehov'><tr>";
             echo "<th>&nbsp;</th>";
             echo "<th>" . ($sort == "`name`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=name&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][16] . "</a></th>";
             if ($software->isRecursive()) {
                 // Ereg to search entity in string for match default order
                 echo "<th>" . (strstr($sort, "entity") ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=entity&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['entity'][0] . "</a></th>";
             }
             echo "<th>" . ($sort == "`serial`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=serial&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][19] . "</a></th>";
             echo "<th>" . ($sort == "`number`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=number&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['tracking'][29] . "</a></th>";
             echo "<th>" . $LANG['software'][9] . "</th>";
             echo "<th>" . ($sort == "`typename`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=typename&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['common'][17] . "</a></th>";
             echo "<th>" . ($sort == "`buyname`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=buyname&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['software'][1] . "</a></th>";
             echo "<th>" . ($sort == "`usename`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=usename&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['software'][2] . "</a></th>";
             echo "<th>" . ($sort == "`expire`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort=expire&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>" . $LANG['software'][32] . "</a></th>";
             echo "</tr>\n";
             $tot_assoc = 0;
             for ($tot = 0; $data = $DB->fetch_assoc($result);) {
                 addToNavigateListItems('SoftwareLicense', $data['id']);
                 echo "<tr class='tab_bg_2'>";
                 if ($license->can($data['id'], "w")) {
                     echo "<td><input type='checkbox' name='item[" . $data["id"] . "]' value='1'></td>";
                 } else {
                     echo "<td>&nbsp;</td>";
                 }
                 echo "<td><a href='softwarelicense.form.php?id=" . $data['id'] . "'>" . $data['name'] . (empty($data['name']) ? $data['id'] : "") . "</a></td>";
                 if ($software->isRecursive()) {
                     echo "<td>" . $data['entity'] . "</td>";
                 }
                 echo "<td>" . $data['serial'] . "</td>";
                 echo "<td class='right'>" . ($data['number'] > 0 ? $data['number'] . "&nbsp;&nbsp;" : $LANG['software'][4]) . "</td>";
                 $nb_assoc = Computer_SoftwareLicense::countForLicense($data['id']);
                 $tot_assoc += $nb_assoc;
                 echo "<td class='right'>{$nb_assoc}&nbsp;&nbsp;</td>";
                 echo "<td>" . $data['typename'] . "</td>";
                 echo "<td>" . $data['buyname'] . "</td>";
                 echo "<td>" . $data['usename'] . "</td>";
                 echo "<td class='center'>" . convDate($data['expire']) . "</td>";
                 echo "</tr>";
                 if ($data['number'] < 0) {
                     // One illimited license, total is illimited
                     $tot = -1;
                 } else {
                     if ($tot >= 0) {
                         // Not illimited, add the current number
                         $tot += $data['number'];
                     }
                 }
             }
             echo "<tr class='tab_bg_1'>";
             echo "<td colspan='" . ($software->isRecursive() ? 4 : 3) . "' class='right b'>" . $LANG['common'][33] . "</td>";
             echo "<td class='right b'>" . ($tot > 0 ? $tot . "&nbsp;&nbsp;" : $LANG['software'][4]) . "</td>";
             echo "<td class='right b'>{$tot_assoc}&nbsp;&nbsp;</td>";
             echo "<td colspan='4' class='center'>";
             if ($canedit) {
                 echo "<a href='softwarelicense.form.php?softwares_id={$softwares_id}'>" . $LANG['software'][8] . "</a>";
             }
             echo "</td></tr>";
             echo "</table>\n";
             if ($canedit) {
                 openArrowMassive("massiveactionlicense_form{$rand}", true);
                 Dropdown::showForMassiveAction('SoftwareLicense', 0, array('softwares_id' => $softwares_id));
                 closeArrowMassive();
                 echo "</form>";
             }
         } else {
             echo $LANG['search'][15];
         }
     }
     echo "</div>";
 }
 /**
  * Show Licenses of a software
  *
  * @param $software Software object
  *
  * @return nothing
  **/
 static function showForSoftware(Software $software)
 {
     global $DB, $CFG_GLPI;
     $softwares_id = $software->getField('id');
     $license = new self();
     $computer = new Computer();
     if (!$software->can($softwares_id, READ)) {
         return false;
     }
     $columns = array('name' => __('Name'), 'entity' => __('Entity'), 'serial' => __('Serial number'), 'number' => _x('quantity', 'Number'), '_affected' => __('Affected computers'), 'typename' => __('Type'), 'buyname' => __('Purchase version'), 'usename' => __('Version in use'), 'expire' => __('Expiration'));
     if (!$software->isRecursive()) {
         unset($columns['entity']);
     }
     if (isset($_GET["start"])) {
         $start = $_GET["start"];
     } else {
         $start = 0;
     }
     if (isset($_GET["order"]) && $_GET["order"] == "DESC") {
         $order = "DESC";
     } else {
         $order = "ASC";
     }
     if (isset($_GET["sort"]) && !empty($_GET["sort"]) && isset($columns[$_GET["sort"]])) {
         $sort = "`" . $_GET["sort"] . "`";
     } else {
         $sort = "`entity` {$order}, `name`";
     }
     // Righ type is enough. Can add a License on a software we have Read access
     $canedit = Software::canUpdate();
     $showmassiveactions = $canedit;
     // Total Number of events
     $number = countElementsInTable("glpi_softwarelicenses", "glpi_softwarelicenses.softwares_id = {$softwares_id} " . getEntitiesRestrictRequest('AND', 'glpi_softwarelicenses', '', '', true));
     echo "<div class='spaced'>";
     Session::initNavigateListItems('SoftwareLicense', sprintf(__('%1$s = %2$s'), Software::getTypeName(1), $software->getName()));
     if ($canedit) {
         echo "<div class='center firstbloc'>";
         echo "<a class='vsubmit' href='softwarelicense.form.php?softwares_id={$softwares_id}'>" . _x('button', 'Add a license') . "</a>";
         echo "</div>";
     }
     $rand = mt_rand();
     $query = "SELECT `glpi_softwarelicenses`.*,\n                       `buyvers`.`name` AS buyname,\n                       `usevers`.`name` AS usename,\n                       `glpi_entities`.`completename` AS entity,\n                       `glpi_softwarelicensetypes`.`name` AS typename\n                FROM `glpi_softwarelicenses`\n                LEFT JOIN `glpi_softwareversions` AS buyvers\n                     ON (`buyvers`.`id` = `glpi_softwarelicenses`.`softwareversions_id_buy`)\n                LEFT JOIN `glpi_softwareversions` AS usevers\n                     ON (`usevers`.`id` = `glpi_softwarelicenses`.`softwareversions_id_use`)\n                LEFT JOIN `glpi_entities`\n                     ON (`glpi_entities`.`id` = `glpi_softwarelicenses`.`entities_id`)\n                LEFT JOIN `glpi_softwarelicensetypes`\n                     ON (`glpi_softwarelicensetypes`.`id`\n                          = `glpi_softwarelicenses`.`softwarelicensetypes_id`)\n                WHERE (`glpi_softwarelicenses`.`softwares_id` = '{$softwares_id}') " . getEntitiesRestrictRequest('AND', 'glpi_softwarelicenses', '', '', true) . "\n                ORDER BY {$sort} {$order}\n                LIMIT " . intval($start) . "," . intval($_SESSION['glpilist_limit']);
     if ($result = $DB->query($query)) {
         if ($num_displayed = $DB->numrows($result)) {
             // Display the pager
             Html::printAjaxPager(self::getTypeName(Session::getPluralNumber()), $start, $number);
             if ($showmassiveactions) {
                 Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
                 $massiveactionparams = array('num_displayed' => $num_displayed, 'container' => 'mass' . __CLASS__ . $rand, 'extraparams' => array('options' => array('glpi_softwareversions.name' => array('condition' => "`glpi_softwareversions`.`softwares_id`\n                                                                  = {$softwares_id}"), 'glpi_softwarelicenses.name' => array('itemlink_as_string' => true))));
                 Html::showMassiveActions($massiveactionparams);
             }
             $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>";
             $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>";
             echo "<table class='tab_cadre_fixehov'>";
             $header_begin = "<tr><th>";
             $header_top = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
             $header_bottom = Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
             $header_end = '';
             foreach ($columns as $key => $val) {
                 // Non order column
                 if ($key[0] == '_') {
                     $header_end .= "<th>{$val}</th>";
                 } else {
                     $header_end .= "<th>" . ($sort == "`{$key}`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort={$key}&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>{$val}</a></th>";
                 }
             }
             $header_end .= "</tr>\n";
             echo $header_begin . $header_top . $header_end;
             $tot_assoc = 0;
             for ($tot = 0; $data = $DB->fetch_assoc($result);) {
                 Session::addToNavigateListItems('SoftwareLicense', $data['id']);
                 $expired = true;
                 if (is_null($data['expire']) || $data['expire'] > date('Y-m-d')) {
                     $expired = false;
                 }
                 echo "<tr class='tab_bg_2" . ($expired ? '_2' : '') . "'>";
                 if ($license->canEdit($data['id'])) {
                     echo "<td>" . Html::getMassiveActionCheckBox(__CLASS__, $data["id"]) . "</td>";
                 } else {
                     echo "<td>&nbsp;</td>";
                 }
                 echo "<td><a href='softwarelicense.form.php?id=" . $data['id'] . "'>" . $data['name'] . (empty($data['name']) ? "(" . $data['id'] . ")" : "") . "</a></td>";
                 if (isset($columns['entity'])) {
                     echo "<td>";
                     echo $data['entity'];
                     echo "</td>";
                 }
                 echo "<td>" . $data['serial'] . "</td>";
                 echo "<td class='numeric'>" . ($data['number'] > 0 ? $data['number'] : __('Unlimited')) . "</td>";
                 $nb_assoc = Computer_SoftwareLicense::countForLicense($data['id']);
                 $tot_assoc += $nb_assoc;
                 $color = $data['is_valid'] ? 'green' : 'red';
                 echo "<td class='numeric {$color}'>" . $nb_assoc . "</td>";
                 echo "<td>" . $data['typename'] . "</td>";
                 echo "<td>" . $data['buyname'] . "</td>";
                 echo "<td>" . $data['usename'] . "</td>";
                 echo "<td class='center'>" . Html::convDate($data['expire']) . "</td>";
                 echo "</tr>";
                 if ($data['number'] < 0) {
                     // One illimited license, total is illimited
                     $tot = -1;
                 } else {
                     if ($tot >= 0) {
                         // Expire license not count
                         if (!$expired) {
                             // Not illimited, add the current number
                             $tot += $data['number'];
                         }
                     }
                 }
             }
             echo "<tr class='tab_bg_1 noHover'>";
             echo "<td colspan='" . ($software->isRecursive() ? 4 : 3) . "' class='right b'>" . __('Total') . "</td>";
             echo "<td class='numeric'>" . ($tot > 0 ? $tot . "" : __('Unlimited')) . "</td>";
             $color = $software->fields['is_valid'] ? 'green' : 'red';
             echo "<td class='numeric {$color}'>" . $tot_assoc . "</td><td></td><td></td><td></td><td></td>";
             echo "</tr>";
             echo "</table>\n";
             if ($showmassiveactions) {
                 $massiveactionparams['ontop'] = false;
                 Html::showMassiveActions($massiveactionparams);
                 Html::closeForm();
             }
             Html::printAjaxPager(self::getTypeName(Session::getPluralNumber()), $start, $number);
         } else {
             echo "<table class='tab_cadre_fixe'><tr><th>" . __('No item found') . "</th></tr></table>";
         }
     }
     echo "</div>";
 }
 function associate($options)
 {
     if (isset($options['computers_id'])) {
         $computer_slicense = new Computer_SoftwareLicense();
         $computer_slicense->add(array('computers_id' => $options['computers_id'], 'softwarelicenses_id' => $options['softwarelicenses_id']));
     }
     $pfLicenseInfo = new self();
     $pfLicenseInfo->update(array('id' => $options['fusioninventory_licenseinfos_id'], 'softwarelicenses_id' => $options['softwarelicenses_id']));
 }
 /**
  * Show installations of a software
  *
  * @param $searchID  value of the ID to search
  * @param $crit      to search : softwares_id (software) or id (version)
  *
  * @return nothing
  **/
 private static function showInstallations($searchID, $crit)
 {
     global $DB, $CFG_GLPI;
     if (!Software::canView() || !$searchID) {
         return false;
     }
     $canedit = Session::haveRightsOr("software", array(CREATE, UPDATE, DELETE, PURGE));
     $canshowcomputer = Computer::canView();
     $refcolumns = array('vername' => _n('Version', 'Versions', Session::getPluralNumber()), 'compname' => __('Name'), 'entity' => __('Entity'), 'serial' => __('Serial number'), 'otherserial' => __('Inventory number'), 'location,compname' => __('Location'), 'state,compname' => __('Status'), 'groupe,compname' => __('Group'), 'username,compname' => __('User'), 'lname' => _n('License', 'Licenses', Session::getPluralNumber()));
     if ($crit != "softwares_id") {
         unset($refcolumns['vername']);
     }
     if (isset($_GET["start"])) {
         $start = $_GET["start"];
     } else {
         $start = 0;
     }
     if (isset($_GET["order"]) && $_GET["order"] == "DESC") {
         $order = "DESC";
     } else {
         $order = "ASC";
     }
     if (isset($_GET["sort"]) && !empty($_GET["sort"]) && isset($refcolumns[$_GET["sort"]])) {
         // manage several param like location,compname :  order first
         $tmp = explode(",", $_GET["sort"]);
         $sort = "`" . implode("` {$order},`", $tmp) . "`";
     } else {
         if ($crit == "softwares_id") {
             $sort = "`entity` {$order}, `version`, `compname`";
         } else {
             $sort = "`entity` {$order}, `compname`";
         }
     }
     // Total Number of events
     if ($crit == "softwares_id") {
         // Software ID
         $query_number = "SELECT COUNT(*) AS cpt\n                          FROM `glpi_computers_softwareversions`\n                          INNER JOIN `glpi_softwareversions`\n                              ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                                    = `glpi_softwareversions`.`id`)\n                          INNER JOIN `glpi_computers`\n                              ON (`glpi_computers_softwareversions`.`computers_id`\n                                    = `glpi_computers`.`id`)\n                          WHERE `glpi_softwareversions`.`softwares_id` = '{$searchID}'" . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                                AND `glpi_computers`.`is_deleted` = '0'\n                                AND `glpi_computers`.`is_template` = '0'\n                                AND `glpi_computers_softwareversions`.`is_deleted` = '0'";
     } else {
         //SoftwareVersion ID
         $query_number = "SELECT COUNT(*) AS cpt\n                          FROM `glpi_computers_softwareversions`\n                          INNER JOIN `glpi_computers`\n                              ON (`glpi_computers_softwareversions`.`computers_id`\n                                    = `glpi_computers`.`id`)\n                          WHERE `glpi_computers_softwareversions`.`softwareversions_id`\n                                       = '{$searchID}'" . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                                AND `glpi_computers`.`is_deleted` = '0'\n                                AND `glpi_computers`.`is_template` = '0'\n                                AND `glpi_computers_softwareversions`.`is_deleted` = '0'";
     }
     $number = 0;
     if ($result = $DB->query($query_number)) {
         $number = $DB->result($result, 0, 0);
     }
     echo "<div class='center'>";
     if ($number < 1) {
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr><th>" . __('No item found') . "</th></tr>";
         echo "</table></div>\n";
         return;
     }
     // Display the pager
     Html::printAjaxPager(self::getTypeName(Session::getPluralNumber()), $start, $number);
     $query = "SELECT DISTINCT `glpi_computers_softwareversions`.*,\n                       `glpi_computers`.`name` AS compname,\n                       `glpi_computers`.`id` AS cID,\n                       `glpi_computers`.`serial`,\n                       `glpi_computers`.`otherserial`,\n                       `glpi_users`.`name` AS username,\n                       `glpi_users`.`id` AS userid,\n                       `glpi_users`.`realname` AS userrealname,\n                       `glpi_users`.`firstname` AS userfirstname,\n                       `glpi_softwareversions`.`name` AS version,\n                       `glpi_softwareversions`.`id` AS vID,\n                       `glpi_softwareversions`.`softwares_id` AS sID,\n                       `glpi_softwareversions`.`name` AS vername,\n                       `glpi_entities`.`completename` AS entity,\n                       `glpi_locations`.`completename` AS location,\n                       `glpi_states`.`name` AS state,\n                       `glpi_groups`.`name` AS groupe\n                FROM `glpi_computers_softwareversions`\n                INNER JOIN `glpi_softwareversions`\n                     ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                           = `glpi_softwareversions`.`id`)\n                INNER JOIN `glpi_computers`\n                     ON (`glpi_computers_softwareversions`.`computers_id` = `glpi_computers`.`id`)\n                LEFT JOIN `glpi_entities` ON (`glpi_computers`.`entities_id` = `glpi_entities`.`id`)\n                LEFT JOIN `glpi_locations`\n                     ON (`glpi_computers`.`locations_id` = `glpi_locations`.`id`)\n                LEFT JOIN `glpi_states` ON (`glpi_computers`.`states_id` = `glpi_states`.`id`)\n                LEFT JOIN `glpi_groups` ON (`glpi_computers`.`groups_id` = `glpi_groups`.`id`)\n                LEFT JOIN `glpi_users` ON (`glpi_computers`.`users_id` = `glpi_users`.`id`)\n                WHERE (`glpi_softwareversions`.`{$crit}` = '{$searchID}') " . getEntitiesRestrictRequest(' AND', 'glpi_computers') . "\n                       AND `glpi_computers`.`is_deleted` = '0'\n                       AND `glpi_computers`.`is_template` = '0'\n                       AND `glpi_computers_softwareversions`.`is_deleted` = '0'\n                ORDER BY {$sort} {$order}\n                LIMIT " . intval($start) . "," . intval($_SESSION['glpilist_limit']);
     $rand = mt_rand();
     if ($result = $DB->query($query)) {
         if ($data = $DB->fetch_assoc($result)) {
             $softwares_id = $data['sID'];
             $soft = new Software();
             $showEntity = $soft->getFromDB($softwares_id) && $soft->isRecursive();
             $linkUser = User::canView();
             $title = $soft->fields["name"];
             if ($crit == "id") {
                 $title = sprintf(__('%1$s - %2$s'), $title, $data["vername"]);
             }
             Session::initNavigateListItems('Computer', sprintf(__('%1$s = %2$s'), Software::getTypeName(1), $title));
             $sort_img = "<img src='" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "' alt=''\n                          title=''>";
             if ($canedit) {
                 $rand = mt_rand();
                 Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
                 $massiveactionparams = array('num_displayed' => $number, 'container' => 'mass' . __CLASS__ . $rand, 'specific_actions' => array(__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'move_version' => _x('button', 'Move'), 'purge' => _x('button', 'Delete permanently')));
                 // Options to update version
                 $massiveactionparams['extraparams']['options']['move']['softwares_id'] = $softwares_id;
                 if ($crit == 'softwares_id') {
                     $massiveactionparams['extraparams']['options']['move']['used'] = array();
                 } else {
                     $massiveactionparams['extraparams']['options']['move']['used'] = array($searchID);
                 }
                 Html::showMassiveActions($massiveactionparams);
             }
             echo "<table class='tab_cadre_fixehov'>";
             $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>";
             $header_begin = "<tr>";
             $header_top = '';
             $header_bottom = '';
             $header_end = '';
             if ($canedit) {
                 $header_begin .= "<th width='10'>";
                 $header_top .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
                 $header_bottom .= Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
                 $header_end .= "</th>";
             }
             $columns = $refcolumns;
             if (!$showEntity) {
                 unset($columns['entity']);
             }
             foreach ($columns as $key => $val) {
                 // Non order column
                 if ($key[0] == '_') {
                     $header_end .= "<th>{$val}</th>";
                 } else {
                     $header_end .= "<th>" . ($sort == "`{$key}`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort={$key}&amp;order=" . ($order == "ASC" ? "DESC" : "ASC") . "&amp;start=0\");'>{$val}</a></th>";
                 }
             }
             $header_end .= "</tr>\n";
             echo $header_begin . $header_top . $header_end;
             do {
                 Session::addToNavigateListItems('Computer', $data["cID"]);
                 echo "<tr class='tab_bg_2'>";
                 if ($canedit) {
                     echo "<td>";
                     Html::showMassiveActionCheckBox(__CLASS__, $data["id"]);
                     echo "</td>";
                 }
                 if ($crit == "softwares_id") {
                     echo "<td><a href='softwareversion.form.php?id=" . $data['vID'] . "'>" . $data['version'] . "</a></td>";
                 }
                 $compname = $data['compname'];
                 if (empty($compname) || $_SESSION['glpiis_ids_visible']) {
                     $compname = sprintf(__('%1$s (%2$s)'), $compname, $data['cID']);
                 }
                 if ($canshowcomputer) {
                     echo "<td><a href='computer.form.php?id=" . $data['cID'] . "'>{$compname}</a></td>";
                 } else {
                     echo "<td>" . $compname . "</td>";
                 }
                 if ($showEntity) {
                     echo "<td>" . $data['entity'] . "</td>";
                 }
                 echo "<td>" . $data['serial'] . "</td>";
                 echo "<td>" . $data['otherserial'] . "</td>";
                 echo "<td>" . $data['location'] . "</td>";
                 echo "<td>" . $data['state'] . "</td>";
                 echo "<td>" . $data['groupe'] . "</td>";
                 echo "<td>" . formatUserName($data['userid'], $data['username'], $data['userrealname'], $data['userfirstname'], $linkUser) . "</td>";
                 $lics = Computer_SoftwareLicense::getLicenseForInstallation($data['cID'], $data['vID']);
                 echo "<td>";
                 if (count($lics)) {
                     foreach ($lics as $data) {
                         $serial = $data['serial'];
                         if (!empty($data['type'])) {
                             $serial = sprintf(__('%1$s (%2$s)'), $serial, $data['type']);
                         }
                         echo "<a href='softwarelicense.form.php?id=" . $data['id'] . "'>" . $data['name'];
                         echo "</a> - " . $serial;
                         echo "<br>";
                     }
                 }
                 echo "</td>";
                 echo "</tr>\n";
             } while ($data = $DB->fetch_assoc($result));
             echo $header_begin . $header_bottom . $header_end;
             echo "</table>\n";
             if ($canedit) {
                 $massiveactionparams['ontop'] = false;
                 Html::showMassiveActions($massiveactionparams);
                 Html::closeForm();
             }
         } else {
             // Not found
             _e('No item found');
         }
     }
     // Query
     Html::printAjaxPager(self::getTypeName(Session::getPluralNumber()), $start, $number);
     echo "</div>\n";
 }
if (!isset($_POST["withtemplate"])) {
    $_POST["withtemplate"] = "";
}
checkRight("software", "r");
$license = new SoftwareLicense();
if ($_POST["id"] > 0 && $license->can($_POST["id"], 'r')) {
    switch ($_REQUEST['glpi_tab']) {
        case -1:
            Infocom::showForItem($license);
            Document::showAssociated($license);
            Plugin::displayAction($license, $_REQUEST['glpi_tab']);
            break;
        case 2:
            Computer_SoftwareLicense::showForLicense($license);
            break;
        case 4:
            Infocom::showForItem($license);
            break;
        case 5:
            Document::showAssociated($license);
            break;
        case 12:
            Log::showForItem($license);
            break;
        default:
            if (!Plugin::displayAction($license, $_REQUEST['glpi_tab'])) {
                Computer_SoftwareLicense::showForLicenseByEntity($license);
            }
    }
}
ajaxFooter();
 function post_addItem()
 {
     global $DB;
     // Manage add from template
     if (isset($this->input["_oldID"])) {
         // ADD Devices
         $compdev = new Computer_Device();
         $compdev->cloneComputer($this->input["_oldID"], $this->fields['id']);
         // ADD Infocoms
         $ic = new Infocom();
         $ic->cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
         // ADD volumes
         $query = "SELECT `id`\n                   FROM `glpi_computerdisks`\n                   WHERE `computers_id` = '" . $this->input["_oldID"] . "'";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             while ($data = $DB->fetch_array($result)) {
                 $disk = new ComputerDisk();
                 $disk->getfromDB($data['id']);
                 unset($disk->fields["id"]);
                 $disk->fields["computers_id"] = $this->fields['id'];
                 $disk->addToDB();
             }
         }
         // ADD software
         $inst = new Computer_SoftwareVersion();
         $inst->cloneComputer($this->input["_oldID"], $this->fields['id']);
         $inst = new Computer_SoftwareLicense();
         $inst->cloneComputer($this->input["_oldID"], $this->fields['id']);
         // ADD Contract
         $query = "SELECT `contracts_id`\n                   FROM `glpi_contracts_items`\n                   WHERE `items_id` = '" . $this->input["_oldID"] . "'\n                         AND `itemtype` = '" . $this->getType() . "';";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             $contractitem = new Contract_Item();
             while ($data = $DB->fetch_array($result)) {
                 $contractitem->add(array('contracts_id' => $data["contracts_id"], 'itemtype' => $this->getType(), 'items_id' => $this->fields['id']));
             }
         }
         // ADD Documents
         $query = "SELECT `documents_id`\n                   FROM `glpi_documents_items`\n                   WHERE `items_id` = '" . $this->input["_oldID"] . "'\n                         AND `itemtype` = '" . $this->getType() . "';";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             $docitem = new Document_Item();
             while ($data = $DB->fetch_array($result)) {
                 $docitem->add(array('documents_id' => $data["documents_id"], 'itemtype' => $this->getType(), 'items_id' => $this->fields['id']));
             }
         }
         // ADD Ports
         $query = "SELECT `id`\n                   FROM `glpi_networkports`\n                   WHERE `items_id` = '" . $this->input["_oldID"] . "'\n                         AND `itemtype` = '" . $this->getType() . "';";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             while ($data = $DB->fetch_array($result)) {
                 $np = new NetworkPort();
                 $npv = new NetworkPort_Vlan();
                 $np->getFromDB($data["id"]);
                 unset($np->fields["id"]);
                 unset($np->fields["ip"]);
                 unset($np->fields["mac"]);
                 unset($np->fields["netpoints_id"]);
                 $np->fields["items_id"] = $this->fields['id'];
                 $portid = $np->addToDB();
                 foreach ($DB->request('glpi_networkports_vlans', array('networkports_id' => $data["id"])) as $vlan) {
                     $npv->assignVlan($portid, $vlan['vlans_id']);
                 }
             }
         }
         // Add connected devices
         $query = "SELECT *\n                   FROM `glpi_computers_items`\n                   WHERE `computers_id` = '" . $this->input["_oldID"] . "';";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             $conn = new Computer_Item();
             while ($data = $DB->fetch_array($result)) {
                 $conn->add(array('computers_id' => $this->fields['id'], 'itemtype' => $data["itemtype"], 'items_id' => $data["items_id"]));
             }
         }
     }
 }
Example #13
0
 function cleanDBonPurge()
 {
     $csv = new Computer_SoftwareVersion();
     $csv->cleanDBonItemDelete('Computer', $this->fields['id']);
     $csl = new Computer_SoftwareLicense();
     $csl->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ip = new Item_Problem();
     $ip->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ci = new Computer_Item();
     $ci->cleanDBonItemDelete('Computer', $this->fields['id']);
     Item_Devices::cleanItemDeviceDBOnItemDelete('Computer', $this->fields['id']);
     $disk = new ComputerDisk();
     $disk->cleanDBonItemDelete('Computer', $this->fields['id']);
     $vm = new ComputerVirtualMachine();
     $vm->cleanDBonItemDelete('Computer', $this->fields['id']);
 }
Example #14
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;
}
This file is part of GLPI.

GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include '../inc/includes.php';
Session::checkRight("software", "w");
$csl = new Computer_SoftwareLicense();
if (isset($_POST["add"])) {
    if ($_POST['softwarelicenses_id'] > 0) {
        $csl->add($_POST);
        Event::log($_POST['softwarelicenses_id'], "softwarelicense", 4, "inventory", sprintf(__('%s associates a computer and a license'), $_SESSION["glpiname"]));
    }
    Html::back();
}
Html::displayErrorAndDie('Lost');
Example #16
0
 function cleanDBonPurge()
 {
     $csv = new Computer_SoftwareVersion();
     $csv->cleanDBonItemDelete('Computer', $this->fields['id']);
     $csl = new Computer_SoftwareLicense();
     $csl->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ip = new Item_Problem();
     $ip->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ci = new Change_Item();
     $ci->cleanDBonItemDelete('Computer', $this->fields['id']);
     $ip = new Item_Project();
     $ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']);
     $ci = new Computer_Item();
     $ci->cleanDBonItemDelete('Computer', $this->fields['id']);
     Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'], !empty($this->input['keep_devices']));
     $disk = new ComputerDisk();
     $disk->cleanDBonItemDelete('Computer', $this->fields['id']);
     $vm = new ComputerVirtualMachine();
     $vm->cleanDBonItemDelete('Computer', $this->fields['id']);
 }
This file is part of GLPI.

GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include '../inc/includes.php';
Session::checkRight("software", UPDATE);
$csl = new Computer_SoftwareLicense();
if (isset($_POST["add"])) {
    if ($_POST['softwarelicenses_id'] > 0) {
        if ($newID = $csl->add($_POST)) {
            Event::log($_POST['softwarelicenses_id'], "softwarelicense", 4, "inventory", sprintf(__('%s associates a computer and a license'), $_SESSION["glpiname"]));
        }
    }
    Html::back();
}
Html::displayErrorAndDie('Lost');
 /**
  * Transfer affected licenses to a computer
  *
  * @param $ID ID of the License
  **/
 function transferAffectedLicense($ID)
 {
     global $DB;
     $computer_softwarelicense = new Computer_SoftwareLicense();
     $license = new SoftwareLicense();
     if ($computer_softwarelicense->getFromDB($ID)) {
         if ($license->getFromDB($computer_softwarelicense->getField('softwarelicenses_id'))) {
             //// Update current : decrement number by 1 if valid
             if ($license->getField('number') > 1) {
                 $license->update(array('id' => $license->getID(), 'number' => $license->getField('number') - 1));
             }
             // Create new license : need to transfer softwre and versions before
             $input = array();
             $newsoftID = $this->copySingleSoftware($license->fields['softwares_id']);
             if ($newsoftID > 0) {
                 //// If license already exists : increment number by one
                 $query = "SELECT *\n                         FROM `glpi_softwarelicenses`\n                         WHERE `softwares_id` = '{$newsoftID}'\n                               AND `name` = '" . addslashes($license->fields['name']) . "'\n                               AND `serial` = '" . addslashes($license->fields['serial']) . "'";
                 $newlicID = -1;
                 if ($result = $DB->query($query)) {
                     //// If exists : increment number by 1
                     if ($DB->numrows($result) > 0) {
                         $data = $DB->fetch_array($result);
                         $newlicID = $data['id'];
                         $license->update(array('id' => $data['id'], 'number' => $data['number'] + 1));
                     } else {
                         //// If not exists : create with number = 1
                         $input = $license->fields;
                         foreach (array('softwareversions_id_buy', 'softwareversions_id_use') as $field) {
                             if ($license->fields[$field] > 0) {
                                 $newversID = $this->copySingleVersion($license->fields[$field]);
                                 if ($newversID > 0 && $newversID != $license->fields[$field]) {
                                     $input[$field] = $newversID;
                                 }
                             }
                         }
                         unset($input['id']);
                         $input['number'] = 1;
                         $input['entities_id'] = $this->to;
                         $input['softwares_id'] = $newsoftID;
                         $newlicID = $license->add($input);
                     }
                 }
                 if ($newlicID > 0) {
                     $input = array('id' => $ID, 'softwarelicenses_id' => $newlicID);
                     $computer_softwarelicense->update($input);
                 }
             }
         }
     }
     // getFromDB
 }
 /**
  *
  * Update config of a new software office
  *
  * This function create a officepack in GLPI with some general data.
  *
  * @param type $computers_id
  * @param $entity
  * @param type $ocsComputer
  * @param type $cfg_ocs
  *
  * @internal param \type $ocsservers_id
  */
 static function updateOfficePack($computers_id, $entity, $ocsComputer, $cfg_ocs)
 {
     global $DB;
     $software = new Software();
     $ocsOfficePacks = $ocsComputer;
     // Read imported software in last sync
     $query = "SELECT `glpi_computers_softwarelicenses`.`id` as id,\n                          `glpi_softwares`.`name` as sname,\n                          `glpi_softwarelicenses`.`name` as lname,\n                          `glpi_softwareversions`.`name` as vname\n                   FROM `glpi_computers_softwarelicenses`\n                   INNER JOIN `glpi_softwarelicenses`\n                           ON `glpi_softwarelicenses`.`id`= `glpi_computers_softwarelicenses`.`softwarelicenses_id`\n                   INNER JOIN `glpi_softwares`\n                           ON `glpi_softwares`.`id`= `glpi_softwarelicenses`.`softwares_id`\n                   INNER JOIN `glpi_softwareversions`\n                           ON `glpi_softwarelicenses`.`softwareversions_id_use` = `glpi_softwareversions`.`id`\n                   WHERE `glpi_computers_softwarelicenses`.`computers_id`='{$computers_id}'\n                         AND `is_dynamic`";
     $imported = array();
     foreach ($DB->request($query) as $data) {
         $imported[$data['id']] = strtolower($data['vname']);
     }
     if (count($ocsOfficePacks) > 0) {
         foreach ($ocsOfficePacks as $ocsOfficePack) {
             $ocsOfficePack = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($ocsOfficePack));
             $query1 = "SELECT `glpi_softwares`.`id` AS softwares_id,\n                              `glpi_softwareversions`.`id` AS softwareversions_id,\n                              `glpi_softwareversions`.`name` AS softwareversions_name\n                     FROM `glpi_softwares`\n                     LEFT JOIN `glpi_softwareversions` ON `glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`\n                     LEFT JOIN `glpi_computers_softwareversions` ON `glpi_computers_softwareversions`.softwareversions_id = `glpi_softwareversions`.`id`\n                     WHERE `glpi_computers_softwareversions`.`computers_id` = '" . $computers_id . "'\n                      AND `is_dynamic` \n                      AND `glpi_softwares`.`name` = '" . $ocsOfficePack['PRODUCT'] . "'\n                      AND `glpi_softwareversions`.`name` = '" . $ocsOfficePack['OFFICEVERSION'] . "'";
             $result = $DB->query($query1);
             if ($DB->numrows($result) > 0) {
                 $softwares_id = $DB->result($result, 0, 'softwares_id');
                 $softwareversions_id = $DB->result($result, 0, 'softwareversions_id');
                 $soft_l['softwares_id'] = $softwares_id;
                 $soft_l['softwareversions_id_use'] = $softwareversions_id;
                 $soft_l['entities_id'] = $entity;
                 $soft_l['name'] = $ocsOfficePack['OFFICEKEY'];
                 $soft_l['serial'] = $ocsOfficePack['OFFICEKEY'];
                 $soft_l['comment'] = $ocsOfficePack['NOTE'];
                 $id = array_search(strtolower(stripslashes($ocsOfficePack['OFFICEVERSION'])), $imported);
                 $software_licenses = new SoftwareLicense();
                 $computer_softwarelicenses = new Computer_SoftwareLicense();
                 if ($id) {
                     //-------------------------------------------------------------------------//
                     //---- The software exists in this license for this computer --------------//
                     //---------------------------- Update comments ----------------------------//
                     //---------------------------------------------------- --------------------//
                     if ($software_licenses->getFromDBByQuery("WHERE `softwares_id` = " . $softwares_id . " \n                                                         AND `serial` = '" . $ocsOfficePack['OFFICEKEY'] . "'\n                                                         AND `softwareversions_id_use` = " . $softwareversions_id)) {
                         $software_licenses->update(array('id' => $software_licenses->getID(), 'comment' => $ocsOfficePack['NOTE']));
                         if (!$computer_softwarelicenses->getFromDBByQuery("WHERE `computers_id` = " . $computers_id . "\n                           AND `softwarelicenses_id` = " . $software_licenses->getID())) {
                             $computer_soft_l['computers_id'] = $computers_id;
                             $computer_soft_l['softwarelicenses_id'] = $software_licenses->getID();
                             $computer_soft_l['is_dynamic'] = -1;
                             $computer_softwarelicenses->add($computer_soft_l);
                         }
                     }
                     unset($imported[$id]);
                 } else {
                     //------------------------------------------------------------------------//
                     //---- The software doesn't exists in this license for this computer -----//
                     //------------------------------------------------------------------------//
                     if ($software_licenses->getFromDBByQuery("WHERE `softwares_id` = " . $softwares_id . " \n                                                         AND `serial` = '" . $ocsOfficePack['OFFICEKEY'] . "'\n                                                         AND `softwareversions_id_use` = " . $softwareversions_id)) {
                         $id_software_licenses = $software_licenses->getID();
                     } else {
                         $software_licenses->fields['softwares_id'] = $softwares_id;
                         $id_software_licenses = $software_licenses->add($soft_l, array(), $cfg_ocs['history_software']);
                     }
                     if ($id_software_licenses) {
                         $computer_soft_l['computers_id'] = $computers_id;
                         $computer_soft_l['softwarelicenses_id'] = $id_software_licenses;
                         $computer_soft_l['is_dynamic'] = 1;
                         $computer_soft_l['number'] = -1;
                         $computer_softwarelicenses->add($computer_soft_l);
                     }
                 }
             }
         }
     }
     foreach ($imported as $id => $unused) {
         $computer_softwarelicenses->delete(array('id' => $id), true, $cfg_ocs['history_software']);
         // delete cause a getFromDB, so fields contains values
         $verid = $computer_softwarelicenses->getField('softwareversions_id');
         if (countElementsInTable('glpi_computers_softwarelicenses', "softwarelicenses_id = '{$verid}'") == 0) {
             $vers = new SoftwareVersion();
             if ($vers->getFromDB($verid) && countElementsInTable('glpi_softwarelicenses', "softwares_id = '" . $vers->fields['softwares_id'] . "'") == 0) {
                 $soft = new Software();
                 $soft->delete(array('id' => $vers->fields['softwares_id']), 1);
             }
             $vers->delete(array("id" => $verid));
         }
     }
 }