Inheritance: extends CommonDBRelation
 static function pdfForSoftware(PluginPdfSimplePDF $pdf, Software $item)
 {
     global $DB;
     $sID = $item->getField('id');
     $query = "SELECT `glpi_softwareversions`.*,\n                       `glpi_states`.`name` AS sname,\n                       `glpi_operatingsystems`.`name` AS osname\n                FROM `glpi_softwareversions`\n                LEFT JOIN `glpi_states`\n                     ON (`glpi_states`.`id` = `glpi_softwareversions`.`states_id`)\n                LEFT JOIN `glpi_operatingsystems`\n                     ON (`glpi_operatingsystems`.`id` = `glpi_softwareversions`.`operatingsystems_id`)\n                WHERE (`softwares_id` = '" . $sID . "')\n                ORDER BY `name`";
     $pdf->setColumnsSize(100);
     $pdf->displayTitle('<b>' . SoftwareVersion::getTypeName(2) . '</b>');
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) > 0) {
             $pdf->setColumnsSize(13, 13, 30, 14, 30);
             $pdf->displayTitle('<b><i>' . SoftwareVersion::getTypeName(2) . '</i></b>', '<b><i>' . __('Status') . '</i></b>', '<b><i>' . __('Operating system') . '</i></b>', '<b><i>' . _n('Installation', 'Installations', 2) . '</i></b>', '<b><i>' . __('Comments') . '</i></b>');
             $pdf->setColumnsAlign('left', 'left', 'left', 'right', 'left');
             for ($tot = $nb = 0; $data = $DB->fetch_assoc($result); $tot += $nb) {
                 $nb = Computer_SoftwareVersion::countForVersion($data['id']);
                 $pdf->displayLine(empty($data['name']) ? "(" . $data['id'] . ")" : $data['name'], $data['sname'], $data['osname'], $nb, str_replace(array("\r", "\n"), " ", $data['comment']));
             }
             $pdf->setColumnsAlign('left', 'right', 'left', 'right', 'left');
             $pdf->displayTitle('', '', "<b>" . sprintf(__('%1$s: %2$s'), __('Total') . "</b>", ''), $tot, '');
         } else {
             $pdf->displayLine(__('No item found'));
         }
     } else {
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
 /**
  * @test
  */
 public function ComputerSoftwareORBit2()
 {
     global $DB;
     $DB->connect();
     $computer_SoftwareVersion = new Computer_SoftwareVersion();
     $computer_SoftwareVersion->getFromDB(3);
     $a_reference = array('id' => '3', 'computers_id' => '1', 'softwareversions_id' => '3', 'is_deleted_computer' => '0', 'is_template_computer' => '0', 'entities_id' => '0', 'is_deleted' => '0', 'is_dynamic' => '1');
     $this->assertEquals($a_reference, $computer_SoftwareVersion->fields);
 }
         if ($item->isEntityAssign()) {
             $options = array('entities_id' => $_POST['entities_id']);
         }
         foreach ($_POST["item"] as $key => $val) {
             if ($val == 1) {
                 if ($item->getFromDB($key)) {
                     if (!$item->isEntityAssign() || $_POST['entities_id'] != $item->getEntityID()) {
                         $item->duplicate($options);
                     }
                 }
             }
         }
     }
     break;
 case "install":
     $inst = new Computer_SoftwareVersion();
     foreach ($_POST["item"] as $key => $val) {
         if ($val == 1) {
             $comp = new Computer();
             if ($comp->getFromDB($key) && $comp->fields["entities_id"] == $_SESSION["glpiactive_entity"]) {
                 $inst->add(array('computers_id' => $key, 'softwareversions_id' => $_POST["softwareversions_id"]));
             }
         }
     }
     break;
 case "add_group":
     $groupuser = new Group_User();
     foreach ($_POST["item"] as $key => $val) {
         if ($val == 1) {
             $input = array('groups_id' => $_POST["groups_id"], 'users_id' => $key);
             if ($groupuser->can(-1, 'w', $input)) {
 /**
  * @since version 0.85
  *
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     global $DB;
     switch ($ma->getAction()) {
         case 'move_version':
             $input = $ma->getInput();
             if (isset($input['softwareversions_id'])) {
                 foreach ($ids as $id) {
                     if ($item->can($id, UPDATE)) {
                         //Process rules
                         if ($item->update(array('id' => $id, 'softwareversions_id' => $input['softwareversions_id']))) {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                         } else {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                             $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                         }
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                         $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                     }
                 }
             } else {
                 $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
             }
             return;
         case 'add':
             $itemtoadd = new Computer_SoftwareVersion();
             if (isset($_POST['peer_softwareversions_id'])) {
                 foreach ($ids as $id) {
                     if ($item->can($id, UPDATE)) {
                         //Process rules
                         if ($itemtoadd->add(array('computers_id' => $id, 'softwareversions_id' => $_POST['peer_softwareversions_id']))) {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                         } else {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                             $ma->addMessage($itemtoadd->getErrorMessage(ERROR_ON_ACTION));
                         }
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                         $ma->addMessage($itemtoadd->getErrorMessage(ERROR_RIGHT));
                     }
                 }
             } else {
                 $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
             }
             return;
     }
     parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
 }
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";
$inst = new Computer_SoftwareVersion();
// From Computer - Software tab (add form or from not installed license)
if (isset($_REQUEST["install"])) {
    checkRight("software", "w");
    if (isset($_REQUEST["softwareversions_id"]) && isset($_REQUEST["computers_id"])) {
        $inst->add(array('computers_id' => $_REQUEST["computers_id"], 'softwareversions_id' => $_REQUEST["softwareversions_id"]));
        Event::log($_REQUEST["computers_id"], "computers", 5, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][110]);
    }
    glpi_header($_SERVER['HTTP_REFERER']);
    // From Computer - Software tab (installed software)
} else {
    if (isset($_GET["uninstall"])) {
        checkRight("software", "w");
        $inst->delete(array('id' => $_GET["id"]));
        Event::log($_GET["computers_id"], "computers", 5, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][111]);
        glpi_header($_SERVER['HTTP_REFERER']);
 /**
  * Show Versions of a software
  *
  * @param $soft Software object
  * @return nothing
  **/
 static function showForSoftware($soft)
 {
     global $DB, $CFG_GLPI, $LANG;
     $softwares_id = $soft->getField('id');
     if (!$soft->can($softwares_id, 'r')) {
         return false;
     }
     $canedit = $soft->can($softwares_id, "w");
     echo "<div class='spaced'>";
     $query = "SELECT `glpi_softwareversions`.*,\n                       `glpi_states`.`name` AS sname\n                FROM `glpi_softwareversions`\n                LEFT JOIN `glpi_states` ON (`glpi_states`.`id` = `glpi_softwareversions`.`states_id`)\n                WHERE `softwares_id` = '{$softwares_id}'\n                ORDER BY `name`";
     initNavigateListItems('SoftwareVersion', $LANG['help'][31] . " = " . $soft->fields["name"]);
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result)) {
             echo "<table class='tab_cadre'><tr>";
             echo "<th>&nbsp;" . $LANG['software'][5] . "&nbsp;</th>";
             echo "<th>&nbsp;" . $LANG['state'][0] . "&nbsp;</th>";
             echo "<th>&nbsp;" . $LANG['setup'][5] . "&nbsp;</th>";
             echo "<th>&nbsp;" . $LANG['software'][19] . "&nbsp;</th>";
             echo "<th>&nbsp;" . $LANG['common'][25] . "&nbsp;</th>";
             echo "</tr>\n";
             for ($tot = $nb = 0; $data = $DB->fetch_assoc($result); $tot += $nb) {
                 addToNavigateListItems('SoftwareVersion', $data['id']);
                 $nb = Computer_SoftwareVersion::countForVersion($data['id']);
                 echo "<tr class='tab_bg_2'>";
                 echo "<td><a href='softwareversion.form.php?id=" . $data['id'] . "'>";
                 echo $data['name'] . (empty($data['name']) ? $data['id'] : "") . "</a></td>";
                 echo "<td>" . $data['sname'] . "</td>";
                 echo "<td class='right'>" . Dropdown::getDropdownName('glpi_operatingsystems', $data['operatingsystems_id']);
                 echo "</td>";
                 echo "<td class='right'>{$nb}&nbsp;&nbsp;</td>";
                 echo "<td>" . $data['comment'] . "</td></tr>\n";
             }
             echo "<tr class='tab_bg_1'><td class='right b' colspan='3'>" . $LANG['common'][33] . "</td>";
             echo "<td class='right b'>{$tot}&nbsp;&nbsp;</td><td>";
             if ($canedit) {
                 echo "<a href='softwareversion.form.php?softwares_id={$softwares_id}'>" . $LANG['software'][7] . "</a>";
             }
             echo "</td></tr>";
             echo "</table>\n";
         } else {
             echo "<table class='tab_cadre_fixe'>";
             echo "<tr><th>" . $LANG['search'][15] . "</th></tr>";
             if ($canedit) {
                 echo "<tr class='tab_bg_2'><td class='center'>";
                 echo "<a href='softwareversion.form.php?softwares_id={$softwares_id}'>" . $LANG['software'][7] . "</a></td></tr>";
             }
             echo "</table>\n";
         }
     }
     echo "</div>";
 }
 static function pdfForVersionByEntity(PluginPdfSimplePDF $pdf, SoftwareVersion $version)
 {
     global $DB, $CFG_GLPI;
     $softwareversions_id = $version->getField('id');
     $pdf->setColumnsSize(75, 25);
     $pdf->setColumnsAlign('left', 'right');
     $pdf->displayTitle('<b>' . __('Entity'), _n('Installation', 'Installations', 2) . '</b>');
     $lig = $tot = 0;
     if (in_array(0, $_SESSION["glpiactiveentities"])) {
         $nb = Computer_SoftwareVersion::countForVersion($softwareversions_id, 0);
         if ($nb > 0) {
             $pdf->displayLine(__('Root entity'), $nb);
             $tot += $nb;
             $lig++;
         }
     }
     $sql = "SELECT `id`, `completename`\n              FROM `glpi_entities` " . getEntitiesRestrictRequest('WHERE', 'glpi_entities') . "\n              ORDER BY `completename`";
     foreach ($DB->request($sql) as $ID => $data) {
         $nb = Computer_SoftwareVersion::countForVersion($softwareversions_id, $ID);
         if ($nb > 0) {
             $pdf->displayLine($data["completename"], $nb);
             $tot += $nb;
             $lig++;
         }
     }
     if ($tot > 0) {
         if ($lig > 1) {
             $pdf->displayLine(__('Total'), $tot);
         }
     } else {
         $pdf->setColumnsSize(100);
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
/** 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");
}
}
if (!isset($_REQUEST['glpi_tab'])) {
    exit;
}
if (!isset($_POST["sort"])) {
    $_POST["sort"] = "";
}
if (!isset($_POST["order"])) {
    $_POST["order"] = "";
}
checkRight("software", "r");
$version = new SoftwareVersion();
if ($_POST["id"] > 0 && $version->can($_POST["id"], 'r')) {
    switch ($_REQUEST['glpi_tab']) {
        case -1:
            Computer_SoftwareVersion::showForVersion($version);
            Plugin::displayAction($version, $_REQUEST['glpi_tab']);
            break;
        case 2:
            Computer_SoftwareVersion::showForVersion($version);
            break;
        case 12:
            Log::showForItem($version);
            break;
        default:
            if (!Plugin::displayAction($version, $_REQUEST['glpi_tab'])) {
                Computer_SoftwareVersion::showForVersionByEntity($version);
            }
    }
}
ajaxFooter();
Example #10
0
     ComputerDisk::showForComputer($computer, $_POST["withtemplate"]);
     Computer_SoftwareVersion::showForComputer($computer);
     Computer_Item::showForComputer($_POST['target'], $computer);
     NetworkPort::showForItem('Computer', $_POST["id"]);
     Infocom::showForItem($computer);
     Contract::showAssociated($computer, $_POST["withtemplate"]);
     Document::showAssociated($computer);
     Ticket::showListForItem('Computer', $_POST["id"]);
     Link::showForItem('Computer', $_POST["id"]);
     RegistryKey::showForComputer($_POST["id"]);
     ComputerVirtualMachine::showForVirtualMachine($computer);
     ComputerVirtualMachine::showForComputer($computer);
     Plugin::displayAction($computer, $_REQUEST['glpi_tab']);
     break;
 case 2:
     Computer_SoftwareVersion::showForComputer($computer);
     break;
 case 3:
     Computer_Item::showForComputer($_POST['target'], $computer);
     NetworkPort::showForItem('Computer', $_POST["id"]);
     break;
 case 4:
     Infocom::showForItem($computer);
     Contract::showAssociated($computer);
     break;
 case 5:
     Document::showAssociated($computer);
     break;
 case 6:
     Ticket::showListForItem('Computer', $_POST["id"]);
     break;
Example #11
0
 /**
  * @see CommonDBTM::doSpecificMassiveActions()
  **/
 function doSpecificMassiveActions($input = array())
 {
     $res = array('ok' => 0, 'ko' => 0, 'noright' => 0);
     switch ($input['action']) {
         case "connect":
             $ci = new Computer_Item();
             return $ci->doSpecificMassiveActions($input);
         case "install":
             if (isset($input['softwareversions_id']) && $input['softwareversions_id'] > 0) {
                 $inst = new Computer_SoftwareVersion();
                 foreach ($input['item'] as $key => $val) {
                     if ($val == 1) {
                         $input2 = array('computers_id' => $key, 'softwareversions_id' => $input['softwareversions_id']);
                         if ($inst->can(-1, 'w', $input2)) {
                             if ($inst->add($input2)) {
                                 $res['ok']++;
                             } else {
                                 $res['ko']++;
                             }
                         } else {
                             $res['noright']++;
                         }
                     }
                 }
             } else {
                 $res['ko']++;
             }
             break;
         default:
             return parent::doSpecificMassiveActions($input);
     }
     return $res;
 }
 /**
  * Show softwares candidates to be merged with the current
  *
  * @return nothing
  **/
 function showMergeCandidates()
 {
     global $DB, $CFG_GLPI, $LANG;
     $ID = $this->getField('id');
     $this->check($ID, "w");
     $rand = mt_rand();
     echo "<div class='center'>";
     $sql = "SELECT `glpi_softwares`.`id`,\n                     `glpi_softwares`.`name`,\n                     `glpi_entities`.`completename` AS entity\n              FROM `glpi_softwares`\n              LEFT JOIN `glpi_entities` ON (`glpi_softwares`.`entities_id` = `glpi_entities`.`id`)\n              WHERE (`glpi_softwares`.`id` != '{$ID}'\n                     AND `glpi_softwares`.`name` = '" . addslashes($this->fields["name"]) . "'\n                     AND `glpi_softwares`.`is_deleted` = '0'\n                     AND `glpi_softwares`.`is_template` = '0' " . getEntitiesRestrictRequest('AND', 'glpi_softwares', 'entities_id', getSonsOf("glpi_entities", $this->fields["entities_id"]), false) . ")\n              ORDER BY `entity`";
     $req = $DB->request($sql);
     if ($req->numrows()) {
         $link = getItemTypeFormURL('Software');
         echo "<form method='post' name='mergesoftware_form{$rand}' id='mergesoftware_form{$rand}'\n                action='" . $link . "'>";
         echo "<table class='tab_cadre_fixehov'><tr><th>&nbsp;</th>";
         echo "<th>" . $LANG['common'][16] . "</th>";
         echo "<th>" . $LANG['entity'][0] . "</th>";
         echo "<th>" . $LANG['software'][19] . "</th>";
         echo "<th>" . $LANG['software'][11] . "</th></tr>";
         foreach ($req as $data) {
             echo "<tr class='tab_bg_2'>";
             echo "<td><input type='checkbox' name='item[" . $data["id"] . "]' value='1'></td>";
             echo "<td<a href='" . $link . "?id=" . $data["id"] . "'>" . $data["name"] . "</a></td>";
             echo "<td>" . $data["entity"] . "</td>";
             echo "<td class='right'>" . Computer_SoftwareVersion::countForSoftware($data["id"]) . "</td>";
             echo "<td class='right'>" . SoftwareLicense::countForSoftware($data["id"]) . "</td></tr>\n";
         }
         echo "</table>\n";
         openArrowMassive("mergesoftware_form{$rand}", true);
         echo "<input type='hidden' name='id' value='{$ID}'>";
         closeArrowMassive('mergesoftware', $LANG['software'][48]);
         echo "</form>";
     } else {
         echo $LANG['search'][15];
     }
     echo "</div>";
 }
Example #13
0
     }
 } else {
     switch ($_REQUEST['glpi_tab']) {
         case -1:
             SoftwareVersion::showForSoftware($soft);
             SoftwareLicense::showForSoftware($soft);
             Computer_SoftwareVersion::showForSoftware($soft);
             Infocom::showForItem($soft);
             Contract::showAssociated($soft);
             Document::showAssociated($soft);
             Ticket::showListForItem('Software', $_POST["id"]);
             Link::showForItem('Software', $_POST["id"]);
             Plugin::displayAction($soft, $_REQUEST['glpi_tab']);
             break;
         case 2:
             Computer_SoftwareVersion::showForSoftware($soft);
             break;
         case 4:
             Infocom::showForItem($soft);
             Contract::showAssociated($soft);
             break;
         case 5:
             Document::showAssociated($soft);
             break;
         case 6:
             Ticket::showListForItem('Software', $_POST["id"]);
             break;
         case 7:
             Link::showForItem('Software', $_POST["id"]);
             break;
         case 10:
Example #14
0
 /**
  * Update config of a new software
  *
  * This function create a new software in GLPI with some general data.
  *
  * @param $computers_id                         integer : glpi computer id.
  * @param $entity                               integer : entity of the computer
  * @param $ocsid                                integer : ocs computer id (ID).
  * @param $plugin_ocsinventoryng_ocsservers_id  integer : ocs server id
  * @param $cfg_ocs                              array   : ocs config
  * @param $import_software                      array   : already imported softwares
  * @param $dohistory                            boolean : log changes?
  *
  * @return Nothing (void).
  **/
 static function updateSoftware($computers_id, $entity, $ocsid, $plugin_ocsinventoryng_ocsservers_id, array $cfg_ocs, $dohistory)
 {
     global $DB, $PluginOcsinventoryngDBocs;
     $alread_processed = array();
     $is_utf8 = $cfg_ocs["ocs_db_utf8"];
     $computer_softwareversion = new Computer_SoftwareVersion();
     self::checkOCSconnection($plugin_ocsinventoryng_ocsservers_id);
     if ($cfg_ocs["import_software"]) {
         //---- Get all the softwares for this machine from OCS -----//
         if ($cfg_ocs["use_soft_dict"]) {
             $query2 = "SELECT `dico_soft`.`FORMATTED` AS NAME,\n                              `softwares`.`VERSION` AS VERSION,\n                              `softwares`.`PUBLISHER` AS PUBLISHER,\n                              `softwares`.`COMMENTS` AS COMMENTS\n                       FROM `softwares`\n                       INNER JOIN `dico_soft` ON (`softwares`.`NAME` = dico_soft.EXTRACTED)\n                       WHERE `softwares`.`HARDWARE_ID` = '{$ocsid}'";
         } else {
             $query2 = "SELECT `softwares`.`NAME` AS NAME,\n                              `softwares`.`VERSION` AS VERSION,\n                              `softwares`.`PUBLISHER` AS PUBLISHER,\n                              `softwares`.`COMMENTS` AS COMMENTS\n                       FROM `softwares`\n                       WHERE `softwares`.`HARDWARE_ID` = '{$ocsid}'";
         }
         $result2 = $PluginOcsinventoryngDBocs->query($query2);
         $soft = new Software();
         // Read imported software in last sync
         $query = "SELECT `glpi_computers_softwareversions`.`id` as id,\n                          `glpi_softwares`.`name` as sname,\n                          `glpi_softwareversions`.`name` as vname\n                   FROM `glpi_computers_softwareversions`\n                   INNER JOIN `glpi_softwareversions`\n                           ON `glpi_softwareversions`.`id`= `glpi_computers_softwareversions`.`softwareversions_id`\n                   INNER JOIN `glpi_softwares`\n                           ON `glpi_softwares`.`id`= `glpi_softwareversions`.`softwares_id`\n                   WHERE `glpi_computers_softwareversions`.`computers_id`='{$computers_id}'\n                         AND `is_dynamic`";
         $imported = array();
         foreach ($DB->request($query) as $data) {
             $imported[$data['id']] = strtolower($data['sname'] . self::FIELD_SEPARATOR . $data['vname']);
         }
         if ($PluginOcsinventoryngDBocs->numrows($result2) > 0) {
             while ($data2 = $PluginOcsinventoryngDBocs->fetch_array($result2)) {
                 $data2 = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data2));
                 //As we cannot be sure that data coming from OCS are in utf8, let's try to encode them
                 //if possible
                 foreach (array('NAME', 'PUBLISHER', 'VERSION') as $field) {
                     $data2[$field] = self::encodeOcsDataInUtf8($is_utf8, $data2[$field]);
                 }
                 //Replay dictionnary on manufacturer
                 $manufacturer = Manufacturer::processName($data2["PUBLISHER"]);
                 $version = $data2['VERSION'];
                 $name = $data2['NAME'];
                 //Software might be created in another entity, depending on the entity's configuration
                 $target_entity = Entity::getUsedConfig('entities_id_software', $entity, '', true);
                 //Do not change software's entity except if the dictionnary explicity changes it
                 if ($target_entity < 0) {
                     $target_entity = $entity;
                 }
                 $modified_name = $name;
                 $modified_version = $version;
                 $is_helpdesk_visible = NULL;
                 if (!$cfg_ocs["use_soft_dict"]) {
                     //Software dictionnary
                     $params = array("name" => $name, "manufacturer" => $manufacturer, "old_version" => $version, "entities_id" => $entity);
                     $rulecollection = new RuleDictionnarySoftwareCollection();
                     $res_rule = $rulecollection->processAllRules(Toolbox::stripslashes_deep($params), array(), Toolbox::stripslashes_deep(array('version' => $version)));
                     if (isset($res_rule["name"]) && $res_rule["name"]) {
                         $modified_name = $res_rule["name"];
                     }
                     if (isset($res_rule["version"]) && $res_rule["version"]) {
                         $modified_version = $res_rule["version"];
                     }
                     if (isset($res_rule["is_helpdesk_visible"]) && strlen($res_rule["is_helpdesk_visible"])) {
                         $is_helpdesk_visible = $res_rule["is_helpdesk_visible"];
                     }
                     if (isset($res_rule['manufacturer']) && $res_rule['manufacturer']) {
                         $manufacturer = Dropdown::getDropdownName('glpi_manufacturers', $res_rule['manufacturer']);
                         $manufacturer = Toolbox::addslashes_deep($manufacturer);
                     }
                     //If software dictionnary returns an entity, it overrides the one that may have
                     //been defined in the entity's configuration
                     if (isset($res_rule["new_entities_id"]) && strlen($res_rule["new_entities_id"])) {
                         $target_entity = $res_rule["new_entities_id"];
                     }
                 }
                 //If software must be imported
                 if (!isset($res_rule["_ignore_import"]) || !$res_rule["_ignore_import"]) {
                     // Clean software object
                     $soft->reset();
                     // EXPLANATION About dictionnaries
                     // OCS dictionnary : if software name change, as we don't store INITNAME
                     //     GLPI will detect an uninstall (oldname) + install (newname)
                     // GLPI dictionnary : is rule have change
                     //     if rule have been replayed, modifiedname will be found => ok
                     //     if not, GLPI will detect an uninstall (oldname) + install (newname)
                     $id = array_search(strtolower(stripslashes($modified_name . self::FIELD_SEPARATOR . $version)), $imported);
                     if ($id) {
                         //-------------------------------------------------------------------------//
                         //---- The software exists in this version for this computer --------------//
                         //---------------------------------------------------- --------------------//
                         unset($imported[$id]);
                     } else {
                         //------------------------------------------------------------------------//
                         //---- The software doesn't exists in this version for this computer -----//
                         //------------------------------------------------------------------------//
                         $isNewSoft = $soft->addOrRestoreFromTrash($modified_name, $manufacturer, $target_entity, '', $entity != $target_entity, $is_helpdesk_visible);
                         //Import version for this software
                         $versionID = self::importVersion($isNewSoft, $modified_version);
                         //Install license for this machine
                         $instID = self::installSoftwareVersion($computers_id, $versionID, $dohistory);
                     }
                 }
             }
         }
         foreach ($imported as $id => $unused) {
             $computer_softwareversion->delete(array('id' => $id, '_no_history' => !$dohistory), true);
             // delete cause a getFromDB, so fields contains values
             $verid = $computer_softwareversion->getField('softwareversions_id');
             if (countElementsInTable('glpi_computers_softwareversions', "softwareversions_id = '{$verid}'") == 0 && countElementsInTable('glpi_softwarelicenses', "softwareversions_id_buy = '{$verid}'") == 0) {
                 $vers = new SoftwareVersion();
                 if ($vers->getFromDB($verid) && countElementsInTable('glpi_softwarelicenses', "softwares_id = '" . $vers->fields['softwares_id'] . "'") == 0 && countElementsInTable('glpi_softwareversions', "softwares_id = '" . $vers->fields['softwares_id'] . "'") == 1) {
                     // 1 is the current to be removed
                     $soft->putInTrash($vers->fields['softwares_id'], __('Software deleted by OCSNG synchronization'));
                 }
                 $vers->delete(array("id" => $verid));
             }
         }
     }
 }
 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"]));
             }
         }
     }
 }
 /**
  * @since version 0.85
  *
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     global $DB;
     switch ($ma->getAction()) {
         case 'move_license':
             $input = $ma->getInput();
             if (isset($input['softwarelicenses_id'])) {
                 foreach ($ids as $id) {
                     if ($item->can($id, UPDATE)) {
                         //Process rules
                         if ($item->update(array('id' => $id, 'softwarelicenses_id' => $input['softwarelicenses_id']))) {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                         } else {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                             $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                         }
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                         $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                     }
                 }
             } else {
                 $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
             }
             return;
         case 'install':
             $csl = new self();
             $csv = new Computer_SoftwareVersion();
             foreach ($ids as $id) {
                 if ($csl->getFromDB($id)) {
                     $sl = new SoftwareLicense();
                     if ($sl->getFromDB($csl->fields["softwarelicenses_id"])) {
                         $version = 0;
                         if ($sl->fields["softwareversions_id_use"] > 0) {
                             $version = $sl->fields["softwareversions_id_use"];
                         } else {
                             $version = $sl->fields["softwareversions_id_buy"];
                         }
                         if ($version > 0) {
                             $params = array('computers_id' => $csl->fields['computers_id'], 'softwareversions_id' => $version);
                             //Get software name and manufacturer
                             if ($csv->can(-1, CREATE, $params)) {
                                 //Process rules
                                 if ($csv->add($params)) {
                                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
                                 } else {
                                     $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                                 }
                             } else {
                                 $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_NORIGHT);
                             }
                         } else {
                             $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                         }
                     } else {
                         $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
                     }
                 }
             }
             return;
     }
     parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
 }
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);
$inst = new Computer_SoftwareVersion();
// From Computer - Software tab (add form)
if (isset($_POST["add"])) {
    if (isset($_POST["computers_id"]) && $_POST["computers_id"] && isset($_POST["softwareversions_id"]) && $_POST["softwareversions_id"]) {
        if ($newID = $inst->add(array('computers_id' => $_POST["computers_id"], 'softwareversions_id' => $_POST["softwareversions_id"]))) {
            Event::log($_POST["computers_id"], "computers", 5, "inventory", sprintf(__('%s installs software'), $_SESSION["glpiname"]));
        }
    }
    Html::back();
}
Html::displayErrorAndDie('Lost');
 /**
  * Show Versions of a software
  *
  * @param $soft Software object
  *
  * @return nothing
  **/
 static function showForSoftware(Software $soft)
 {
     global $DB, $CFG_GLPI;
     $softwares_id = $soft->getField('id');
     if (!$soft->can($softwares_id, READ)) {
         return false;
     }
     $canedit = $soft->canEdit($softwares_id);
     echo "<div class='spaced'>";
     if ($canedit) {
         echo "<div class='center firstbloc'>";
         echo "<a class='vsubmit' href='softwareversion.form.php?softwares_id={$softwares_id}'>" . _x('button', 'Add a version') . "</a>";
         echo "</div>";
     }
     $query = "SELECT `glpi_softwareversions`.*,\n                       `glpi_states`.`name` AS sname\n                FROM `glpi_softwareversions`\n                LEFT JOIN `glpi_states` ON (`glpi_states`.`id` = `glpi_softwareversions`.`states_id`)\n                WHERE `softwares_id` = '{$softwares_id}'\n                ORDER BY `name`";
     Session::initNavigateListItems('SoftwareVersion', sprintf(__('%1$s = %2$s'), Software::getTypeName(1), $soft->getName()));
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result)) {
             echo "<table class='tab_cadre_fixehov'><tr>";
             echo "<th>" . self::getTypeName(Session::getPluralNumber()) . "</th>";
             echo "<th>" . __('Status') . "</th>";
             echo "<th>" . __('Operating system') . "</th>";
             echo "<th>" . _n('Installation', 'Installations', Session::getPluralNumber()) . "</th>";
             echo "<th>" . __('Comments') . "</th>";
             echo "</tr>\n";
             for ($tot = $nb = 0; $data = $DB->fetch_assoc($result); $tot += $nb) {
                 Session::addToNavigateListItems('SoftwareVersion', $data['id']);
                 $nb = Computer_SoftwareVersion::countForVersion($data['id']);
                 echo "<tr class='tab_bg_2'>";
                 echo "<td><a href='softwareversion.form.php?id=" . $data['id'] . "'>";
                 echo $data['name'] . (empty($data['name']) ? "(" . $data['id'] . ")" : "") . "</a></td>";
                 echo "<td>" . $data['sname'] . "</td>";
                 echo "<td class='right'>" . Dropdown::getDropdownName('glpi_operatingsystems', $data['operatingsystems_id']);
                 echo "</td>";
                 echo "<td class='numeric'>{$nb}</td>";
                 echo "<td>" . $data['comment'] . "</td></tr>\n";
             }
             echo "<tr class='tab_bg_1 noHover'><td class='right b' colspan='3'>" . __('Total') . "</td>";
             echo "<td class='numeric b'>{$tot}</td><td></td></tr>";
             echo "</table>\n";
         } else {
             echo "<table class='tab_cadre_fixe'>";
             echo "<tr><th>" . __('No item found') . "</th></tr>";
             echo "</table>\n";
         }
     }
     echo "</div>";
 }
 /**
  * @covers Computer_SoftwareVersion::updateDatasForComputer
  */
 public function testUpdateDatasFromComputer()
 {
     $c00 = 1566671;
     $computer1 = getItemByTypeName('Computer', '_test_pc01');
     $ver1 = getItemByTypeName('SoftwareVersion', '_test_softver_1', true);
     $ver2 = getItemByTypeName('SoftwareVersion', '_test_softver_2', true);
     // Do some installations
     $softver = new Computer_SoftwareVersion();
     $softver01 = $softver->add(['computers_id' => $computer1->getID(), 'softwareversions_id' => $ver1]);
     $this->assertGreaterThan(0, $softver01);
     $softver02 = $softver->add(['computers_id' => $computer1->getID(), 'softwareversions_id' => $ver2]);
     $this->assertGreaterThan(0, $softver02);
     foreach ([$softver01, $softver02] as $tsoftver) {
         $o = new Computer_SoftwareVersion();
         $o->getFromDb($tsoftver);
         $this->assertEquals('0', $o->getField('is_deleted_computer'));
     }
     //computer that does not exists
     $this->assertFalse($softver->updateDatasForComputer($c00));
     //update existing computer
     $input = $computer1->fields;
     $input['is_deleted'] = '1';
     $this->assertTrue($computer1->update($input));
     $this->assertEquals(2, $softver->updateDatasForComputer($computer1->getID()));
     //check if all has been updated
     foreach ([$softver01, $softver02] as $tsoftver) {
         $o = new Computer_SoftwareVersion();
         $o->getFromDb($tsoftver);
         $this->assertEquals('1', $o->getField('is_deleted_computer'));
     }
     //restore computer state
     $input['is_deleted'] = '0';
     $this->assertTrue($computer1->update($input));
 }
