示例#1
0
 static function pdfForTicket(PluginPdfSimplePDF $pdf, Ticket $job, $private)
 {
     global $CFG_GLPI, $DB;
     $ID = $job->getField('id');
     //////////////Tasks///////////
     $RESTRICT = "";
     if (!$private) {
         // Don't show private'
         $RESTRICT = " AND `is_private` = '0' ";
     } else {
         if (!Session::haveRight("show_full_ticket", "1")) {
             // No right, only show connected user private one
             $RESTRICT = " AND (`is_private` = '0'\n                          OR `users_id` ='" . Session::getLoginUserID() . "' ) ";
         }
     }
     $query = "SELECT *\n                FROM `glpi_tickettasks`\n                WHERE `tickets_id` = '{$ID}'\n                      {$RESTRICT}\n                ORDER BY `date` DESC";
     $result = $DB->query($query);
     if (!$DB->numrows($result)) {
         $pdf->setColumnsSize(100);
         $pdf->displayLine(__('No task found.'));
     } else {
         $pdf->displayTitle("<b>" . TicketTask::getTypeName($DB->numrows($result) . "</b>"));
         $pdf->setColumnsSize(20, 20, 20, 20, 20);
         $pdf->displayTitle("<b><i>" . __('Type') . "</i></b>", "<b><i>" . __('Date') . "</i></b>", "<b><i>" . __('Duration') . "</i></b>", "<b><i>" . __('Writer') . "</i></b>", "<b><i>" . __('Planning') . "</i></b>");
         while ($data = $DB->fetch_array($result)) {
             $actiontime = Html::timestampToString($data['actiontime'], false);
             $planification = '';
             if (empty($data['begin'])) {
                 if (isset($data["state"])) {
                     $planification = Planning::getState($data["state"]) . "<br>";
                 }
                 $planification .= _e('None');
             } else {
                 if (isset($data["state"])) {
                     $planification = sprintf(__('%1$s: %2$s'), _x('item', 'State'), Planning::getState($data["state"]));
                 }
                 $planificiation = sprintf(__('%1$s - %2$s'), $planification, Html::convDateTime($data["begin"]) . " -> " . Html::convDateTime($data["end"]));
                 $planificiation = sprintf(__('%1$s - %2$s'), $planification, sprintf(__('%1$s  %2$s'), __('By'), getUserName($data["users_id_tech"])));
             }
             if ($data['taskcategories_id']) {
                 $lib = Dropdown::getDropdownName('glpi_taskcategories', $data['taskcategories_id']);
             } else {
                 $lib = '';
             }
             if ($data['is_private']) {
                 $lib = sprintf(__('%1$s (%2$s)'), $lib, __('Private'));
             }
             toolbox::logdebug("lib", $data);
             $pdf->displayLine(Html::clean($lib), Html::convDateTime($data["date"]), Html::timestampToString($data["actiontime"], 0), Html::clean(getUserName($data["users_id"])), Html::clean($planification), 1);
             $pdf->displayText("<b><i>" . sprintf(__('%1$s: %2$s'), __('Description') . "</i></b>", Html::clean($data["content"]), 1));
         }
     }
     $pdf->displaySpace();
 }
示例#2
0
 function getFromDBbyOcsServer($id)
 {
     global $DB;
     $query = "SELECT *\n                FROM `" . $this->getTable() . "`\n                WHERE `plugin_ocsinventoryng_ocsservers_id` = '{$id}'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) != 1) {
             return false;
         }
         $this->fields = $DB->fetch_assoc($result);
         if (is_array($this->fields) && count($this->fields)) {
             return true;
         }
         toolbox::logdebug($this->fields);
     }
     return false;
 }
