Relation between Group and User
Наследование: extends CommonDBRelation
 function cleanDBonPurge()
 {
     global $DB;
     $gu = new Group_User();
     $gu->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     $gt = new Group_Ticket();
     $gt->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     $gp = new Group_Problem();
     $gp->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     $cg = new Change_Group();
     $cg->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     $query1 = "DELETE\n                 FROM `glpi_projecttaskteams`\n                 WHERE `items_id` = '" . $this->fields['id'] . "'\n                       AND `itemtype` = '" . __CLASS__ . "'";
     $DB->query($query1);
     $query1 = "DELETE\n                 FROM `glpi_projectteams`\n                 WHERE `items_id` = '" . $this->fields['id'] . "'\n                       AND `itemtype` = '" . __CLASS__ . "'";
     $DB->query($query1);
     $gki = new Group_KnowbaseItem();
     $gki->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     $gr = new Group_Reminder();
     $gr->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     // Ticket rules use various _groups_id_*
     Rule::cleanForItemAction($this, '_groups_id%');
     Rule::cleanForItemCriteria($this, '_groups_id%');
     // GROUPS for RuleMailcollector
     Rule::cleanForItemCriteria($this, 'GROUPS');
     // Set no group to consumables
     $query = "UPDATE `glpi_consumables`\n                SET `items_id` = '0'\n                WHERE `items_id` = '" . $this->fields['id'] . "'\n                      AND `itemtype` = 'Group'";
     $DB->query($query);
 }
Пример #2
0
 function cleanDBonPurge()
 {
     global $DB;
     $gu = new Group_User();
     $gu->cleanDBonItemDelete($this->getType(), $this->fields['id']);
     $gt = new Group_Ticket();
     $gt->cleanDBonItemDelete($this->getType(), $this->fields['id']);
 }
Пример #3
0
 function getGroups($ticket_id, $removeAlreadyAssigned = true)
 {
     $groups = $user_groups = $ticket_groups = array();
     // get groups for user connected
     $tmp_user_groups = Group_User::getUserGroups($_SESSION['glpiID']);
     foreach ($tmp_user_groups as $current_group) {
         $user_groups[$current_group['id']] = $current_group['id'];
         $groups[$current_group['id']] = $current_group['id'];
     }
     // get groups already assigned in the ticket
     if ($ticket_id > 0) {
         $ticket = new Ticket();
         $ticket->getFromDB($ticket_id);
         foreach ($ticket->getGroups(CommonITILActor::ASSIGN) as $current_group) {
             $ticket_groups[$current_group['groups_id']] = $current_group['groups_id'];
         }
     }
     // To do an escalation, the user must be in a group currently assigned to the ticket
     // or no group is assigned to the ticket
     // TODO : matching with "view all tickets (yes/no) option in profile user"
     if (!empty($ticket_groups) && count(array_intersect($ticket_groups, $user_groups)) == 0) {
         return array();
     }
     //get all group which we can climb
     if (count($groups) > 0) {
         $group_group = $this->find("groups_id_source IN (" . implode(", ", $groups) . ")");
         foreach ($group_group as $current_group) {
             $groups[$current_group['groups_id_destination']] = $current_group['groups_id_destination'];
         }
     }
     //remove already assigned groups
     if (!empty($ticket_groups) && $removeAlreadyAssigned) {
         $groups = array_diff_assoc($groups, $ticket_groups);
     }
     //add name to returned groups and remove non assignable groups
     $group_obj = new Group();
     foreach ($groups as $groups_id => &$groupname) {
         $group_obj->getFromDB($groups_id);
         //check if we can assign this group
         if ($group_obj->fields['is_assign'] == 0) {
             unset($groups[$groups_id]);
             continue;
         }
         //add name
         $groupname = $group_obj->fields['name'];
     }
     //sort by group name (and keep associative index)
     asort($groups);
     return $groups;
 }