Example #20
0
 /**
  * Show softwares candidates to be merged with the current
  *
  * @return nothing
  **/
 function showMergeCandidates()
 {
     global $DB, $CFG_GLPI;
     $ID = $this->getField('id');
     $this->check($ID, "w");
     $rand = mt_rand();
     echo "<div class='center'>";
     $sql = "SELECT `glpi_softwares`.`id`,\n                     `glpi_softwares`.`name`,\n                     `glpi_entities`.`completename` AS entity\n              FROM `glpi_softwares`\n              LEFT JOIN `glpi_entities` ON (`glpi_softwares`.`entities_id` = `glpi_entities`.`id`)\n              WHERE (`glpi_softwares`.`id` != '{$ID}'\n                     AND `glpi_softwares`.`name` = '" . addslashes($this->fields["name"]) . "'\n                     AND `glpi_softwares`.`is_deleted` = '0'\n                     AND `glpi_softwares`.`is_template` = '0' " . getEntitiesRestrictRequest('AND', 'glpi_softwares', 'entities_id', getSonsOf("glpi_entities", $this->fields["entities_id"]), false) . ")\n              ORDER BY `entity`";
     $req = $DB->request($sql);
     if ($nb = $req->numrows()) {
         $link = Toolbox::getItemTypeFormURL('Software');
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $paramsma = array('num_displayed' => $nb, 'specific_actions' => array('mergesoftware' => __('Merge')));
         Html::showMassiveActions(__CLASS__, $paramsma);
         echo "<table class='tab_cadre_fixehov'>";
         echo "<tr><th width='10'>";
         echo Html::checkAllAsCheckbox('mass' . __CLASS__ . $rand);
         echo "</th>";
         echo "<th>" . __('Name') . "</th>";
         echo "<th>" . __('Entity') . "</th>";
         echo "<th>" . _n('Installation', 'Installations', 2) . "</th>";
         echo "<th>" . _n('License', 'Licenses', 2) . "</th></tr>";
         foreach ($req as $data) {
             echo "<tr class='tab_bg_2'>";
             echo "<td>" . Html::getMassiveActionCheckBox(__CLASS__, $data["id"]) . "</td>";
             echo "<td><a href='" . $link . "?id=" . $data["id"] . "'>" . $data["name"] . "</a></td>";
             echo "<td>" . $data["entity"] . "</td>";
             echo "<td class='right'>" . Computer_SoftwareVersion::countForSoftware($data["id"]) . "</td>";
             echo "<td class='right'>" . SoftwareLicense::countForSoftware($data["id"]) . "</td></tr>\n";
         }
         echo "</table>\n";
         echo "<input type='hidden' name='id' value='{$ID}'>";
         $paramsma['ontop'] = false;
         Html::showMassiveActions(__CLASS__, $paramsma);
         Html::closeForm();
     } else {
         _e('No item found');
     }
     echo "</div>";
 }
 /**
  * @since version 0.84
  *
  * @see CommonDBTM::doSpecificMassiveActions()
  **/
 function doSpecificMassiveActions($input = array())
 {
     $res = array('ok' => 0, 'ko' => 0, 'noright' => 0);
     switch ($input['action']) {
         case "move_license":
             if (isset($input['softwarelicenses_id'])) {
                 foreach ($input["item"] as $key => $val) {
                     if ($val == 1) {
                         //Get software name and manufacturer
                         if ($this->can($key, 'w')) {
                             //Process rules
                             if ($this->update(array('id' => $key, 'softwarelicenses_id' => $input['softwarelicenses_id']))) {
                                 $res['ok']++;
                             } else {
                                 $res['ko']++;
                             }
                         } else {
                             $res['noright']++;
                         }
                     }
                 }
             } else {
                 $res['ko']++;
             }
             break;
         case "install":
             $csl = new self();
             $csv = new Computer_SoftwareVersion();
             foreach ($input["item"] as $key => $val) {
                 if ($val == 1) {
                     if ($csl->getFromDB($key)) {
                         $sl = new SoftwareLicense();
                         if ($sl->getFromDB($csl->fields["softwarelicenses_id"])) {
                             $version = 0;
                             if ($sl->fields["softwareversions_id_use"] > 0) {
                                 $version = $sl->fields["softwareversions_id_use"];
                             } else {
                                 $version = $sl->fields["softwareversions_id_buy"];
                             }
                             if ($version > 0) {
                                 $params = array('computers_id' => $csl->fields['computers_id'], 'softwareversions_id' => $version);
                                 //Get software name and manufacturer
                                 if ($csv->can(-1, 'w', $params)) {
                                     //Process rules
                                     if ($csv->add($params)) {
                                         $res['ok']++;
                                     } else {
                                         $res['ko']++;
                                     }
                                 } else {
                                     $res['noright']++;
                                 }
                             } else {
                                 $res['ko']++;
                             }
                         } else {
                             $res['ko']++;
                         }
                     } else {
                         $res['ko']++;
                     }
                 }
             }
             break;
         default:
             return parent::doSpecificMassiveActions($input);
     }
     return $res;
 }