示例#3
0
 /**
  * Constructor
  *
  * @param $mailgateID   ID of the mailgate
  * @param $display      display messages in MessageAfterRedirect or just return error (default 0=)
  *
  * @return if $display = false return messages result string
  **/
 function collect($mailgateID, $display = 0)
 {
     global $CFG_GLPI;
     if ($this->getFromDB($mailgateID)) {
         $this->mid = -1;
         $this->fetch_emails = 0;
         //Connect to the Mail Box
         $this->connect();
         $rejected = new NotImportedEmail();
         // Clean from previous collect (from GUI, cron already truncate the table)
         $rejected->deleteByCriteria(array('mailcollectors_id' => $this->fields['id']));
         if ($this->marubox) {
             // Get Total Number of Unread Email in mail box
             $tot = $this->getTotalMails();
             //Total Mails in Inbox Return integer value
             $error = 0;
             $refused = 0;
             $blacklisted = 0;
             for ($i = 1; $i <= $tot && $this->fetch_emails < $this->maxfetch_emails; $i++) {
                 $tkt = $this->buildTicket($i, array('mailgates_id' => $mailgateID, 'play_rules' => true));
                 toolbox::logdebug("tkt", $tkt);
                 //Indicates that the mail must be deleted from the mailbox
                 $delete_mail = false;
                 //If entity assigned, or email refused by rule, or no user and no supplier associated with the email
                 $user_condition = $CFG_GLPI["use_anonymous_helpdesk"] || isset($tkt['_users_id_requester']) && $tkt['_users_id_requester'] > 0 || isset($tkt['_supplier_email']) && $tkt['_supplier_email'];
                 $rejinput = array();
                 $rejinput['mailcollectors_id'] = $mailgateID;
                 if (!$tkt['_blacklisted']) {
                     $rejinput['from'] = $tkt['_head']['from'];
                     $rejinput['to'] = $tkt['_head']['to'];
                     $rejinput['users_id'] = $tkt['_users_id_requester'];
                     $rejinput['subject'] = $this->textCleaner($tkt['_head']['subject']);
                     $rejinput['messageid'] = $tkt['_head']['message_id'];
                 }
                 $rejinput['date'] = $_SESSION["glpi_currenttime"];
                 // Manage blacklisted emails
                 if (isset($tkt['_blacklisted']) && $tkt['_blacklisted']) {
                     $this->deleteMails($i, self::REFUSED_FOLDER);
                     $blacklisted++;
                     // entities_id set when new ticket / tickets_id when new followup
                 } else {
                     if ((isset($tkt['entities_id']) || isset($tkt['tickets_id'])) && $user_condition || isset($tkt['_refuse_email_no_response']) || isset($tkt['_refuse_email_with_response'])) {
                         if (isset($tkt['_refuse_email_with_response'])) {
                             $this->sendMailRefusedResponse($tkt['_head']['from'], $tkt['name']);
                             $delete_mail = self::REFUSED_FOLDER;
                             $refused++;
                         } else {
                             if (isset($tkt['_refuse_email_no_response'])) {
                                 $delete_mail = self::REFUSED_FOLDER;
                                 $refused++;
                             } else {
                                 if (isset($tkt['entities_id']) || isset($tkt['tickets_id'])) {
                                     // Is a mail responding of an already existing ticket ?
                                     if (isset($tkt['tickets_id'])) {
                                         $fup = new TicketFollowup();
                                         if ($fup->add($tkt)) {
                                             $delete_mail = self::ACCEPTED_FOLDER;
                                         } else {
                                             $error++;
                                             $rejinput['reason'] = NotImportedEmail::FAILED_INSERT;
                                             $rejected->add($rejinput);
                                         }
                                     } else {
                                         // New ticket
                                         $track = new Ticket();
                                         if ($track->add($tkt)) {
                                             $delete_mail = self::ACCEPTED_FOLDER;
                                         } else {
                                             $error++;
                                             $rejinput['reason'] = NotImportedEmail::FAILED_INSERT;
                                             $rejected->add($rejinput);
                                         }
                                     }
                                 } else {
                                     // Case never raise
                                     $delete_mail = self::REFUSED_FOLDER;
                                     $refused++;
                                 }
                             }
                         }
                         //Delete Mail from Mail box if ticket is added successfully
                         if ($delete_mail) {
                             $this->deleteMails($i, $delete_mail);
                         }
                     } else {
                         if (!$tkt['_users_id_requester']) {
                             $rejinput['reason'] = NotImportedEmail::USER_UNKNOWN;
                         } else {
                             $rejinput['reason'] = NotImportedEmail::MATCH_NO_RULE;
                         }
                         $rejected->add($rejinput);
                     }
                 }
                 $this->fetch_emails++;
             }
             imap_expunge($this->marubox);
             $this->close_mailbox();
             //Close Mail Box
             //TRANS: %1$d, %2$d, %3$d, %4$d and %5$d are number of messages
             $msg = sprintf(__('Number of messages: available=%1$d, retrieved=%2$d, refused=%3$d, errors=%4$d, blacklisted=%5$d'), $tot, $this->fetch_emails, $refused, $error, $blacklisted);
             if ($display) {
                 Session::addMessageAfterRedirect($msg, false, $error ? ERROR : INFO);
             } else {
                 return $msg;
             }
         } else {
             $msg = __('Could not connect to mailgate server');
             if ($display) {
                 Session::addMessageAfterRedirect($msg, false, ERROR);
             } else {
                 return $msg;
             }
         }
     } else {
         //TRANS: %s is the ID of the mailgate
         $msg = sprintf(__('Could not find mailgate %d'), $mailgateID);
         if ($display) {
             Session::addMessageAfterRedirect($msg, false, ERROR);
         } else {
             return $msg;
         }
     }
 }