Пример #4
0
 static function pdfForGroup(PluginPdfSimplePDF $pdf, Group $group, $tree)
 {
     global $DB, $CFG_GLPI;
     $used = array();
     $ids = array();
     // Retrieve member list
     $entityrestrict = Group_User::getDataForGroup($group, $used, $ids, '', $tree);
     $title = "<b>" . sprintf(__('%1$s (%2$s)'), _n('User', 'Users', 2) . "</b>", __('D=Dynamic'));
     $number = count($used);
     if ($number > $_SESSION['glpilist_limit']) {
         $title = sprintf(__('%1$s (%2$s)'), $title, $_SESSION['glpilist_limit'] . "/" . $number);
     } else {
         $title = sprintf(__('%1$s (%2$s)'), $title, $number);
     }
     $pdf->setColumnsSize(100);
     $pdf->displayTitle($title);
     if ($number) {
         $user = new User();
         $group = new Group();
         if ($tree) {
             $pdf->setColumnsSize(35, 45, 10, 10);
             $pdf->displayTitle(User::getTypeName(1), Group::getTypeName(1), __('Manager'), __('Delegatee'));
         } else {
             $pdf->setColumnsSize(60, 20, 20);
             $pdf->displayTitle(User::getTypeName(1), __('Manager'), __('Delegatee'));
         }
         for ($i = 0; $i < $number && $i < $_SESSION['glpilist_limit']; $i++) {
             $data = $used[$i];
             $name = Html::clean(getUserName($data["id"]));
             if ($data["is_dynamic"]) {
                 $name = sprintf(__('%1$s (%2$s)'), $name, '<b>' . __('D') . '</b>');
             }
             if ($tree) {
                 $group->getFromDB($data["groups_id"]);
                 $pdf->displayLine($name, $group->getName(), Dropdown::getYesNo($data['is_manager']), Dropdown::getYesNo($data['is_userdelegate']));
             } else {
                 $pdf->displayLine($name, Dropdown::getYesNo($data['is_manager']), Dropdown::getYesNo($data['is_userdelegate']));
             }
         }
     } else {
         $pdf->setColumnsAlign('center');
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
Пример #5
0
 static function checkGroupUserFromForm($formID)
 {
     //$formID = $_REQUEST['id'];
     $grupos = Group_User::getUserGroups($_SESSION['glpiID']);
     $gruposUsuario = array("0");
     $found = 0;
     foreach ($grupos as $grupo) {
         if (in_array($grupo['id'], PluginFormcreatorForm::getGroupForm($formID))) {
             $found = 1;
         }
     }
     return $found;
 }
Пример #6
0
// ----------------------------------------------------------------------
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
header_nocache();
if (!isset($_POST["id"])) {
    exit;
}
checkRight("group", "r");
$group = new Group();
if ($_POST["id"] > 0 && $group->can($_POST["id"], 'r')) {
    switch ($_REQUEST['glpi_tab']) {
        case -1:
            Group_User::showForGroup($_POST['target'], $group);
            $group->showItems();
            $group->showLDAPForm($_POST['target'], $_POST["id"]);
            Plugin::displayAction($group, $_REQUEST['glpi_tab']);
            break;
        case 2:
            $group->showItems();
            break;
        case 3:
            $group->showLDAPForm($_POST['target'], $_POST["id"]);
            break;
        default:
            if (!Plugin::displayAction($group, $_REQUEST['glpi_tab'])) {
                Group_User::showForGroup($_POST['target'], $group);
            }
    }
}
ajaxFooter();
Пример #7
0
/** 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");
}
Пример #8
0
 static function deleteGroups($user_ID, $only_dynamic = false)
 {
     global $DB;
     $crit['users_id'] = $user_ID;
     if ($only_dynamic) {
         $crit['is_dynamic'] = '1';
     }
     $obj = new Group_User();
     $obj->deleteByCriteria($crit);
 }
Пример #9
0
 /**
  * Recieve 'All users of a group' data from self::showAddGroupUsersForm and save them to session and DB
  *
  * @since 9.1
  *
  * @param $params (array) : must contais form data (typically $_REQUEST)
  */
 static function sendAddGroupUsersForm($params = array())
 {
     $current_group =& $_SESSION['glpi_plannings']['plannings']["group_" . $params['groups_id'] . "_users"];
     $current_group = array('display' => true, 'type' => 'group_users');
     $users = Group_User::getGroupUsers($params['groups_id']);
     $index_color = count($_SESSION['glpi_plannings']['plannings']);
     $group_user_index = 0;
     foreach ($users as $user_data) {
         // do not add an already set user
         if (!isset($_SESSION['glpi_plannings']['plannings']['user_' . $user_data['id']])) {
             $current_group['users']['user_' . $user_data['id']] = array('color' => self::$palette_bg[$_SESSION['glpi_plannings_color_index']], 'display' => true, 'type' => 'user');
             $_SESSION['glpi_plannings_color_index']++;
         }
     }
     self::savePlanningsInDB();
 }
 /**
  * get users linked to an object including groups ones
  *
  * @since version 0.85
  *
  * @param $type type to search (see constants)
  *
  * @return array
  **/
 function getAllUsers($type)
 {
     $users = array();
     foreach ($this->getUsers($type) as $link) {
         $users[$link['users_id']] = $link['users_id'];
     }
     foreach ($this->getGroups($type) as $link) {
         $gusers = Group_User::getGroupUsers($link['groups_id']);
         foreach ($gusers as $user) {
             $users[$user['id']] = $user['id'];
         }
     }
     return $users;
 }
Пример #11
0
 /**
  * @param $users_id
  **/
 static function manageDeletedUserInLdap($users_id)
 {
     global $CFG_GLPI;
     //User is present in DB but not in the directory : it's been deleted in LDAP
     $tmp['id'] = $users_id;
     $myuser = new User();
     switch ($CFG_GLPI['user_deleted_ldap']) {
         //DO nothing
         default:
         case 0:
             break;
             //Put user in dustbin
         //Put user in dustbin
         case 1:
             $myuser->delete($tmp);
             break;
             //Delete all user dynamic habilitations and groups
         //Delete all user dynamic habilitations and groups
         case 2:
             Profile_User::deleteRights($users_id, true);
             Group_User::deleteGroups($users_id, true);
             break;
             //Deactivate the user
         //Deactivate the user
         case 3:
             $tmp['is_active'] = 0;
             $myuser->update($tmp);
             break;
     }
     $changes[0] = '0';
     $changes[1] = '';
     $changes[2] = __('Deleted user in LDAP directory');
     Log::history($users_id, 'User', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);
 }
Пример #12
0
This file is part of GLPI.

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

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

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
* @since vesion 0.84
*/
include '../inc/includes.php';
Session::checkCentralAccess();
$group_user = new Group_User();
if (isset($_POST["add"])) {
    $group_user->check(-1, 'w', $_POST);
    if ($group_user->add($_POST)) {
        Event::log($_POST["groups_id"], "groups", 4, "setup", sprintf(__('%s adds a user to a group'), $_SESSION["glpiname"]));
    }
    Html::back();
}
Html::displayErrorAndDie("lost");
Пример #13
0
 /**
  * Manage Validation add from input
  *
  * @since version 0.85
  *
  * @param $input array : input array
  *
  * @return nothing
  **/
 function manageValidationAdd($input)
 {
     //Action for send_validation rule
     if (isset($input["_add_validation"])) {
         if (isset($input['entities_id'])) {
             $entid = $input['entities_id'];
         } else {
             if (isset($this->fields['entities_id'])) {
                 $entid = $this->fields['entities_id'];
             } else {
                 return false;
             }
         }
         $validations_to_send = array();
         if (!is_array($input["_add_validation"])) {
             $input["_add_validation"] = array($input["_add_validation"]);
         }
         foreach ($input["_add_validation"] as $key => $validation) {
             switch ($validation) {
                 case 'requester_supervisor':
                     if (isset($input['_groups_id_requester']) && $input['_groups_id_requester']) {
                         $users = Group_User::getGroupUsers($input['_groups_id_requester'], "is_manager='1'");
                         foreach ($users as $data) {
                             $validations_to_send[] = $data['id'];
                         }
                     }
                     // Add to already set groups
                     foreach ($this->getGroups(CommonITILActor::REQUESTER) as $d) {
                         $users = Group_User::getGroupUsers($d['groups_id'], "is_manager='1'");
                         foreach ($users as $data) {
                             $validations_to_send[] = $data['id'];
                         }
                     }
                     break;
                 case 'assign_supervisor':
                     if (isset($input['_groups_id_assign']) && $input['_groups_id_assign']) {
                         $users = Group_User::getGroupUsers($input['_groups_id_assign'], "is_manager='1'");
                         foreach ($users as $data) {
                             $validations_to_send[] = $data['id'];
                         }
                     }
                     foreach ($this->getGroups(CommonITILActor::ASSIGN) as $d) {
                         $users = Group_User::getGroupUsers($d['groups_id'], "is_manager='1'");
                         foreach ($users as $data) {
                             $validations_to_send[] = $data['id'];
                         }
                     }
                     break;
                 default:
                     // Group case from rules
                     if ($key === 'group') {
                         foreach ($validation as $groups_id) {
                             $validation_right = 'validate_incident';
                             if (isset($input['type']) && $input['type'] == Ticket::DEMAND_TYPE) {
                                 $validation_right = 'validate_request';
                             }
                             $opt = array('groups_id' => $groups_id, 'right' => $validation_right, 'entity' => $entid);
                             $data_users = TicketValidation::getGroupUserHaveRights($opt);
                             foreach ($data_users as $user) {
                                 $validations_to_send[] = $user['id'];
                             }
                         }
                     } else {
                         $validations_to_send[] = $validation;
                     }
             }
         }
         // Validation user added on ticket form
         if (isset($input['users_id_validate'])) {
             if (array_key_exists('groups_id', $input['users_id_validate'])) {
                 foreach ($input['users_id_validate'] as $key => $validation_to_add) {
                     if (is_numeric($key)) {
                         $validations_to_send[] = $validation_to_add;
                     }
                 }
             } else {
                 foreach ($input['users_id_validate'] as $key => $validation_to_add) {
                     if (is_numeric($key)) {
                         $validations_to_send[] = $validation_to_add;
                     }
                 }
             }
         }
         // Keep only one
         $validations_to_send = array_unique($validations_to_send);
         $validation = new TicketValidation();
         if (count($validations_to_send)) {
             $values = array();
             $values['tickets_id'] = $this->fields['id'];
             if (isset($input['id']) && $input['id'] != $this->fields['id']) {
                 $values['_ticket_add'] = true;
             }
             // to know update by rules
             if (isset($input["_rule_process"])) {
                 $values['_rule_process'] = $input["_rule_process"];
             }
             // if auto_import, tranfert it for validation
             if (isset($input['_auto_import'])) {
                 $values['_auto_import'] = $input['_auto_import'];
             }
             // Cron or rule process of hability to do
             if (Session::isCron() || isset($input["_auto_import"]) || isset($input["_rule_process"]) || $validation->can(-1, CREATE, $values)) {
                 // cron or allowed user
                 $add_done = false;
                 foreach ($validations_to_send as $user) {
                     // Do not auto add twice same validation
                     if (!TicketValidation::alreadyExists($values['tickets_id'], $user)) {
                         $values["users_id_validate"] = $user;
                         if ($validation->add($values)) {
                             $add_done = true;
                         }
                     }
                 }
                 if ($add_done) {
                     Event::log($this->fields['id'], "ticket", 4, "tracking", sprintf(__('%1$s updates the item %2$s'), $_SESSION["glpiname"], $this->fields['id']));
                 }
             }
         }
     }
     return true;
 }
 function prepareRun($taskjob_id, $definitions_filter = NULL)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $agentmodule = new PluginFusioninventoryAgentmodule();
     $job->getFromDB($taskjob_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 if ($this->definitionFiltered("Computer", $definitions_filter)) {
                     break;
                 }
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 if ($this->definitionFiltered("Group", $definitions_filter)) {
                     break;
                 }
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupStatic", $definitions_filter)) {
                             break;
                         }
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupDynamic", $definitions_filter)) {
                             break;
                         }
                         //$definitions_filter is NULL = update by crontask !
                         if ($definitions_filter != NULL) {
                             $where = " AND `can_update_group`='1'";
                         } else {
                             $where = "";
                         }
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}' {$where}\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         //No dynamic groups have been found : break
                         if ($DB->numrows($res) == 0) {
                             break;
                         }
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageParams('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     //Remove duplicatas from array
     //We are using isset for faster processing than array_unique because we might have many
     //entries in this list.
     $tmp_computers = array();
     foreach ($computers as $computer) {
         if (!isset($tmp_computers[$computer])) {
             $tmp_computers[$computer] = 1;
         }
     }
     $computers = array_keys($tmp_computers);
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $job->fields['id'];
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $package = new PluginFusioninventoryDeployPackage();
     foreach ($computers as $computer_id) {
         //Unique Id match taskjobstatuses for an agent(computer)
         foreach ($definitions as $definition) {
             $uniqid = uniqid();
             $package->getFromDB($definition['PluginFusioninventoryDeployPackage']);
             $c_input['state'] = 0;
             $c_input['itemtype'] = 'PluginFusioninventoryDeployPackage';
             $c_input['items_id'] = $package->fields['id'];
             $c_input['date'] = date("Y-m-d H:i:s");
             $c_input['uniqid'] = $uniqid;
             //get agent for this computer
             $agents_id = $agent->getAgentWithComputerid($computer_id);
             if ($agents_id === FALSE) {
                 $jobstates_id = $jobstate->add($c_input);
                 $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
             } else {
                 if ($agentmodule->isAgentCanDo('DEPLOY', $agents_id)) {
                     $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                     $jobstates_running = $jobstate->find(implode(" ", array("    `itemtype` = 'PluginFusioninventoryDeployPackage'", "AND `items_id` = " . $package->fields['id'], "AND `state` <> " . PluginFusioninventoryTaskjobstate::FINISHED, "AND `plugin_fusioninventory_agents_id` = " . $agents_id)));
                     if (count($jobstates_running) == 0) {
                         # Push the agent, in the stack of agent to awake
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                         }
                         $jobstates_id = $jobstate->add($c_input);
                         //Add log of taskjob
                         $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                         $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                         $taskvalid++;
                         $joblog->add($c_input);
                         unset($c_input['state']);
                         unset($c_input['plugin_fusioninventory_agents_id']);
                     }
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
Пример #15
0
 /**
  * @param $users_id
  **/
 static function manageDeletedUserInLdap($users_id)
 {
     global $CFG_GLPI;
     //The only case where users_id can be null if when a user has been imported into GLPi
     //it's dn still exists, but doesn't match the connection filter anymore
     //In this case, do not try to process the user
     if (!$users_id) {
         return true;
     }
     //User is present in DB but not in the directory : it's been deleted in LDAP
     $tmp['id'] = $users_id;
     $tmp['is_deleted_ldap'] = 1;
     $myuser = new self();
     $myuser->getFromDB($users_id);
     //User is already considered as delete from ldap
     if ($myuser->fields['is_deleted_ldap'] == 1) {
         return;
     }
     switch ($CFG_GLPI['user_deleted_ldap']) {
         //DO nothing
         default:
         case 0:
             $myuser->update($tmp);
             break;
             //Put user in dustbin
         //Put user in dustbin
         case 1:
             $myuser->delete($tmp);
             break;
             //Delete all user dynamic habilitations and groups
         //Delete all user dynamic habilitations and groups
         case 2:
             Profile_User::deleteRights($users_id, true);
             Group_User::deleteGroups($users_id, true);
             $myuser->update($tmp);
             break;
             //Deactivate the user
         //Deactivate the user
         case 3:
             $tmp['is_active'] = 0;
             $myuser->update($tmp);
             break;
             //Deactivate the user+ Delete all user dynamic habilitations and groups
         //Deactivate the user+ Delete all user dynamic habilitations and groups
         case 4:
             $tmp['is_active'] = 0;
             $myuser->update($tmp);
             Profile_User::deleteRights($users_id, true);
             Group_User::deleteGroups($users_id, true);
             break;
     }
     /*
           $changes[0] = '0';
           $changes[1] = '';
           $changes[2] = __('Deleted user in LDAP directory');
           Log::history($users_id, 'User', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);*/
 }
 /**
  * @see RuleCollection::prepareInputDataForProcess()
  **/
 function prepareInputDataForProcess($input, $params)
 {
     // Pass x-priority header if exists
     if (isset($input['_head']['x-priority'])) {
         $input['_x-priority'] = $input['_head']['x-priority'];
     }
     $input['_groups_id_of_requester'] = array();
     // Get groups of users
     if (isset($input['_users_id_requester'])) {
         foreach (Group_User::getUserGroups($input['_users_id_requester']) as $g) {
             $input['_groups_id_of_requester'][$g['id']] = $g['id'];
         }
     }
     return $input;
 }
Пример #17
0
 function getWidgetContentForItem($widgetId)
 {
     global $CFG_GLPI, $DB;
     if (empty($this->form)) {
         $this->init();
     }
     switch ($widgetId) {
         case $this->getType() . "1":
             $plugin = new Plugin();
             if ($plugin->isActivated("tasklists")) {
                 $widget = new PluginMydashboardDatatable();
                 $headers = array(__('Name'), __('Priority'), _n('Context', 'Contexts', 1, 'tasklists'), __('User'), __('Percent done'), __('Due date'), __('Action'));
                 $query = "SELECT `glpi_plugin_tasklists_tasks`.*,`glpi_plugin_tasklists_tasktypes`.`completename` as 'type' \n                            FROM `glpi_plugin_tasklists_tasks`\n                            LEFT JOIN `glpi_plugin_tasklists_tasktypes` ON (`glpi_plugin_tasklists_tasks`.`plugin_tasklists_tasktypes_id` = `glpi_plugin_tasklists_tasktypes`.`id`) \n                            WHERE NOT `glpi_plugin_tasklists_tasks`.`is_deleted`\n                                 AND `glpi_plugin_tasklists_tasks`.`state` < 2 ";
                 $query .= getEntitiesRestrictRequest('AND', 'glpi_plugin_tasklists_tasks');
                 $query .= "ORDER BY `glpi_plugin_tasklists_tasks`.`priority`DESC ";
                 $tasks = array();
                 if ($result = $DB->query($query)) {
                     if ($DB->numrows($result)) {
                         while ($data = $DB->fetch_array($result)) {
                             //$groups = Group_User::getGroupUsers($data['groups_id']);
                             $groupusers = Group_User::getGroupUsers($data['groups_id']);
                             $groups = array();
                             foreach ($groupusers as $groupuser) {
                                 $groups[] = $groupuser["id"];
                             }
                             if ($data['visibility'] == 1 && $data['users_id'] == Session::getLoginUserID() || $data['visibility'] == 2 && ($data['users_id'] == Session::getLoginUserID() || in_array(Session::getLoginUserID(), $groups)) || $data['visibility'] == 3) {
                                 $ID = $data['id'];
                                 $rand = mt_rand();
                                 $url = Toolbox::getItemTypeFormURL("PluginTasklistsTask") . "?id=" . $data['id'];
                                 $tasks[$data['id']][0] = "<a id='task" . $data["id"] . $rand . "' target='_blank' href='{$url}'>" . $data['name'] . "</a>";
                                 $tasks[$data['id']][0] .= Html::showToolTip($data['comment'], array('applyto' => 'task' . $data["id"] . $rand, 'display' => false));
                                 $bgcolor = $_SESSION["glpipriority_" . $data['priority']];
                                 $tasks[$data['id']][1] = "<div class='center' style='background-color:{$bgcolor};'>" . CommonITILObject::getPriorityName($data['priority']) . "</div>";
                                 $tasks[$data['id']][2] = $data['type'];
                                 $tasks[$data['id']][3] = getUserName($data['users_id']);
                                 $tasks[$data['id']][4] = Dropdown::getValueWithUnit($data['percent_done'], "%");
                                 $due_date = $data['due_date'];
                                 $display = Html::convDate($data['due_date']);
                                 if ($due_date <= date('Y-m-d') && !empty($due_date)) {
                                     $display = "<div class='deleted'>" . Html::convDate($data['due_date']) . "</div>";
                                 }
                                 $tasks[$data['id']][5] = $display;
                                 $tasks[$data['id']][6] = "<div align='center'>";
                                 if (Session::haveRight("plugin_tasklists", UPDATE)) {
                                     $tasks[$data['id']][6] .= "<a class='pointer' onclick=\" submitGetLink('" . $CFG_GLPI['root_doc'] . "/plugins/tasklists/front/task.form.php', {'done': 'done', 'id': '" . $data['id'] . "', '_glpi_csrf_token': '" . Session::getNewCSRFToken() . "', '_glpi_simple_form': '1'});\"><img src='" . $CFG_GLPI['root_doc'] . "/plugins/tasklists/pics/ok.png' title='" . __('Mark as done', 'tasklists') . "'></a>";
                                 }
                                 if (Session::haveRight("plugin_tasklists", UPDATENOTE)) {
                                     $link = "&nbsp;<a href=\"javascript:" . Html::jsGetElementbyID('comment' . $rand) . ".dialog('open');\">";
                                     $link .= "<img class='pointer' src='" . $CFG_GLPI['root_doc'] . "/plugins/tasklists/pics/plus.png' title='" . __('Add comment', 'tasklists') . "'>";
                                     $link .= "</a>";
                                     $link .= Ajax::createIframeModalWindow('comment' . $rand, $CFG_GLPI["root_doc"] . "/plugins/tasklists/front/comment.form.php?id=" . $ID, array('title' => __('Add comment', 'tasklists'), 'reloadonclose' => false, 'width' => 1100, 'display' => false, 'height' => 300));
                                     $tasks[$data['id']][6] .= $link;
                                 }
                                 $tasks[$data['id']][6] .= "</div>";
                             }
                         }
                     }
                 }
                 $widget->setTabDatas($tasks);
                 $widget->setTabNames($headers);
                 $widget->setOption("bSort", false);
                 $widget->toggleWidgetRefresh();
                 $link = "<div align='right'><a class='vsubmit' href=\"javascript:" . Html::jsGetElementbyID('task') . ".dialog('open');\">";
                 $link .= __('Add task', 'tasklists');
                 $link .= "</a></div>";
                 $link .= Ajax::createIframeModalWindow('task', $CFG_GLPI["root_doc"] . "/plugins/tasklists/front/task.form.php", array('title' => __('Add task', 'tasklists'), 'reloadonclose' => false, 'width' => 1180, 'display' => false, 'height' => 600));
                 $widget->appendWidgetHtmlContent($link);
                 $widget->setWidgetTitle(__("Tasks list", 'tasklists'));
                 return $widget;
             } else {
                 $widget = new PluginMydashboardDatatable();
                 $widget->setWidgetTitle(__("Tasks list", 'tasklists'));
                 return $widget;
             }
             break;
     }
 }
 /**
  * Show the availability of a user
  *
  * @since version 0.83
  *
  * @param $params   array of params
  *    must contain :
  *          - begin: begin date to check (default '')
  *          - end: end date to check (default '')
  *          - itemtype : User or Object type (Ticket...)
  *          - foreign key field of the itemtype to define which item to used
  *    optional :
  *          - limitto : limit display to a specific user
  *
  * @return Nothing (display function)
  **/
 static function checkAvailability($params = array())
 {
     global $CFG_GLPI, $DB;
     if (!isset($params['itemtype'])) {
         return false;
     }
     if (!($item = getItemForItemtype($params['itemtype']))) {
         return false;
     }
     if (!isset($params[$item->getForeignKeyField()]) || !$item->getFromDB($params[$item->getForeignKeyField()])) {
         return false;
     }
     // No limit by default
     if (!isset($params['limitto'])) {
         $params['limitto'] = 0;
     }
     if (isset($params['begin']) && !empty($params['begin'])) {
         $begin = $params['begin'];
     } else {
         $begin = date("Y-m-d");
     }
     if (isset($params['end']) && !empty($params['end'])) {
         $end = $params['end'];
     } else {
         $end = date("Y-m-d");
     }
     if ($end < $begin) {
         $end = $begin;
     }
     $realbegin = $begin . " " . $CFG_GLPI["planning_begin"];
     $realend = $end . " " . $CFG_GLPI["planning_end"];
     $users = array();
     switch ($item->getType()) {
         case 'User':
             $users[$item->getID()] = $item->getName();
             break;
         default:
             if (Toolbox::is_a($item, 'CommonITILObject')) {
                 foreach ($item->getUsers(CommonITILActor::ASSIGN) as $data) {
                     $users[$data['users_id']] = getUserName($data['users_id']);
                 }
                 foreach ($item->getGroups(CommonITILActor::ASSIGN) as $data) {
                     foreach (Group_User::getGroupUsers($data['groups_id']) as $data2) {
                         $users[$data2['id']] = formatUserName($data2["id"], $data2["name"], $data2["realname"], $data2["firstname"]);
                     }
                 }
             }
             break;
     }
     asort($users);
     // Use get method to check availability
     echo "<div class='center'><form method='GET' name='form' action='planning.php'>\n";
     echo "<table class='tab_cadre_fixe'>";
     $colspan = 5;
     if (count($users) > 1) {
         $colspan++;
     }
     echo "<tr class='tab_bg_1'><th colspan='{$colspan}'>" . __('Availability') . "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Start') . "</td>\n";
     echo "<td>";
     Html::showDateField("begin", array('value' => $begin, 'maybeempty' => false));
     echo "</td>\n";
     echo "<td>" . __('End') . "</td>\n";
     echo "<td>";
     Html::showDateField("end", array('value' => $end, 'maybeempty' => false));
     echo "</td>\n";
     if (count($users) > 1) {
         echo "<td width='40%'>";
         $data = array(0 => __('All'));
         $data += $users;
         Dropdown::showFromArray('limitto', $data, array('width' => '100%', 'value' => $params['limitto']));
         echo "</td>";
     }
     echo "<td class='center'>";
     echo "<input type='hidden' name='" . $item->getForeignKeyField() . "' value=\"" . $item->getID() . "\">";
     echo "<input type='hidden' name='itemtype' value=\"" . $item->getType() . "\">";
     echo "<input type='submit' class='submit' name='checkavailability' value=\"" . _sx('button', 'Search') . "\">";
     echo "</td>\n";
     echo "</tr>";
     echo "</table>";
     Html::closeForm();
     echo "</div>\n";
     if ($params['limitto'] > 0 && isset($users[$params['limitto']])) {
         $displayuser[$params['limitto']] = $users[$params['limitto']];
     } else {
         $displayuser = $users;
     }
     if (count($displayuser)) {
         foreach ($displayuser as $who => $whoname) {
             $params = array('who' => $who, 'who_group' => 0, 'begin' => $realbegin, 'end' => $realend);
             $interv = array();
             foreach ($CFG_GLPI['planning_types'] as $itemtype) {
                 $interv = array_merge($interv, $itemtype::populatePlanning($params));
             }
             // Print Headers
             echo "<br><div class='center'><table class='tab_cadre_fixe'>";
             $colnumber = 1;
             $plan_begin = explode(":", $CFG_GLPI["planning_begin"]);
             $plan_end = explode(":", $CFG_GLPI["planning_end"]);
             $begin_hour = intval($plan_begin[0]);
             $end_hour = intval($plan_end[0]);
             if ($plan_end[1] != 0) {
                 $end_hour++;
             }
             $colsize = floor((100 - 15) / ($end_hour - $begin_hour));
             $timeheader = '';
             for ($i = $begin_hour; $i < $end_hour; $i++) {
                 $from = ($i < 10 ? '0' : '') . $i;
                 $timeheader .= "<th width='{$colsize}%' colspan='4'>" . $from . ":00</th>";
                 $colnumber += 4;
             }
             // Print Headers
             echo "<tr class='tab_bg_1'><th colspan='{$colnumber}'>";
             echo $whoname;
             echo "</th></tr>";
             echo "<tr class='tab_bg_1'><th width='15%'>&nbsp;</th>";
             echo $timeheader;
             echo "</tr>";
             $day_begin = strtotime($realbegin);
             $day_end = strtotime($realend);
             for ($time = $day_begin; $time < $day_end; $time += DAY_TIMESTAMP) {
                 $current_day = date('Y-m-d', $time);
                 echo "<tr><th>" . Html::convDate($current_day) . "</th>";
                 $begin_quarter = $begin_hour * 4;
                 $end_quarter = $end_hour * 4;
                 for ($i = $begin_quarter; $i < $end_quarter; $i++) {
                     $begin_time = date("Y-m-d H:i:s", strtotime($current_day) + $i * HOUR_TIMESTAMP / 4);
                     $end_time = date("Y-m-d H:i:s", strtotime($current_day) + ($i + 1) * HOUR_TIMESTAMP / 4);
                     // Init activity interval
                     $begin_act = $end_time;
                     $end_act = $begin_time;
                     reset($interv);
                     while ($data = current($interv)) {
                         if ($data["begin"] >= $begin_time && $data["end"] <= $end_time) {
                             // In
                             if ($begin_act > $data["begin"]) {
                                 $begin_act = $data["begin"];
                             }
                             if ($end_act < $data["end"]) {
                                 $end_act = $data["end"];
                             }
                             unset($interv[key($interv)]);
                         } else {
                             if ($data["begin"] < $begin_time && $data["end"] > $end_time) {
                                 // Through
                                 $begin_act = $begin_time;
                                 $end_act = $end_time;
                                 next($interv);
                             } else {
                                 if ($data["begin"] >= $begin_time && $data["begin"] < $end_time) {
                                     // Begin
                                     if ($begin_act > $data["begin"]) {
                                         $begin_act = $data["begin"];
                                     }
                                     $end_act = $end_time;
                                     next($interv);
                                 } else {
                                     if ($data["end"] > $begin_time && $data["end"] <= $end_time) {
                                         //End
                                         $begin_act = $begin_time;
                                         if ($end_act < $data["end"]) {
                                             $end_act = $data["end"];
                                         }
                                         unset($interv[key($interv)]);
                                     } else {
                                         // Defautl case
                                         next($interv);
                                     }
                                 }
                             }
                         }
                     }
                     if ($begin_act < $end_act) {
                         if ($begin_act <= $begin_time && $end_act >= $end_time) {
                             // Activity in quarter
                             echo "<td class='notavailable'>&nbsp;</td>";
                         } else {
                             // Not all the quarter
                             if ($begin_act <= $begin_time) {
                                 echo "<td class='partialavailableend'>&nbsp;</td>";
                             } else {
                                 echo "<td class='partialavailablebegin'>&nbsp;</td>";
                             }
                         }
                     } else {
                         // No activity
                         echo "<td class='available'>&nbsp;</td>";
                     }
                 }
                 echo "</tr>";
             }
             echo "<tr class='tab_bg_1'><td colspan='{$colnumber}'>&nbsp;</td></tr>";
             echo "</table></div>";
         }
     }
     echo "<div><table class='tab_cadre'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . __('Caption') . "</th>";
     echo "<td class='available' colspan=8>" . __('Available') . "</td>";
     echo "<td class='notavailable' colspan=8>" . __('Unavailable') . "</td>";
     echo "</tr>";
     echo "</table></div>";
 }
 /**
  * @see RuleCollection::prepareInputDataForProcess()
  **/
 function prepareInputDataForProcess($input, $params)
 {
     $input['mailcollector'] = $params['mailcollector'];
     $input['_users_id_requester'] = $params['_users_id_requester'];
     $fields = $this->getFieldsToLookFor();
     //Add needed ticket datas for rules processing
     if (isset($params['ticket']) && is_array($params['ticket'])) {
         foreach ($params['ticket'] as $key => $value) {
             if (in_array($key, $fields) && !isset($input[$key])) {
                 $input[$key] = $value;
             }
         }
     }
     //Add needed headers for rules processing
     if (isset($params['headers']) && is_array($params['headers'])) {
         foreach ($params['headers'] as $key => $value) {
             if (in_array($key, $fields) && !isset($input[$key])) {
                 $input[$key] = $value;
             }
         }
     }
     //Add all user's groups
     if (in_array('groups', $fields)) {
         foreach (Group_User::getUserGroups($input['_users_id_requester']) as $group) {
             $input['GROUPS'][] = $group['id'];
         }
     }
     //Add all user's profiles
     if (in_array('profiles', $fields)) {
         foreach (Profile_User::getForUser($input['_users_id_requester']) as $profile) {
             $input['PROFILES'][$profile['profiles_id']] = $profile['profiles_id'];
         }
     }
     //If the criteria is "user has only one time the profile xxx"
     if (in_array('unique_profile', $fields)) {
         //Get all profiles
         $profiles = Profile_User::getForUser($input['_users_id_requester']);
         foreach ($profiles as $profile) {
             if (Profile_User::haveUniqueRight($input['_users_id_requester'], $profile['profiles_id'])) {
                 $input['UNIQUE_PROFILE'][$profile['profiles_id']] = $profile['profiles_id'];
             }
         }
     }
     //Store the number of profiles of which the user belongs to
     if (in_array('one_profile', $fields)) {
         $profiles = Profile_User::getForUser($input['_users_id_requester']);
         if (count($profiles) == 1) {
             $tmp = array_pop($profiles);
             $input['ONE_PROFILE'] = $tmp['profiles_id'];
         }
     }
     //Store the number of profiles of which the user belongs to
     if (in_array('known_domain', $fields)) {
         if (preg_match("/@(.*)/", $input['from'], $results)) {
             if (Entity::getEntityIDByDomain($results[1]) != -1) {
                 $input['KNOWN_DOMAIN'] = 1;
             } else {
                 $input['KNOWN_DOMAIN'] = 0;
             }
         }
     }
     return $input;
 }
Пример #20
0
     $config = new Config();
     $user->computePreferences();
     $config->showFormUserPrefs($user->fields);
     $user->showItems();
     Reservation::showForUser($_POST["id"]);
     Ticket::showListForUser($_POST["id"]);
     Plugin::displayAction($user, $_REQUEST['glpi_tab']);
     break;
 case 2:
     $user->showItems();
     break;
 case 3:
     Ticket::showListForUser($_POST["id"]);
     break;
 case 4:
     Group_User::showForUser($user);
     break;
 case 5:
     Document::showAssociated($user);
     break;
 case 6:
     $config = new Config();
     $user->computePreferences();
     $config->showFormUserPrefs($user->fields);
     break;
 case 11:
     Reservation::showForUser($_POST["id"]);
     break;
 case 12:
     Auth::showSynchronizationForm($_POST["id"]);
     break;
Пример #21
0
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
if (empty($_GET["id"])) {
    $_GET["id"] = "";
}
if (!isset($_GET["start"])) {
    $_GET["start"] = 0;
}
if (!isset($_GET["sort"])) {
    $_GET["sort"] = "";
}
if (!isset($_GET["order"])) {
    $_GET["order"] = "";
}
$user = new User();
$groupuser = new Group_User();
//print_r($_POST);exit();
if (empty($_GET["id"]) && isset($_GET["name"])) {
    $user->getFromDBbyName($_GET["name"]);
    glpi_header($CFG_GLPI["root_doc"] . "/front/user.form.php?id=" . $user->fields['id']);
}
if (empty($_GET["name"])) {
    $_GET["name"] = "";
}
if (isset($_REQUEST['getvcard'])) {
    if (empty($_GET["id"])) {
        glpi_header($CFG_GLPI["root_doc"] . "/front/user.php");
    }
    $user->check($_GET['id'], 'r');
    $user->generateVcard($_GET["id"]);
} else {
Пример #22
0
 /**
  * Recieve 'All users of a group' data from self::showAddGroupUsersForm and save them to session and DB
  *
  * @since 9.1
  *
  * @param $params (array) : must contais form data (typically $_REQUEST)
  */
 static function sendAddGroupUsersForm($params = array())
 {
     $current_group =& $_SESSION['glpi_plannings']['plannings']["group_" . $params['groups_id'] . "_users"];
     $current_group = array('display' => true, 'type' => 'group_users');
     $users = Group_User::getGroupUsers($params['groups_id'], "`glpi_users`.`is_active` = 1\n                                          AND NOT `glpi_users`.`is_deleted`\n                                          AND (`glpi_users`.`begin_date` IS NULL\n                                             OR `glpi_users`.`begin_date` < NOW())\n                                          AND (`glpi_users`.`end_date` IS NULL\n                                             OR `glpi_users`.`end_date` > NOW())");
     $index_color = count($_SESSION['glpi_plannings']['plannings']);
     $group_user_index = 0;
     foreach ($users as $user_data) {
         // do not add an already set user
         if (!isset($_SESSION['glpi_plannings']['plannings']['user_' . $user_data['id']])) {
             $current_group['users']['user_' . $user_data['id']] = array('color' => self::getPaletteColor('bg', $_SESSION['glpi_plannings_color_index']), 'display' => true, 'type' => 'user');
             $_SESSION['glpi_plannings_color_index']++;
         }
     }
     self::savePlanningsInDB();
 }
Пример #23
0
 function post_addItem()
 {
     global $CFG_GLPI;
     // Log this event
     $username = '******';
     if (isset($_SESSION["glpiname"])) {
         $username = $_SESSION["glpiname"];
     }
     Event::log($this->fields['id'], "ticket", 4, "tracking", sprintf(__('%1$s adds the item %2$s'), $username, $this->fields['id']));
     if (isset($this->input["_followup"]) && is_array($this->input["_followup"]) && strlen($this->input["_followup"]['content']) > 0) {
         $fup = new TicketFollowup();
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == self::SOLVED) {
             $type = "solved";
         }
         $toadd = array("type" => $type, "tickets_id" => $this->fields['id']);
         if (isset($this->input["_followup"]['content']) && strlen($this->input["_followup"]['content']) > 0) {
             $toadd["content"] = $this->input["_followup"]['content'];
         }
         if (isset($this->input["_followup"]['is_private'])) {
             $toadd["is_private"] = $this->input["_followup"]['is_private'];
         }
         $toadd['_no_notif'] = true;
         $fup->add($toadd);
     }
     if (isset($this->input["plan"]) && count($this->input["plan"]) || isset($this->input["actiontime"]) && $this->input["actiontime"] > 0) {
         $task = new TicketTask();
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == self::SOLVED) {
             $type = "solved";
         }
         $toadd = array("type" => $type, "tickets_id" => $this->fields['id'], "actiontime" => $this->input["actiontime"]);
         if (isset($this->input["plan"]) && count($this->input["plan"])) {
             $toadd["plan"] = $this->input["plan"];
         }
         if (isset($_SESSION['glpitask_private'])) {
             $toadd['is_private'] = $_SESSION['glpitask_private'];
         }
         $toadd['_no_notif'] = true;
         $task->add($toadd);
     }
     $ticket_ticket = new Ticket_Ticket();
     // From interface
     if (isset($this->input['_link'])) {
         $this->input['_link']['tickets_id_1'] = $this->fields['id'];
         // message if ticket's ID doesn't exist
         if (!empty($this->input['_link']['tickets_id_2'])) {
             if ($ticket_ticket->can(-1, 'w', $this->input['_link'])) {
                 $ticket_ticket->add($this->input['_link']);
             } else {
                 Session::addMessageAfterRedirect(__('Unknown ticket'), false, ERROR);
             }
         }
     }
     // From mailcollector : do not check rights
     if (isset($this->input["_linkedto"])) {
         $input2['tickets_id_1'] = $this->fields['id'];
         $input2['tickets_id_2'] = $this->input["_linkedto"];
         $input2['link'] = Ticket_Ticket::LINK_TO;
         $ticket_ticket->add($input2);
     }
     // Manage SLA Level : add actions
     if (isset($this->input["slas_id"]) && $this->input["slas_id"] > 0 && isset($this->input["slalevels_id"]) && $this->input["slalevels_id"] > 0) {
         $calendars_id = Entity::getUsedConfig('calendars_id', $this->fields['entities_id']);
         $sla = new SLA();
         if ($sla->getFromDB($this->input["slas_id"])) {
             $sla->setTicketCalendar($calendars_id);
             // Add first level in working table
             if ($this->input["slalevels_id"] > 0) {
                 $sla->addLevelToDo($this);
             }
             // Replay action in case of open date is set before now
         }
         SlaLevel_Ticket::replayForTicket($this->getID());
     }
     parent::post_addItem();
     //Action for send_validation rule
     if (isset($this->input["_add_validation"])) {
         $validations_to_send = array();
         if (!is_array($this->input["_add_validation"])) {
             $this->input["_add_validation"] = array($this->input["_add_validation"]);
         }
         foreach ($this->input["_add_validation"] as $validation) {
             switch ($validation) {
                 case 'requester_supervisor':
                     if (isset($this->input['_groups_id_requester']) && $this->input['_groups_id_requester']) {
                         $users = Group_User::getGroupUsers($this->input['_groups_id_requester'], "is_manager='1'");
                         foreach ($users as $data) {
                             $validations_to_send[] = $data['id'];
                         }
                     }
                     break;
                 case 'assign_supervisor':
                     if (isset($this->input['_groups_id_assign']) && $this->input['_groups_id_assign']) {
                         $users = Group_User::getGroupUsers($this->input['_groups_id_assign'], "is_manager='1'");
                         foreach ($users as $data) {
                             $validations_to_send[] = $data['id'];
                         }
                     }
                     break;
                 default:
                     $validations_to_send[] = $validation;
             }
         }
         // Keep only one
         $validations_to_send = array_unique($validations_to_send);
         $validation = new TicketValidation();
         foreach ($validations_to_send as $users_id) {
             if ($users_id > 0) {
                 $values = array();
                 $values['tickets_id'] = $this->fields['id'];
                 $values['users_id_validate'] = $users_id;
                 $values['_ticket_add'] = true;
                 // to know update by rules
                 if (isset($this->input["_rule_process"])) {
                     $values['_rule_process'] = $this->input["_rule_process"];
                 }
                 // if auto_import, tranfert it for validation
                 if (isset($this->input['_auto_import'])) {
                     $values['_auto_import'] = $this->input['_auto_import'];
                 }
                 // Cron or rule process of hability to do
                 if (Session::isCron() || isset($this->input["_auto_import"]) || isset($this->input["_rule_process"]) || $validation->can(-1, 'w', $values)) {
                     // cron or allowed user
                     $validation->add($values);
                     Event::log($this->fields['id'], "ticket", 4, "tracking", sprintf(__('%1$s updates the item %2$s'), $_SESSION["glpiname"], $this->fields['id']));
                 }
             }
         }
     }
     // Processing Email
     if ($CFG_GLPI["use_mailing"]) {
         // Clean reload of the ticket
         $this->getFromDB($this->fields['id']);
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == self::SOLVED) {
             $type = "solved";
         }
         NotificationEvent::raiseEvent($type, $this);
     }
     if (isset($_SESSION['glpiis_ids_visible']) && !$_SESSION['glpiis_ids_visible']) {
         Session::addMessageAfterRedirect(sprintf(__('%1$s (%2$s)'), __('Your ticket has been registered, its treatment is in progress.'), sprintf(__('%1$s: %2$s'), __('Ticket'), "<a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id=" . $this->fields['id'] . "'>" . $this->fields['id'] . "</a>")));
     }
 }
Пример #24
0
 if (isset($_GET['entities_id']) && isset($_GET['is_recursive'])) {
     $user->loadMinimalSession($_GET['entities_id'], $_GET['is_recursive']);
 }
 //// check if the request is valid: rights on uID / gID
 // First check mine : user then groups
 $ismine = false;
 if ($user->getID() == $_GET["uID"]) {
     $ismine = true;
 }
 // Check groups if have right to see
 if (!$ismine && $_GET["gID"] !== 0) {
     if ($_GET["gID"] === 'mine') {
         $ismine = true;
     } else {
         $entities = Profile_User::getUserEntitiesForRight($user->getID(), Planning::READGROUP);
         $groups = Group_User::getUserGroups($user->getID());
         foreach ($groups as $group) {
             if ($_GET["gID"] == $group['id'] && in_array($group['entities_id'], $entities)) {
                 $ismine = true;
             }
         }
     }
 }
 $canview = false;
 // If not mine check global right
 if (!$ismine) {
     // First check user
     $entities = Profile_User::getUserEntitiesForRight($user->getID(), Planning::READALL);
     if ($_GET["uID"]) {
         $userentities = Profile_User::getUserEntities($user->getID());
         $intersect = array_intersect($entities, $userentities);
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';
if (empty($_GET["id"])) {
    $_GET["id"] = "";
}
$user = new User();
$groupuser = new Group_User();
if (empty($_GET["id"]) && isset($_GET["name"])) {
    $user->getFromDBbyName($_GET["name"]);
    Html::redirect($CFG_GLPI["root_doc"] . "/front/user.form.php?id=" . $user->fields['id']);
}
if (empty($_GET["name"])) {
    $_GET["name"] = "";
}
if (isset($_GET['getvcard'])) {
    if (empty($_GET["id"])) {
        Html::redirect($CFG_GLPI["root_doc"] . "/front/user.php");
    }
    $user->check($_GET['id'], READ);
    $user->generateVcard();
} else {
    if (isset($_POST["add"])) {
Пример #26
0
         }
     }
     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)) {
                 $groupuser->add($input);
             }
         }
     }
     break;
 case "add_userprofile":
     $right = new Profile_User();
     if (isset($_POST['profiles_id']) && $_POST['profiles_id'] > 0 && isset($_POST['entities_id']) && $_POST['entities_id'] >= 0) {
         $input['entities_id'] = $_POST['entities_id'];
         $input['profiles_id'] = $_POST['profiles_id'];
         $input['is_recursive'] = $_POST['is_recursive'];
Пример #27
0
This file is part of GLPI.

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

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

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
* @since vesion 0.84
*/
include '../inc/includes.php';
Session::checkCentralAccess();
$group_user = new Group_User();
if (isset($_POST["add"])) {
    $group_user->check(-1, CREATE, $_POST);
    if ($group_user->add($_POST)) {
        Event::log($_POST["groups_id"], "groups", 4, "setup", sprintf(__('%s adds a user to a group'), $_SESSION["glpiname"]));
    }
    Html::back();
}
Html::displayErrorAndDie("lost");
Пример #28
0
 /**
  * check right for Approve ticket Solution
  * for an authenticated user and a particular user
  *
  * @param $users_id  user id used for check ticket right
  * @param $ticket    ticket object
  *
  * @return array of hashtable
  **/
 static function checkApprobationSolution($users_id, Ticket $ticket)
 {
     if (!self::checkUserRights(Session::getLoginUserID(), 'update_ticket', 1, $ticket->getField('entities_id'))) {
         return false;
     }
     if (!($ticket->fields["users_id_recipient"] === $users_id || $ticket->isUser(CommonITILActor::REQUESTER, $users_id) || sizeof(Group_User::getUserGroups($users_id) > 0) && $ticket->haveAGroup(CommonITILActor::REQUESTER, Group_User::getUserGroups($users_id)))) {
         return false;
     }
     return true;
 }
Пример #29
0
 /**
  * @param $output
  * @param $params
  **/
 function executeActions($output, $params)
 {
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "send":
                     $ticket = new Ticket();
                     if ($ticket->getFromDB($output['id'])) {
                         NotificationEvent::raiseEvent('recall', $ticket);
                     }
                     break;
                 case "add_validation":
                     if (isset($output['_add_validation']) && !is_array($output['_add_validation'])) {
                         $output['_add_validation'] = array($output['_add_validation']);
                     }
                     switch ($action->fields['field']) {
                         case 'users_id_validate_requester_supervisor':
                             $output['_add_validation'][] = 'requester_supervisor';
                             break;
                         case 'users_id_validate_assign_supervisor':
                             $output['_add_validation'][] = 'assign_supervisor';
                             break;
                         case 'groups_id_validate':
                             $output['_add_validation']['group'][] = $action->fields["value"];
                             break;
                         case 'users_id_validate':
                             $output['_add_validation'][] = $action->fields["value"];
                             break;
                         case 'validation_percent':
                             $output[$action->fields["field"]] = $action->fields["value"];
                             break;
                         default:
                             $output['_add_validation'][] = $action->fields["value"];
                             break;
                     }
                     break;
                 case "assign":
                     $output[$action->fields["field"]] = $action->fields["value"];
                     // Special case of users_id_requester
                     if ($action->fields["field"] === '_users_id_requester') {
                         // Add groups of requester
                         if (!isset($output['_groups_id_of_requester'])) {
                             $output['_groups_id_of_requester'] = array();
                         }
                         foreach (Group_User::getUserGroups($action->fields["value"]) as $g) {
                             $output['_groups_id_of_requester'][$g['id']] = $g['id'];
                         }
                     }
                     break;
                 case "append":
                     $actions = $this->getActions();
                     $value = $action->fields["value"];
                     if (isset($actions[$action->fields["field"]]["appendtoarray"]) && isset($actions[$action->fields["field"]]["appendtoarrayfield"])) {
                         $value = $actions[$action->fields["field"]]["appendtoarray"];
                         $value[$actions[$action->fields["field"]]["appendtoarrayfield"]] = $action->fields["value"];
                     }
                     $output[$actions[$action->fields["field"]]["appendto"]][] = $value;
                     // Special case of users_id_requester
                     if ($action->fields["field"] === '_users_id_requester') {
                         // Add groups of requester
                         if (!isset($output['_groups_id_of_requester'])) {
                             $output['_groups_id_of_requester'] = array();
                         }
                         foreach (Group_User::getUserGroups($action->fields["value"]) as $g) {
                             $output['_groups_id_of_requester'][$g['id']] = $g['id'];
                         }
                     }
                     break;
                 case 'fromuser':
                     if ($action->fields['field'] == 'locations_id' && isset($output['users_locations'])) {
                         $output['locations_id'] = $output['users_locations'];
                     }
                     break;
                 case 'fromitem':
                     if ($action->fields['field'] == 'locations_id' && isset($output['items_locations'])) {
                         $output['locations_id'] = $output['items_locations'];
                     }
                     if ($action->fields['field'] == 'groups_id' && isset($output['items_groups'])) {
                         $output['groups_id'] = $output['items_groups'];
                     }
                     break;
                 case 'compute':
                     // Value could be not set (from test)
                     $urgency = isset($output['urgency']) ? $output['urgency'] : 3;
                     $impact = isset($output['impact']) ? $output['impact'] : 3;
                     // Apply priority_matrix from config
                     $output['priority'] = Ticket::computePriority($urgency, $impact);
                     break;
                 case "affectbyip":
                 case "affectbyfqdn":
                 case "affectbymac":
                     if (!isset($output["entities_id"])) {
                         $output["entities_id"] = $params["entities_id"];
                     }
                     if (isset($this->regex_results[0])) {
                         $regexvalue = RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                     } else {
                         $regexvalue = $action->fields["value"];
                     }
                     switch ($action->fields["action_type"]) {
                         case "affectbyip":
                             $result = IPAddress::getUniqueItemByIPAddress($regexvalue, $output["entities_id"]);
                             break;
                         case "affectbyfqdn":
                             $result = FQDNLabel::getUniqueItemByFQDN($regexvalue, $output["entities_id"]);
                             break;
                         case "affectbymac":
                             $result = NetworkPortInstantiation::getUniqueItemByMac($regexvalue, $output["entities_id"]);
                             break;
                         default:
                             $result = array();
                     }
                     if (!empty($result)) {
                         $output["items_id"][$result["itemtype"]][] = $result["id"];
                     }
                     break;
             }
         }
     }
     return $output;
 }
 /**
  * Get Computers from Actors defined in taskjobs
  * TODO: this method should be rewritten to call directly a getAgents() method in the
  * corresponding itemtype classes.
  */
 public function getAgentsFromActors($actors = array())
 {
     $agents = array();
     $computers = array();
     $computer = new Computer();
     $agent = new PluginFusioninventoryAgent();
     $pfToolbox = new PluginFusioninventoryToolbox();
     foreach ($actors as $actor) {
         $itemtype = key($actor);
         $itemid = $actor[$itemtype];
         $item = getItemForItemtype($itemtype);
         $dbresult = $item->getFromDB($itemid);
         // If this item doesn't exists, we continue to the next actor item.
         // TODO: remove this faulty actor from the list of job actor.
         if ($dbresult === false) {
             continue;
         }
         switch ($itemtype) {
             case 'Computer':
                 $computers[$itemid] = 1;
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group_targets = $pfToolbox->executeAsFusioninventoryUser('PluginFusioninventoryDeployGroup::getTargetsForGroup', array($itemid));
                 foreach ($group_targets as $computerid) {
                     $computers[$computerid] = 1;
                 }
                 break;
             case 'Group':
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $members = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($itemid);
                 foreach ($members as $member) {
                     $computers_from_user = $computer->find("users_id = '{$member['id']}'");
                     foreach ($computers_from_user as $computer_entry) {
                         $computers[$computer_entry['id']] = 1;
                     }
                 }
                 //find computers directly associated with this group
                 $computer_from_group = $computer->find("groups_id = '{$itemid}'");
                 foreach ($computer_from_group as $computer_entry) {
                     $computers[$computer_entry['id']] = 1;
                 }
                 break;
                 /**
                  * TODO: The following should be replaced with Dynamic groups
                  */
             /**
              * TODO: The following should be replaced with Dynamic groups
              */
             case 'PluginFusioninventoryAgent':
                 switch ($itemid) {
                     case "dynamic":
                         break;
                     case "dynamic-same-subnet":
                         break;
                     default:
                         $agents[$itemid] = 1;
                         break;
                 }
                 break;
         }
     }
     //Get agents from the computer's ids list
     foreach ($agent->getAgentsFromComputers(array_keys($computers)) as $agent_entry) {
         $agents[$agent_entry['id']] = 1;
     }
     // Return the list of agent's ids.
     // (We used hash keys to avoid duplicates in the list)
     return array_keys($agents);
 }