Example #22
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']);
 }
 /**
  * Update config of a new software
  *
  * This function create a new software in GLPI with some general datas.
  *
  * @param $computers_id integer : glpi computer id.
  * @param $entity integer : entity of the computer
  * @param $ocsid integer : ocs computer id (ID).
  * @param $ocsservers_id integer : ocs server id
  * @param $cfg_ocs array : ocs config
  * @param $import_software array : already imported softwares
  * @param $dohistory boolean : log changes ?
  *
  * @return Nothing (void).
  **/
 static function updateSoftware($computers_id, $entity, $ocsid, $ocsservers_id, $cfg_ocs, $import_software, $dohistory)
 {
     global $DB, $DBocs, $LANG;
     self::checkOCSconnection($ocsservers_id);
     if ($cfg_ocs["import_software"]) {
         //------------------------------------------------------------------------------//
         //---- Import_software array is not in the new form ( ID => name+version) ------//
         //------------------------------------------------------------------------------//
         if (!in_array(self::IMPORT_TAG_070, $import_software)) {
             //Add the tag of the version at the beginning of the array
             $softs_array[0] = self::IMPORT_TAG_070;
             //For each element of the table, add instID=>name.version
             foreach ($import_software as $key => $value) {
                 $query_softs = "SELECT `glpi_softwareversions`.`name` AS version\n                               FROM `glpi_computers_softwareversions`,\n                                    `glpi_softwareversions`\n                               WHERE `glpi_computers_softwareversions`.`softwareversions_id`\n                                          =`glpi_softwareversions`.`id`\n                                     AND `glpi_computers_softwareversions`.`computers_id`\n                                          = '{$computers_id}'\n                                     AND `glpi_computers_softwareversions`.`id` = '{$key}'";
                 $result_softs = $DB->query($query_softs);
                 $softs = $DB->fetch_array($result_softs);
                 $softs_array[$key] = $value . self::FIELD_SEPARATOR . $softs["version"];
             }
             //Replace in GLPI database the import_software by the new one
             self::replaceOcsArray($computers_id, $softs_array, "import_software");
             // Get import_software from the GLPI db
             $query = "SELECT `import_software`\n                      FROM `glpi_ocslinks`\n                      WHERE `computers_id` = '{$computers_id}'";
             $result = $DB->query($query);
             //Reload import_software from DB
             if ($DB->numrows($result)) {
                 $tmp = $DB->fetch_array($result);
                 $import_software = importArrayFromDB($tmp["import_software"]);
             }
         }
         //---- Get all the softwares for this machine from OCS -----//
         if ($cfg_ocs["use_soft_dict"]) {
             $query2 = "SELECT `softwares`.`NAME` AS INITNAME,\n                              `dico_soft`.`FORMATTED` AS NAME,\n                              `softwares`.`VERSION` AS VERSION,\n                              `softwares`.`PUBLISHER` AS PUBLISHER,\n                              `softwares`.`COMMENTS` AS COMMENTS\n                       FROM `softwares`\n                       INNER JOIN `dico_soft` ON (`softwares`.`NAME` = dico_soft.EXTRACTED)\n                       WHERE `softwares`.`HARDWARE_ID` = '{$ocsid}'";
         } else {
             $query2 = "SELECT `softwares`.`NAME` AS INITNAME,\n                              `softwares`.`NAME` AS NAME,\n                              `softwares`.`VERSION` AS VERSION,\n                              `softwares`.`PUBLISHER` AS PUBLISHER,\n                              `softwares`.`COMMENTS` AS COMMENTS\n                       FROM `softwares`\n                       WHERE `softwares`.`HARDWARE_ID` = '{$ocsid}'";
         }
         $result2 = $DBocs->query($query2);
         $to_add_to_ocs_array = array();
         $soft = new Software();
         if ($DBocs->numrows($result2) > 0) {
             while ($data2 = $DBocs->fetch_array($result2)) {
                 $data2 = clean_cross_side_scripting_deep(addslashes_deep($data2));
                 $initname = $data2["INITNAME"];
                 // Hack for OCS encoding problems
                 if (!$cfg_ocs["ocs_db_utf8"] && !seems_utf8($initname)) {
                     $initname = encodeInUtf8($initname);
                 }
                 $name = $data2["NAME"];
                 // Hack for OCS encoding problems
                 if (!$cfg_ocs["ocs_db_utf8"] && !seems_utf8($name)) {
                     $name = encodeInUtf8($name);
                 }
                 // Hack for OCS encoding problems
                 if (!$cfg_ocs["ocs_db_utf8"] && !seems_utf8($data2["PUBLISHER"])) {
                     $data2["PUBLISHER"] = encodeInUtf8($data2["PUBLISHER"]);
                 }
                 $version = $data2["VERSION"];
                 $manufacturer = Manufacturer::processName($data2["PUBLISHER"]);
                 $use_glpi_dictionnary = false;
                 if (!$cfg_ocs["use_soft_dict"]) {
                     //Software dictionnary
                     $rulecollection = new RuleDictionnarySoftwareCollection();
                     $res_rule = $rulecollection->processAllRules(array("name" => $name, "manufacturer" => $manufacturer, "old_version" => $version), array(), array('version' => $version));
                     $res_rule = addslashes_deep($res_rule);
                     if (isset($res_rule["name"])) {
                         $modified_name = $res_rule["name"];
                     } else {
                         $modified_name = $name;
                     }
                     if (isset($res_rule["version"]) && $res_rule["version"] != '') {
                         $modified_version = $res_rule["version"];
                     } else {
                         $modified_version = $version;
                     }
                 } else {
                     $modified_name = $name;
                     $modified_version = $version;
                 }
                 //Ignore this software
                 if (!isset($res_rule["_ignore_ocs_import"]) || !$res_rule["_ignore_ocs_import"]) {
                     // Clean software object
                     $soft->reset();
                     //If name+version not in present for this computer in glpi, add it
                     if (!in_array(stripslashes($initname . self::FIELD_SEPARATOR . $version), $import_software)) {
                         //------------------------------------------------------------------------//
                         //---- The software doesn't exists in this version for this computer -----//
                         //------------------------------------------------------------------------//
                         $isNewSoft = $soft->addOrRestoreFromTrash($modified_name, $manufacturer, $entity);
                         //Import version for this software
                         $versionID = self::importVersion($isNewSoft, $modified_version);
                         //Install license for this machine
                         $instID = self::installSoftwareVersion($computers_id, $versionID, $dohistory);
                         //Add the software to the table of softwares for this computer to add in database
                         $to_add_to_ocs_array[$instID] = $initname . self::FIELD_SEPARATOR . $version;
                     } else {
                         $instID = -1;
                         //-------------------------------------------------------------------------//
                         //---- The software exists in this version for this computer --------------//
                         //---------------------------------------------------- --------------------//
                         //Get the name of the software in GLPI to know if the software's name
                         //have already been changed by the OCS dictionnary
                         $instID = array_search(stripslashes($initname . self::FIELD_SEPARATOR . $version), $import_software);
                         $query_soft = "SELECT `glpi_softwares`.`id`,\n                                           `glpi_softwares`.`name`,\n                                           `glpi_softwares`.`entities_id`\n                                    FROM `glpi_softwares`,\n                                         `glpi_computers_softwareversions`,\n                                         `glpi_softwareversions`\n                                    WHERE `glpi_computers_softwareversions`.`id` = '{$instID}'\n                                          AND `glpi_computers_softwareversions`.`softwareversions_id`\n                                                = `glpi_softwareversions`.`id`\n                                          AND `glpi_softwareversions`.`softwares_id`\n                                                = `glpi_softwares`.`id`";
                         $result_soft = $DB->query($query_soft);
                         $tmpsoft = $DB->fetch_array($result_soft);
                         $softName = $tmpsoft["name"];
                         $softID = $tmpsoft["id"];
                         $s = new Software();
                         $input["id"] = $softID;
                         $input["entities_id"] = $tmpsoft['entities_id'];
                         //First, get the name of the software into GLPI db IF dictionnary is used
                         if ($cfg_ocs["use_soft_dict"]) {
                             //First use of the OCS dictionnary OR name changed in the dictionnary
                             if ($softName != $name) {
                                 $input["name"] = $name;
                                 $s->update($input);
                             }
                         } else {
                             if ($softName != $modified_name) {
                                 // OCS Dictionnary not use anymore : revert to original name
                                 $input["name"] = $modified_name;
                                 $s->update($input);
                             }
                         }
                         unset($import_software[$instID]);
                     }
                 }
             }
         }
         //Remove the tag from the import_software array
         unset($import_software[0]);
         //Add all the new softwares
         if (count($to_add_to_ocs_array)) {
             self::addToOcsArray($computers_id, $to_add_to_ocs_array, "import_software");
         }
         // Remove softwares not present in OCS
         if (count($import_software)) {
             $inst = new Computer_SoftwareVersion();
             foreach ($import_software as $key => $val) {
                 $query = "SELECT *\n                         FROM `glpi_computers_softwareversions`\n                         WHERE `id` = '{$key}'";
                 $result = $DB->query($query);
                 if ($DB->numrows($result) > 0) {
                     if ($data = $DB->fetch_assoc($result)) {
                         $inst->delete(array('id' => $key, '_no_history' => !$dohistory));
                         if (countElementsInTable('glpi_computers_softwareversions', "softwareversions_id = '" . $data['softwareversions_id'] . "'") == 0 && countElementsInTable('glpi_softwarelicenses', "softwareversions_id_buy = '" . $data['softwareversions_id'] . "'") == 0) {
                             $vers = new SoftwareVersion();
                             if ($vers->getFromDB($data['softwareversions_id']) && countElementsInTable('glpi_softwarelicenses', "softwares_id = '" . $vers->fields['softwares_id'] . "'") == 0 && countElementsInTable('glpi_softwareversions', "softwares_id = '" . $vers->fields['softwares_id'] . "'") == 1) {
                                 // 1 is the current to be removed
                                 $soft->putInTrash($vers->fields['softwares_id'], $LANG['ocsng'][54]);
                             }
                             $vers->delete(array("id" => $data['softwareversions_id']));
                         }
                     }
                 }
                 self::deleteInOcsArray($computers_id, $key, "import_software");
             }
         }
     }
 }