示例#4
0
 function prepareInputForUpdate($input)
 {
     global $CFG_GLPI;
     //picture manually uploaded by user
     if (isset($input["_blank_picture"]) && $input["_blank_picture"]) {
         self::dropPictureFiles($this->fields['picture']);
         $input['picture'] = 'NULL';
     } else {
         if (isset($_FILES['picture'])) {
             if (!count($_FILES['picture']) || empty($_FILES['picture']['name']) || !is_file($_FILES['picture']['tmp_name'])) {
                 switch ($_FILES['picture']['error']) {
                     case UPLOAD_ERR_INI_SIZE:
                     case UPLOAD_ERR_FORM_SIZE:
                         Session::addMessageAfterRedirect(__('File too large to be added.'), false, ERROR);
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         // Session::addMessageAfterRedirect(__('No file specified.'),false,ERROR);
                         break;
                 }
             } else {
                 if (toolbox::getMime($_FILES['picture']['tmp_name'], 'image')) {
                     // Unlink old picture (clean on changing format)
                     self::dropPictureFiles($this->fields['picture']);
                     // Move uploaded file
                     $filename = uniqid($this->fields['id'] . '_');
                     $sub = substr($filename, -2);
                     /* 2 hex digit */
                     $tmp = explode(".", $_FILES['picture']['name']);
                     $extension = array_pop($tmp);
                     @mkdir(GLPI_PICTURE_DIR . "/{$sub}");
                     $picture_path = GLPI_PICTURE_DIR . "/{$sub}/{$filename}.{$extension}";
                     self::dropPictureFiles($filename . "." . $extension);
                     if (in_array($extension, array('jpg', 'jpeg', 'png', 'bmp', 'gif')) && Document::renameForce($_FILES['picture']['tmp_name'], $picture_path)) {
                         Session::addMessageAfterRedirect(__('The file is valid. Upload is successful.'));
                         // For display
                         $input['picture'] = "{$sub}/{$filename}.{$extension}";
                         //prepare a thumbnail
                         $thumb_path = GLPI_PICTURE_DIR . "/{$sub}/{$filename}_min.{$extension}";
                         Toolbox::resizePicture($picture_path, $thumb_path);
                     } else {
                         Session::addMessageAfterRedirect(__('Potential upload attack or file too large. Moving temporary file failed.'), false, ERROR);
                     }
                 } else {
                     Session::addMessageAfterRedirect(__('The file is not an image file.'), false, ERROR);
                 }
             }
         } else {
             //ldap jpegphoto synchronisation.
             if (isset($this->fields["authtype"]) && ($this->fields["authtype"] == Auth::LDAP || Auth::isAlternateAuth($this->fields['authtype'])) && ($picture = $this->syncLdapPhoto())) {
                 if (!empty($picture)) {
                     $input['picture'] = $picture;
                 }
             }
         }
     }
     if (isset($input["password2"])) {
         // Empty : do not update
         if (empty($input["password"])) {
             unset($input["password"]);
         } else {
             if ($input["password"] == $input["password2"]) {
                 // Check right : my password of user with lesser rights
                 if (isset($input['id']) && Config::validatePassword($input["password"]) && ($input['id'] == Session::getLoginUserID() || $this->currentUserHaveMoreRightThan($input['id']) || $input['password_forget_token'] == $this->fields['password_forget_token'] && abs(strtotime($_SESSION["glpi_currenttime"]) - strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP && $this->isEmail($input['email']))) {
                     $input["password"] = Auth::getPasswordHash(Toolbox::unclean_cross_side_scripting_deep(stripslashes($input["password"])));
                 } else {
                     unset($input["password"]);
                 }
                 unset($input["password2"]);
             } else {
                 Session::addMessageAfterRedirect(__('Error: the two passwords do not match'), false, ERROR);
                 return false;
             }
         }
     } else {
         if (isset($input["password"])) {
             // From login
             unset($input["password"]);
         }
     }
     // Update User in the database
     if (!isset($input["id"]) && isset($input["name"])) {
         if ($this->getFromDBbyName($input["name"])) {
             $input["id"] = $this->fields["id"];
         }
     }
     if (isset($input["entities_id"]) && Session::getLoginUserID() === $input['id']) {
         $_SESSION["glpidefault_entity"] = $input["entities_id"];
     }
     // Security on default profile update
     if (isset($input['profiles_id'])) {
         if (!in_array($input['profiles_id'], Profile_User::getUserProfiles($input['id']))) {
             unset($input['profiles_id']);
         }
     }
     // Security on default entity  update
     if (isset($input['entities_id'])) {
         if (!in_array($input['entities_id'], Profile_User::getUserEntities($input['id']))) {
             unset($input['entities_id']);
         }
     }
     if (isset($input['_reset_personal_token'])) {
         $input['personal_token'] = self::getUniquePersonalToken();
         $input['personal_token_date'] = $_SESSION['glpi_currenttime'];
     }
     // Manage preferences fields
     if (Session::getLoginUserID() === $input['id']) {
         if (isset($input['use_mode']) && $_SESSION['glpi_use_mode'] != $input['use_mode']) {
             $_SESSION['glpi_use_mode'] = $input['use_mode'];
             //Session::loadLanguage();
         }
     }
     foreach ($CFG_GLPI['user_pref_field'] as $f) {
         if (isset($input[$f])) {
             if (Session::getLoginUserID() === $input['id']) {
                 if ($_SESSION["glpi{$f}"] != $input[$f]) {
                     $_SESSION["glpi{$f}"] = $input[$f];
                     // reinit translations
                     if ($f == 'language') {
                         $_SESSION['glpi_dropdowntranslations'] = DropdownTranslation::getAvailableTranslations($_SESSION["glpilanguage"]);
                         unset($_SESSION['glpimenu']);
                     }
                 }
             }
             if ($input[$f] == $CFG_GLPI[$f]) {
                 $input[$f] = "NULL";
             }
         }
     }
     return $input;
 }
 /**
  * Display a HTML report about systeme information / configuration
  **/
 function showSystemInformations()
 {
     global $DB, $CFG_GLPI;
     if (!Config::canUpdate()) {
         return false;
     }
     echo "<div class='center' id='tabsbody'>";
     echo "<form name='form' action=\"" . Toolbox::getItemTypeFormURL(__CLASS__) . "\" method='post'>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='4'>" . __('General setup') . "</th></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Log Level') . "</td><td>";
     $values[1] = __('1- Critical (login error only)');
     $values[2] = __('2- Severe (not used)');
     $values[3] = __('3- Important (successful logins)');
     $values[4] = __('4- Notices (add, delete, tracking)');
     $values[5] = __('5- Complete (all)');
     Dropdown::showFromArray('event_loglevel', $values, array('value' => $CFG_GLPI["event_loglevel"]));
     echo "</td><td>" . __('Maximal number of automatic actions (run by CLI)') . "</td><td>";
     Dropdown::showNumber('cron_limit', array('value' => $CFG_GLPI["cron_limit"], 'min' => 1, 'max' => 30));
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td> " . __('Logs in files (SQL, email, automatic action...)') . "</td><td>";
     Dropdown::showYesNo("use_log_in_files", $CFG_GLPI["use_log_in_files"]);
     echo "</td><td> " . _n('Mysql replica', 'Mysql replicas', 1) . "</td><td>";
     $active = DBConnection::isDBSlaveActive();
     Dropdown::showYesNo("_dbslave_status", $active);
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='4' class='center b'>" . __('Password security policy');
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Password security policy validation') . "</td>";
     echo "<td>";
     Dropdown::showYesNo("use_password_security", $CFG_GLPI["use_password_security"]);
     echo "</td>";
     echo "<td>" . __('Password minimum length') . "</td>";
     echo "<td>";
     Dropdown::showNumber('password_min_length', array('value' => $CFG_GLPI["password_min_length"], 'min' => 4, 'max' => 30));
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Password need digit') . "</td>";
     echo "<td>";
     Dropdown::showYesNo("password_need_number", $CFG_GLPI["password_need_number"]);
     echo "</td>";
     echo "<td>" . __('Password need lowercase character') . "</td>";
     echo "<td>";
     Dropdown::showYesNo("password_need_letter", $CFG_GLPI["password_need_letter"]);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Password need uppercase character') . "</td>";
     echo "<td>";
     Dropdown::showYesNo("password_need_caps", $CFG_GLPI["password_need_caps"]);
     echo "</td>";
     echo "<td>" . __('Password need symbol') . "</td>";
     echo "<td>";
     Dropdown::showYesNo("password_need_symbol", $CFG_GLPI["password_need_symbol"]);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='4' class='center b'>" . __('Maintenance mode');
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Maintenance mode') . "</td>";
     echo "<td>";
     Dropdown::showYesNo("maintenance_mode", $CFG_GLPI["maintenance_mode"]);
     echo "</td>";
     //TRANS: Proxy port
     echo "<td>" . __('Maintenance text') . "</td>";
     echo "<td>";
     echo "<textarea cols='70' rows='4' name='maintenance_text'>" . $CFG_GLPI["maintenance_text"];
     echo "</textarea>";
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='4' class='center b'>" . __('Proxy configuration for upgrade check');
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Server') . "</td>";
     echo "<td><input type='text' name='proxy_name' value='" . $CFG_GLPI["proxy_name"] . "'></td>";
     //TRANS: Proxy port
     echo "<td>" . __('Port') . "</td>";
     echo "<td><input type='text' name='proxy_port' value='" . $CFG_GLPI["proxy_port"] . "'></td>";
     echo "</tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td>" . __('Login') . "</td>";
     echo "<td><input type='text' name='proxy_user' value='" . $CFG_GLPI["proxy_user"] . "'></td>";
     echo "<td>" . __('Password') . "</td>";
     echo "<td><input type='password' name='proxy_passwd' value='' autocomplete='off'>";
     echo "<br><input type='checkbox' name='_blank_proxy_passwd'>" . __('Clear');
     echo "</td></tr>";
     echo "<tr class='tab_bg_2'>";
     echo "<td colspan='4' class='center'>";
     echo "<input type='submit' name='update' class='submit' value=\"" . _sx('button', 'Save') . "\">";
     echo "</td></tr>";
     echo "</table>";
     Html::closeForm();
     $width = 128;
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr><th>" . __('Information about system installation and configuration') . "</th></tr>";
     $oldlang = $_SESSION['glpilanguage'];
     // Keep this, for some function call which still use translation (ex showAllReplicateDelay)
     Session::loadLanguage('en_GB');
     // No need to translate, this part always display in english (for copy/paste to forum)
     // Try to compute a better version for .git
     if (is_dir(GLPI_ROOT . "/.git")) {
         $dir = getcwd();
         chdir(GLPI_ROOT);
         $returnCode = 1;
         $result = @exec('git describe --tags 2>&1', $output, $returnCode);
         chdir($dir);
         $ver = $returnCode ? $CFG_GLPI['version'] . '-git' : $result;
     } else {
         $ver = $CFG_GLPI['version'];
     }
     echo "<tr class='tab_bg_1'><td><pre>[code]\n&nbsp;\n";
     echo "GLPI {$ver} (" . $CFG_GLPI['root_doc'] . " => " . GLPI_ROOT . ")\n";
     echo "\n</pre></td></tr>";
     echo "<tr><th>Server</th></tr>\n";
     echo "<tr class='tab_bg_1'><td><pre>\n&nbsp;\n";
     echo wordwrap("Operating system: " . php_uname() . "\n", $width, "\n\t");
     $exts = get_loaded_extensions();
     sort($exts);
     echo wordwrap("PHP " . phpversion() . ' ' . php_sapi_name() . " (" . implode(', ', $exts) . ")\n", $width, "\n\t");
     $msg = "Setup: ";
     foreach (array('max_execution_time', 'memory_limit', 'post_max_size', 'safe_mode', 'session.save_handler', 'upload_max_filesize') as $key) {
         $msg .= $key . '="' . ini_get($key) . '" ';
     }
     echo wordwrap($msg . "\n", $width, "\n\t");
     $msg = 'Software: ';
     if (isset($_SERVER["SERVER_SOFTWARE"])) {
         $msg .= $_SERVER["SERVER_SOFTWARE"];
     }
     if (isset($_SERVER["SERVER_SIGNATURE"])) {
         $msg .= ' (' . Html::clean($_SERVER["SERVER_SIGNATURE"]) . ')';
     }
     echo wordwrap($msg . "\n", $width, "\n\t");
     if (isset($_SERVER["HTTP_USER_AGENT"])) {
         echo "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n";
     }
     foreach ($DB->getInfo() as $key => $val) {
         echo "{$key}: {$val}\n\t";
     }
     echo "\n";
     self::checkWriteAccessToDirs(true);
     toolbox::checkSELinux(true);
     echo "\n</pre></td></tr>";
     self::showLibrariesInformation();
     foreach ($CFG_GLPI["systeminformations_types"] as $type) {
         $tmp = new $type();
         $tmp->showSystemInformations($width);
     }
     Session::loadLanguage($oldlang);
     echo "<tr class='tab_bg_1'><td>[/code]\n</td></tr>";
     echo "<tr class='tab_bg_2'><th>" . __('To copy/paste in your support request') . "</th></tr>\n";
     echo "</table></div>\n";
 }
示例#6
0
 /**
  * Manage use authentication and initialize the session
  *
  * @param $login_name      string
  * @param $login_password  string
  * @param $noauto          boolean (false by default)
  *
  * @return boolean (success)
  */
 function Login($login_name, $login_password, $noauto = false)
 {
     global $DB, $CFG_GLPI;
     $this->getAuthMethods();
     $this->user_present = 1;
     $this->auth_succeded = false;
     //In case the user was deleted in the LDAP directory
     $user_deleted_ldap = false;
     // Trim login_name : avoid LDAP search errors
     $login_name = trim($login_name);
     if (!$noauto && ($authtype = self::checkAlternateAuthSystems())) {
         if ($this->getAlternateAuthSystemsUserLogin($authtype) && !empty($this->user->fields['name'])) {
             // Used for log when login process failed
             $login_name = $this->user->fields['name'];
             $this->auth_succeded = true;
             $this->extauth = 1;
             $this->user_present = $this->user->getFromDBbyName(addslashes($login_name));
             $this->user->fields['authtype'] = $authtype;
             $user_dn = false;
             $ldapservers = '';
             //if LDAP enabled too, get user's infos from LDAP
             if (Toolbox::canUseLdap()) {
                 $ldapservers = array();
                 //User has already authenticate, at least once : it's ldap server if filled
                 if (isset($this->user->fields["auths_id"]) && $this->user->fields["auths_id"] > 0) {
                     $authldap = new AuthLdap();
                     //If ldap server is enabled
                     if ($authldap->getFromDB($this->user->fields["auths_id"]) && $authldap->fields['is_active']) {
                         $ldapservers[] = $authldap->fields;
                     }
                     //User has never beeen authenticated : try all active ldap server to find the right one
                 } else {
                     foreach (getAllDatasFromTable('glpi_authldaps', "`is_active`='1'") as $ldap_config) {
                         $ldapservers[] = $ldap_config;
                     }
                 }
                 foreach ($ldapservers as $ldap_method) {
                     $ds = AuthLdap::connectToServer($ldap_method["host"], $ldap_method["port"], $ldap_method["rootdn"], Toolbox::decrypt($ldap_method["rootdn_passwd"], GLPIKEY), $ldap_method["use_tls"], $ldap_method["deref_option"]);
                     if ($ds) {
                         $params['method'] = AuthLdap::IDENTIFIER_LOGIN;
                         $params['fields'][AuthLdap::IDENTIFIER_LOGIN] = $ldap_method["login_field"];
                         $user_dn = AuthLdap::searchUserDn($ds, array('basedn' => $ldap_method["basedn"], 'login_field' => $ldap_method['login_field'], 'search_parameters' => $params, 'user_params' => array('method' => AuthLDAP::IDENTIFIER_LOGIN, 'value' => $login_name), 'condition' => $ldap_method["condition"]));
                         if ($user_dn) {
                             $this->user->fields['auths_id'] = $ldap_method['id'];
                             $this->user->getFromLDAP($ds, $ldap_method, $user_dn['dn'], $login_name, !$this->user_present);
                             break;
                         }
                     }
                 }
             }
             if (count($ldapservers) == 0 && $authtype == self::EXTERNAL) {
                 // Case of using external auth and no LDAP servers, so get data from external auth
                 $this->user->getFromSSO();
             } else {
                 //If user is set as present in GLPI but no LDAP DN found : it means that the user
                 //is not present in an ldap directory anymore
                 if (!$user_dn && $this->user_present) {
                     $user_deleted_ldap = true;
                     $this->user_deleted_ldap = true;
                 }
             }
             // Reset to secure it
             $this->user->fields['name'] = $login_name;
             $this->user->fields["last_login"] = $_SESSION["glpi_currenttime"];
         } else {
             $this->addToError(__('Empty login or password'));
         }
     }
     // If not already auth
     if (!$this->auth_succeded) {
         if (empty($login_name) || strstr($login_name, "") || empty($login_password) || strstr($login_password, "")) {
             $this->addToError(__('Empty login or password'));
         } else {
             // exists=0 -> user doesn't yet exist
             // exists=1 -> user is present in DB with password
             // exists=2 -> user is present in DB but without password
             $exists = $this->userExists(array('name' => addslashes($login_name)));
             // Pas en premier car sinon on ne fait pas le blankpassword
             // First try to connect via le DATABASE
             if ($exists == 1) {
                 // Without UTF8 decoding
                 if (!$this->auth_succeded) {
                     $this->auth_succeded = $this->connection_db(addslashes($login_name), $login_password);
                     if ($this->auth_succeded) {
                         $this->extauth = 0;
                         $this->user_present = $this->user->getFromDBbyName(addslashes($login_name));
                         $this->user->fields["authtype"] = self::DB_GLPI;
                         $this->user->fields["password"] = $login_password;
                     }
                 }
             } else {
                 if ($exists == 2) {
                     //The user is not authenticated on the GLPI DB, but we need to get information about him
                     //to find out his authentication method
                     $this->user->getFromDBbyName(addslashes($login_name));
                     //If the user has already been logged, the method_auth and auths_id are already set
                     //so we test this connection first
                     switch ($this->user->fields["authtype"]) {
                         case self::CAS:
                         case self::EXTERNAL:
                         case self::LDAP:
                             if (Toolbox::canUseLdap()) {
                                 AuthLdap::tryLdapAuth($this, $login_name, $login_password, $this->user->fields["auths_id"], toolbox::addslashes_deep($this->user->fields["user_dn"]));
                                 if (!$this->auth_succeded && $this->user_deleted_ldap) {
                                     $user_deleted_ldap = true;
                                 }
                             }
                             break;
                         case self::MAIL:
                             if (Toolbox::canUseImapPop()) {
                                 AuthMail::tryMailAuth($this, $login_name, $login_password, $this->user->fields["auths_id"]);
                             }
                             break;
                         case self::NOT_YET_AUTHENTIFIED:
                             break;
                     }
                 } else {
                     if (!$exists) {
                         //test all ldap servers only is user is not present in glpi's DB
                         if (!$this->auth_succeded && Toolbox::canUseLdap()) {
                             AuthLdap::tryLdapAuth($this, $login_name, $login_password, 0, false, false);
                         }
                         //test all imap/pop servers
                         if (!$this->auth_succeded && Toolbox::canUseImapPop()) {
                             AuthMail::tryMailAuth($this, $login_name, $login_password, 0, false);
                         }
                     }
                 }
             }
             // Fin des tests de connexion
         }
     }
     if ($user_deleted_ldap) {
         User::manageDeletedUserInLdap($this->user->fields["id"]);
     }
     // Ok, we have gathered sufficient data, if the first return false the user
     // is not present on the DB, so we add him.
     // if not, we update him.
     if ($this->auth_succeded) {
         //Set user an not deleted from LDAP
         $this->user->fields['is_deleted_ldap'] = 0;
         // Prepare data
         $this->user->fields["last_login"] = $_SESSION["glpi_currenttime"];
         if ($this->extauth) {
             $this->user->fields["_extauth"] = 1;
         }
         if ($DB->isSlave()) {
             if (!$this->user_present) {
                 // Can't add in slave mode
                 $this->addToError(__('User not authorized to connect in GLPI'));
                 $this->auth_succeded = false;
             }
         } else {
             if ($this->user_present) {
                 // First stripslashes to avoid double slashes
                 $input = Toolbox::stripslashes_deep($this->user->fields);
                 // Then ensure addslashes
                 $input = Toolbox::addslashes_deep($input);
                 // update user and Blank PWD to clean old database for the external auth
                 $this->user->update($input);
                 if ($this->extauth) {
                     $this->user->blankPassword();
                 }
             } else {
                 if ($CFG_GLPI["is_users_auto_add"]) {
                     // Auto add user
                     // First stripslashes to avoid double slashes
                     $input = Toolbox::stripslashes_deep($this->user->fields);
                     // Then ensure addslashes
                     $input = Toolbox::addslashes_deep($input);
                     unset($this->user->fields);
                     $this->user->add($input);
                 } else {
                     // Auto add not enable so auth failed
                     $this->addToError(__('User not authorized to connect in GLPI'));
                     $this->auth_succeded = false;
                 }
             }
         }
     }
     // Log Event (if possible)
     if (!$DB->isSlave()) {
         // GET THE IP OF THE CLIENT
         $ip = getenv("HTTP_X_FORWARDED_FOR") ? getenv("HTTP_X_FORWARDED_FOR") : getenv("REMOTE_ADDR");
         if ($this->auth_succeded) {
             if (GLPI_DEMO_MODE) {
                 // not translation in GLPI_DEMO_MODE
                 Event::log(-1, "system", 3, "login", $login_name . " log in from " . $ip);
             } else {
                 //TRANS: %1$s is the login of the user and %2$s its IP address
                 Event::log(-1, "system", 3, "login", sprintf(__('%1$s log in from IP %2$s'), $login_name, $ip));
             }
         } else {
             if (GLPI_DEMO_MODE) {
                 Event::log(-1, "system", 1, "login", "login", "Connection failed for " . $login_name . " ({$ip})");
             } else {
                 //TRANS: %1$s is the login of the user and %2$s its IP address
                 Event::log(-1, "system", 1, "login", sprintf(__('Failed login for %1$s from IP %2$s'), $login_name, $ip));
             }
         }
     }
     Session::init($this);
     if ($noauto) {
         $_SESSION["noAUTO"] = 1;
     }
     return $this->auth_succeded;
 }
 /**
  * Execute a MySQL query
  *
  * @param $query Query to execute
  *
  * @return Query result handler
  **/
 function query($query)
 {
     global $CFG_GLPI, $DEBUG_SQL, $SQL_TOTAL_REQUEST;
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $SQL_TOTAL_REQUEST++;
         $DEBUG_SQL["queries"][$SQL_TOTAL_REQUEST] = $query;
         $TIMER = new Timer();
         $TIMER->start();
     }
     $res = @$this->dbh->query($query);
     if (!$res) {
         // no translation for error logs
         $error = "  *** MySQL query error:\n  SQL: " . addslashes($query) . "\n  Error: " . $this->dbh->error . "\n";
         $error .= toolbox::backtrace(false, 'DBmysql->query()', array('Toolbox::backtrace()'));
         Toolbox::logInFile("sql-errors", $error);
         if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
             $DEBUG_SQL["errors"][$SQL_TOTAL_REQUEST] = $this->error();
         }
     }
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && $CFG_GLPI["debug_sql"]) {
         $TIME = $TIMER->getTime();
         $DEBUG_SQL["times"][$SQL_TOTAL_REQUEST] = $TIME;
     }
     return $res;
 }
/** 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");
}
示例#9
0
 /**
  * Transfer network links
  *
  * @param $itemtype     original type of transfered item
  * @param $ID           original ID of the item
  * @param $newID        new ID of the item
  **/
 function transferNetworkLink($itemtype, $ID, $newID)
 {
     global $DB;
     /// TODO manage with new network system
     $np = new NetworkPort();
     $nn = new NetworkPort_NetworkPort();
     $query = "SELECT `glpi_networkports`.*, `glpi_networkportethernets`.`netpoints_id`\n                FROM `glpi_networkports`\n                LEFT JOIN `glpi_networkportethernets`\n                  ON (`glpi_networkports`.`id` = `glpi_networkportethernets`.`networkports_id`)\n                WHERE `glpi_networkports`.`items_id` = '{$ID}'\n                      AND `glpi_networkports`.`itemtype` = '{$itemtype}'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) != 0) {
             switch ($this->options['keep_networklink']) {
                 // Delete netport
                 case 0:
                     // Not a copy -> delete
                     if ($ID == $newID) {
                         while ($data = $DB->fetch_assoc($result)) {
                             $np->delete(array('id' => $data['id']));
                         }
                     }
                     // Copy -> do nothing
                     break;
                     // Disconnect
                 // Disconnect
                 case 1:
                     // Not a copy -> disconnect
                     if ($ID == $newID) {
                         while ($data = $DB->fetch_assoc($result)) {
                             if ($nn->getFromDBForNetworkPort($data['id'])) {
                                 $nn->delete($data);
                             }
                             if ($data['netpoints_id']) {
                                 $netpointID = $this->transferDropdownNetpoint($data['netpoints_id']);
                                 $input['id'] = $data['id'];
                                 $input['netpoints_id'] = $netpointID;
                                 $np->update($input);
                             }
                         }
                     } else {
                         // Copy -> copy netports
                         while ($data = $DB->fetch_assoc($result)) {
                             $data = Toolbox::addslashes_deep($data);
                             unset($data['id']);
                             $data['items_id'] = $newID;
                             $data['netpoints_id'] = $this->transferDropdownNetpoint($data['netpoints_id']);
                             unset($np->fields);
                             $np->add(toolbox::addslashes_deep($data));
                         }
                     }
                     break;
                     // Keep network links
                 // Keep network links
                 default:
                     // Copy -> Copy netpoints (do not keep links)
                     if ($ID != $newID) {
                         while ($data = $DB->fetch_assoc($result)) {
                             unset($data['id']);
                             $data['items_id'] = $newID;
                             $data['netpoints_id'] = $this->transferDropdownNetpoint($data['netpoints_id']);
                             unset($np->fields);
                             $np->add(toolbox::addslashes_deep($data));
                         }
                     } else {
                         while ($data = $DB->fetch_assoc($result)) {
                             // Not a copy -> only update netpoint
                             if ($data['netpoints_id']) {
                                 $netpointID = $this->transferDropdownNetpoint($data['netpoints_id']);
                                 $input['id'] = $data['id'];
                                 $input['netpoints_id'] = $netpointID;
                                 $np->update($input);
                             }
                         }
                     }
             }
         }
     }
 }
示例#10
0
 /**
  * Authentify a user by checking a specific directory
  *
  * @param $auth         identification object
  * @param $login        user login
  * @param $password     user password
  * @param $ldap_method  ldap_method array to use
  * @param $user_dn      user LDAP DN if present
  *
  * @return identification object
  **/
 static function ldapAuth($auth, $login, $password, $ldap_method, $user_dn)
 {
     $oldlevel = error_reporting(0);
     $user_dn = $auth->connection_ldap($ldap_method, $login, $password);
     error_reporting($oldlevel);
     $auth->auth_succeded = false;
     $auth->extauth = 1;
     if ($user_dn) {
         $auth->auth_succeded = true;
         //There's already an existing user in DB with the same DN but its login field has changed
         if ($auth->user->getFromDBbyDn(toolbox::addslashes_deep($user_dn))) {
             //Change user login
             $auth->user->fields['name'] = $login;
             $auth->user_present = true;
         } else {
             // The user is a new user
             $auth->user_present = $auth->user->getFromDBbyName(addslashes($login));
         }
         $auth->user->getFromLDAP($auth->ldap_connection, $ldap_method, $user_dn, $login, !$auth->user_present);
         $auth->user->fields["authtype"] = Auth::LDAP;
         $auth->user->fields["auths_id"] = $ldap_method["id"];
     }
     return $auth;
 }
示例#11
0
 /**
  * Duplicate a rule
  *
  * @param $ID        of the rule to duplicate
  *
  * @since version 0.85
  *
  * @return true if all ok
  **/
 function duplicateRule($ID)
 {
     //duplicate rule
     $rulecollection = new self();
     $rulecollection->getFromDB($ID);
     //get ranking
     $ruletype = $rulecollection->fields['sub_type'];
     $rule = new $ruletype();
     $nextRanking = $rule->getNextRanking();
     //Update fields of the new duplicate
     $rulecollection->fields['name'] = sprintf(__('Copy of %s'), $rulecollection->fields['name']);
     $rulecollection->fields['is_active'] = 0;
     $rulecollection->fields['ranking'] = $nextRanking;
     $rulecollection->fields['uuid'] = Rule::getUuid();
     unset($rulecollection->fields['id']);
     //add new duplicate
     $input = toolbox::addslashes_deep($rulecollection->fields);
     $newID = $rulecollection->add($input);
     $rule = $rulecollection->getRuleClass();
     if (!$newID) {
         return false;
     }
     //find and duplicate actions
     $ruleaction = new RuleAction(get_class($rule));
     $actions = $ruleaction->find("`rules_id` = '{$ID}'");
     $actions = toolbox::addslashes_deep($actions);
     foreach ($actions as $action) {
         $action['rules_id'] = $newID;
         unset($action['id']);
         if (!$ruleaction->add($action)) {
             return false;
         }
     }
     //find and duplicate criterias
     $rulecritera = new RuleCriteria(get_class($rule));
     $criteria = $rulecritera->find("`rules_id` = '{$ID}'");
     $criteria = toolbox::addslashes_deep($criteria);
     foreach ($criteria as $criterion) {
         $criterion['rules_id'] = $newID;
         unset($criterion['id']);
         if (!$rulecritera->add($criterion)) {
             return false;
         }
     }
     return true;
 }
示例#12
0
 /**
  * Constructor
  *
  * @param $dbconnexion                    Database Connnexion (must be a CommonDBTM object)
  * @param $table        string or array   table name (optional when $crit have FROM entry)
  * @param $crit         string or array   of filed/values, ex array("id"=>1), if empty => all rows
  *                                        (default '')
  * @param $debug                          for log the request (default false)
  **/
 function __construct($dbconnexion, $table, $crit = "", $debug = false)
 {
     $this->conn = $dbconnexion;
     if (is_string($table) && strpos($table, " ")) {
         //if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
         //   trigger_error("Deprecated usage of SQL in DB/request (full query)", E_USER_DEPRECATED);
         //}
         $this->sql = $table;
     } else {
         // Modern way
         if (is_array($table) && isset($table['FROM'])) {
             // Shift the args
             $debug = $crit;
             $crit = $table;
             $table = $crit['FROM'];
             unset($crit['FROM']);
         }
         // Check field, orderby, limit, start in criterias
         $field = "";
         $orderby = "";
         $limit = 0;
         $start = 0;
         $distinct = '';
         $where = '';
         $count = '';
         $join = '';
         if (is_array($crit) && count($crit)) {
             foreach ($crit as $key => $val) {
                 switch ((string) $key) {
                     case 'SELECT':
                     case 'FIELDS':
                         $field = $val;
                         unset($crit[$key]);
                         break;
                     case 'SELECT DISTINCT':
                     case 'DISTINCT FIELDS':
                         $field = $val;
                         $distinct = "DISTINCT";
                         unset($crit[$key]);
                         break;
                     case 'COUNT':
                         $count = $val;
                         unset($crit[$key]);
                         break;
                     case 'ORDER':
                         $orderby = $val;
                         unset($crit[$key]);
                         break;
                     case 'LIMIT':
                         $limit = $val;
                         unset($crit[$key]);
                         break;
                     case 'START':
                         $start = $val;
                         unset($crit[$key]);
                         break;
                     case 'WHERE':
                         $where = $val;
                         unset($crit[$key]);
                         break;
                     case 'JOIN':
                         if (is_array($val)) {
                             foreach ($val as $jointable => $joincrit) {
                                 $join .= " LEFT JOIN " . self::quoteName($jointable) . " ON (" . $this->analyseCrit($joincrit) . ")";
                             }
                         } else {
                             trigger_error("BAD JOIN, value sould be [ table => criteria ]", E_USER_ERROR);
                         }
                         unset($crit[$key]);
                         break;
                 }
             }
         }
         // SELECT field list
         if ($count) {
             $this->sql = "SELECT COUNT(*) AS {$count}";
         } else {
             if (is_array($field)) {
                 $this->sql = "";
                 foreach ($field as $t => $f) {
                     if (is_numeric($t)) {
                         $this->sql .= (empty($this->sql) ? 'SELECT ' : ', ') . self::quoteName($f);
                     } else {
                         if (is_array($f)) {
                             $t = self::quoteName($t);
                             $f = array_map([__CLASS__, 'quoteName'], $f);
                             $this->sql .= (empty($this->sql) ? "SELECT {$t}." : ",{$t}.") . implode(", {$t}.", $f);
                         } else {
                             $t = self::quoteName($t);
                             $f = $f == '*' ? $f : self::quoteName($f);
                             $this->sql .= (empty($this->sql) ? 'SELECT ' : ', ') . "{$t}.{$f}";
                         }
                     }
                 }
             } else {
                 if (empty($field)) {
                     $this->sql = "SELECT *";
                 } else {
                     $this->sql = "SELECT {$distinct} " . self::quoteName($field);
                 }
             }
         }
         // FROM table list
         if (is_array($table)) {
             if (count($table)) {
                 $table = array_map([__CLASS__, 'quoteName'], $table);
                 $this->sql .= ' FROM ' . implode(", ", $table);
             } else {
                 trigger_error("Missing table name", E_USER_ERROR);
             }
         } else {
             if ($table) {
                 $table = self::quoteName($table);
                 $this->sql .= " FROM {$table}";
             } else {
                 /*
                  * TODO filter with if ($where || !empty($crit)) {
                  * but not usefull for now, as we CANNOT write somthing like "SELECT NOW()"
                  */
                 trigger_error("Missing table name", E_USER_ERROR);
             }
         }
         // JOIN
         $this->sql .= $join;
         // WHERE criteria list
         if (!empty($crit)) {
             $this->sql .= " WHERE " . $this->analyseCrit($crit);
         } else {
             if ($where) {
                 $this->sql .= " WHERE " . $this->analyseCrit($where);
             }
         }
         // ORDER BY
         if (is_array($orderby)) {
             $cleanorderby = array();
             foreach ($orderby as $o) {
                 $new = '';
                 $tmp = explode(' ', $o);
                 $new .= self::quoteName($tmp[0]);
                 // ASC OR DESC added
                 if (isset($tmp[1]) && in_array($tmp[1], array('ASC', 'DESC'))) {
                     $new .= ' ' . $tmp[1];
                 }
                 $cleanorderby[] = $new;
             }
             $this->sql .= " ORDER BY " . implode(", ", $cleanorderby);
         } else {
             if (!empty($orderby)) {
                 $this->sql .= " ORDER BY ";
                 $tmp = explode(' ', $orderby);
                 $this->sql .= self::quoteName($tmp[0]);
                 // ASC OR DESC added
                 if (isset($tmp[1]) && in_array($tmp[1], array('ASC', 'DESC'))) {
                     $this->sql .= ' ' . $tmp[1];
                 }
             }
         }
         if (is_numeric($limit) && $limit > 0) {
             $this->sql .= " LIMIT {$limit}";
             if (is_numeric($start) && $start > 0) {
                 $this->sql .= " OFFSET {$start}";
             }
         }
     }
     if ($debug) {
         toolbox::logdebug("Generated query:", $this->getSql());
     }
     $this->res = $this->conn ? $this->conn->query($this->sql) : false;
 }
示例#13
0
 /**
  * Constructor
  *
  * @param $dbconnexion                    Database Connnexion (must be a CommonDBTM object)
  * @param $table                          table name
  * @param $crit         string or array   of filed/values, ex array("id"=>1), if empty => all rows
  *                                        (default '')
  * @param $debug                          for log the request (default false)
  **/
 function __construct($dbconnexion, $table, $crit = "", $debug = false)
 {
     $this->conn = $dbconnexion;
     if (is_string($table) && strpos($table, " ")) {
         $this->sql = $table;
     } else {
         // Check field, orderby, limit, start in criterias
         $field = "";
         $orderby = "";
         $limit = 0;
         $start = 0;
         $distinct = '';
         $where = '';
         if (is_array($crit) && count($crit)) {
             foreach ($crit as $key => $val) {
                 if ($key === "FIELDS") {
                     $field = $val;
                     unset($crit[$key]);
                 } else {
                     if ($key === "DISTINCT FIELDS") {
                         $field = $val;
                         $distinct = "DISTINCT";
                         unset($crit[$key]);
                     } else {
                         if ($key === "ORDER") {
                             $orderby = $val;
                             unset($crit[$key]);
                         } else {
                             if ($key === "LIMIT") {
                                 $limit = $val;
                                 unset($crit[$key]);
                             } else {
                                 if ($key === "START") {
                                     $start = $val;
                                     unset($crit[$key]);
                                 } else {
                                     if ($key === "WHERE") {
                                         $where = $val;
                                         unset($crit[$key]);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // SELECT field list
         if (is_array($field)) {
             $this->sql = "";
             foreach ($field as $t => $f) {
                 if (is_numeric($t)) {
                     $this->sql .= (empty($this->sql) ? 'SELECT ' : ', ') . self::quoteName($f);
                 } else {
                     if (is_array($f)) {
                         $t = self::quoteName($t);
                         $f = array_map([__CLASS__, 'quoteName'], $f);
                         $this->sql .= (empty($this->sql) ? "SELECT {$t}." : ",{$t}.") . implode(", {$t}.", $f);
                     } else {
                         $t = self::quoteName($t);
                         $f = self::quoteName($f);
                         $this->sql .= (empty($this->sql) ? 'SELECT ' : ', ') . "{$t}.{$f}";
                     }
                 }
             }
         } else {
             if (empty($field)) {
                 $this->sql = "SELECT *";
             } else {
                 $this->sql = "SELECT {$distinct} `{$field}`";
             }
         }
         // FROM table list
         if (is_array($table)) {
             $table = array_map([__CLASS__, 'quoteName'], $table);
             $this->sql .= ' FROM ' . implode(", ", $table);
         } else {
             $table = self::quoteName($table);
             $this->sql .= " FROM {$table}";
         }
         // WHERE criteria list
         if (!empty($crit)) {
             $this->sql .= " WHERE " . $this->analyseCrit($crit);
         } else {
             if ($where) {
                 $this->sql .= " WHERE " . $this->analyseCrit($where);
             }
         }
         // ORDER BY
         if (is_array($orderby)) {
             $cleanorderby = array();
             foreach ($orderby as $o) {
                 $new = '';
                 $tmp = explode(' ', $o);
                 $new .= self::quoteName($tmp[0]);
                 // ASC OR DESC added
                 if (isset($tmp[1]) && in_array($tmp[1], array('ASC', 'DESC'))) {
                     $new .= ' ' . $tmp[1];
                 }
                 $cleanorderby[] = $new;
             }
             $this->sql .= " ORDER BY " . implode(", ", $cleanorderby);
         } else {
             if (!empty($orderby)) {
                 $this->sql .= " ORDER BY ";
                 $tmp = explode(' ', $orderby);
                 $this->sql .= self::quoteName($tmp[0]);
                 // ASC OR DESC added
                 if (isset($tmp[1]) && in_array($tmp[1], array('ASC', 'DESC'))) {
                     $this->sql .= ' ' . $tmp[1];
                 }
             }
         }
         if (is_numeric($limit) && $limit > 0) {
             $this->sql .= " LIMIT {$limit}";
             if (is_numeric($start) && $start > 0) {
                 $this->sql .= " OFFSET {$start}";
             }
         }
     }
     if ($debug) {
         toolbox::logdebug("Generated query:", $this->getSql());
     }
     $this->res = $this->conn ? $this->conn->query($this->sql) : false;
 }
示例#14
0
文件: index.php 项目: klaver/peerlist
/*
 * peerlist - an app that shows peer info for your IX
 * (C) 2006i-2009 Martijn Bakker <*****@*****.**>
 */
define('BASEDIR', getcwd() . DIRECTORY_SEPARATOR);
if (!is_file('config.inc.php')) {
    echo "no config file found! Please create config.inc.php\n";
    exit(1);
}
include_once 'config.inc.php';
include_once 'xtemplate.class.php';
include_once 'toolbox.class.php';
$application = array(name => 'peerlist', version => '0.3-rc1');
$xtpl = new xtemplate("templates/peerlist.xtpl");
$toolbox = new toolbox();
$xtpl->assign('application', $toolbox->htmlspecialchars_array($application));
$xtpl->assign('getoptions', $toolbox->htmlspecialchars_array($_GET));
foreach ($config as $routerid => $routerconfig) {
    if (is_array($routerconfig) && $routerconfig['common_name'] != '') {
        $routerconfig['id'] = $routerid;
        if ($_GET['router'] == "{$routerid}" && $_GET['router'] != '') {
            $routerconfig['selected'] = 'selected';
        }
        if (is_file('routers/' . $routerconfig['router']['module'] . '.class.php')) {
            include_once 'routers/' . $routerconfig['router']['module'] . '.class.php';
        } else {
            die('router type not available');
        }
        if (is_file('exchanges/' . $routerconfig['exchange']['module'] . '.class.php')) {
            include_once 'exchanges/' . $routerconfig['exchange']['module'] . '.class.php';