Example #1
0
 function setup()
 {
     if (Admin::count_users() == 0 && isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password'])) {
         // Do setup
         $user_id = User::add($_POST['email']);
         User::signup($user_id, $_POST['username'], $_POST['password'], $this->config->encryption_salt);
         $user = User::get_by_email($_POST['email']);
         // Update session
         $_SESSION['user_id'] = $user->id;
         // Log login
         if (isset($this->plugins->log)) {
             $this->plugins->log->add($_SESSION['user_id'], 'user', NULL, 'signup');
         }
         Application::flash('success', 'You are now logged in to your app!');
         // Go forth!
         header('Location: ' . $this->url_for('admin', 'config'));
         exit;
     } else {
         // Show setup form
         if (Admin::count_users() == 0) {
             Application::flash('info', 'Welcome to Rat!');
             $this->loadView('admin/setup');
         } else {
             throw new RoutingException($this->uri, "Page not found");
         }
     }
 }
Example #2
0
function user_add()
{
    $log = Log::getInstance();
    $user = new User();
    $storeid = isset($_POST['store']) ? $_POST['store'] : 0;
    $user->firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
    $user->lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
    $user->username = isset($_POST['username']) ? $_POST['username'] : "";
    $user->password = isset($_POST['passwd']) ? $_POST['passwd'] : "";
    $user->ci = isset($_POST['ci']) ? $_POST['ci'] : "";
    $user->active = isset($_POST['active']);
    $user->level = isset($_POST['role']) ? $_POST['role'] : 0;
    $user->address = isset($_POST['address']) ? $_POST['address'] : "";
    $user->phone = isset($_POST['phone']) ? $_POST['phone'] : "";
    $user->email = isset($_POST['email']) ? $_POST['email'] : "";
    if ($user->add($storeid)) {
        if ($_FILES['upload']['name']) {
            $imagepath = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']) . "img/user/\${$user->id}.jpg";
            if (move_uploaded_file($_FILES['upload']['tmp_name'], $imagepath)) {
                $user->imagepath = $imagepath;
                $user->update();
            } else {
                $log->addError("No fue posible subir imagen");
            }
        }
        header("Location: index.php?pages=user_detail&user={$user->id}");
    } else {
        $log->addError("No fue posible agregar usuario, verifique que Usuario sea único.");
    }
}
Example #3
0
 public function create()
 {
     if ($this->f3->exists('POST.create')) {
         $user = new User($this->db);
         $user->add();
         $this->f3->reroute('/success/New User Created');
     } else {
         $this->f3->set('page_head', 'Create User');
         $this->f3->set('view', 'user/create.htm');
     }
 }
Example #4
0
 function register()
 {
     $fname = $_POST['reg_first_name'];
     $lname = $_POST['reg_last_name'];
     $email = $_POST['reg_email'];
     $password = $_POST['reg_password'];
     if (strlen($fname) < 2 || strlen($lname) < 2 || !valid_email($email) || User::emailExists($email) || strlen(trim($password)) < 6) {
         throw new Exception("Error when registering new user.");
     }
     User::add($email, md5($password), $fname, $lname);
     redirect('/registered');
 }
 public function menu()
 {
     if ($this->f3->exists('POST.create')) {
         $user = new User($this->db);
         $user->add();
         $this->f3->reroute('/');
     } else {
         $item = new Item($this->db);
         $this->f3->set('items', $item->getAllByCategoryId(1, 1));
         $this->f3->set('view', 'user/item.html');
     }
 }
 /**
  * undocumented function
  *
  * @return void
  * @author 
  **/
 public function store()
 {
     $validator = $this->storeValid();
     if ($validator->passes()) {
         $input = $this->storeInput();
         $user = User::add($input);
         if ($user) {
             return Redirect::route('admin.user')->withStatuses(['add' => 'Tambah Berhasil!']);
         }
         return Redirect::route('admin.user.create')->withErrors(['add' => 'Tambah Gagal!'])->withInput();
     }
     return Redirect::route('admin.user.create')->withErrors($validator)->withInput();
 }
Example #7
0
 public function post_register()
 {
     $rules = Config::get('rules.register');
     $validation = Validator::make(Input::get(), $rules);
     if ($validation->passes()) {
         if ($user = User::add(Input::get())) {
             Auth::login($user);
             return Redirect::to('/')->with('registered', TRUE);
         }
         return Event::first('500', 'You could not be registered due to a system error. We apologize for any inconvenience.');
     }
     return Redirect::to('/register')->with_input()->with_errors($validation);
 }
Example #8
0
 public function doSignUp()
 {
     $user = new StdClass();
     $fields = array('name' => Data::STR, 'lastname' => Data::STR, 'middlename' => Data::STR, 'email' => Data::STR, 'phone' => Data::INT, 'password' => Data::STR);
     foreach ($fields as $field => $dataType) {
         $user->{$field} = Data::get($field, '', $dataType);
     }
     $a = (object) array('success' => false, 'message' => '');
     if (User::add($user)) {
         $a->message = 'Пользователь успешно добавлен!';
         $a->success = true;
     } else {
         $a->message = 'Ошибка при создании пользователя';
     }
     return $a;
 }
Example #9
0
    function addUser()
    {
        $translator = new Translator();
        $user = new User();
        try {
            $user->add($_POST);
            echo <<<EOF
<div class="container">
   <div class="page-header">
        <h1>{$translator->User_registered}</h1>
      </div>
   <p class="lead">{$translator->User_registered_Desc}</p>
      <p >{$translator->Error_Back}</p>
</div>

EOF;
        } catch (Exception $e) {
            echo <<<EOF
<div class="container">
   <div class="page-header">
        <h1>{$translator->Error_User_register}</h1>
      </div>

EOF;
            switch ($e->getCode()) {
                case User::EXISTS:
                    echo "   <p class=\"lead\">{$translator->Error_User_exists_Desc}</p>";
                    break;
                case User::NO_DATA:
                    echo "   <p class=\"lead\">{$translator->Error_User_no_data_Desc}</p>";
                    break;
                case User::BAD_PASSWORD:
                    echo "   <p class=\"lead\">{$translator->Error_User_bad_password_Desc}</p>";
                    break;
                default:
                    echo "   <p class=\"lead\">{$translator->Error_User_register_Desc}</p>";
                    Sendmail::toAdmin(var_export($e, true));
            }
            echo <<<EOF
      <p >{$translator->Error_Back}</p>
</div>

EOF;
        }
    }
 function add_user()
 {
     $do_api_user = new User();
     if ($this->firstname == '' || $this->lastname == '') {
         $this->setMessage("521", "First name, Last name required");
         return false;
     } elseif ($this->email == '') {
         $this->setMessage("522", "Email Id Required");
         return false;
     } elseif ($this->username == '') {
         $this->setMessage("523", "Username required.");
         return false;
     } elseif ($do_api_user->checkDuplicateUserName(trim($this->username))) {
         $this->setMessage("524", "Username is already in use.");
         return false;
     } elseif ($this->password == '') {
         $this->setMessage("525", "Password is required.");
         return false;
     } else {
         $do_api_user->addNew();
         $do_api_user->firstname = $this->firstname;
         $do_api_user->lastname = $this->lastname;
         $do_api_user->email = $this->email;
         $do_api_user->username = $this->username;
         $do_api_user->password = $this->password;
         $do_api_user->company = $this->company;
         $do_api_user->plan = $this->plan;
         $do_api_user->regdate = date("Y-m-d");
         $do_api_user->add();
         $inserted_id = $do_api_user->getPrimaryKeyValue();
         //$do_api_user->addUserAsContact($this->firstname,$this->lastname,$this->company,$this->email,$inserted_id);
         // Lets create the Contact view now
         $ContactView = new ContactView();
         $ContactView->rebuildContactUserTable($inserted_id);
         $this->email_work = $this->email;
         $this->add_contact();
         // adding the contact to the API key user
         //$do_api_user->idcontact = $this->idcontact;
         //$do_api_user->update();
         $this->setValues(array("msg" => "User Added", "stat" => "ok", "code" => "520", "iduser" => $inserted_id, "contact" => $this->idcontact));
         return true;
     }
 }
Example #11
0
 public function register()
 {
     if (post('register')) {
         $pengguna = ['username' => post('username'), 'email' => post('email'), 'level' => 0, 'aktif' => 1];
         $pelanggan = ['nama_lengkap' => post('nama'), 'alamat' => post('alamat'), 'kota' => post('kota'), 'telp' => post('telp')];
         if (post('password') == post('passconf')) {
             $pengguna['password'] = md5(post('password'));
         }
         if ($userId = User::add($pengguna)) {
             $pelanggan['id_pengguna'] = $userId;
             if (Customer::add($pelanggan)) {
                 set_alert('success', 'Registrasi berhasil, silahkan login ke akun yang baru saja anda buat');
                 redirect('login');
             } else {
                 set_alert('error', 'Maaf registrasi gagal');
                 redirect('register');
             }
         }
     }
     return $this->render('form-register', ['heading' => 'Silahkan register']);
 }
Example #12
0
 public function cmdAdd()
 {
     Language::init();
     //
     $login = ArgsHolder::get()->shiftCommand();
     $password = ArgsHolder::get()->shiftCommand();
     $email = ArgsHolder::get()->shiftCommand();
     if ($login === false || $email === false || $password === false) {
         return io::out('Incorrect param count', IO::MESSAGE_FAIL) | 1;
     }
     $confirm = ArgsHolder::get()->getOption('confirmation');
     // TODO  Confirn not working
     // TODO: Registration link without instance of Controller
     $confirm = false;
     io::out('Adding user: ~WHITE~' . $login . ' <' . $email . '>~~~', false);
     try {
         User::add(array("login" => $login, "password" => $password, "email" => $email));
     } catch (UserException $e) {
         return io::out(PHP_EOL . $e->getMessage(), IO::MESSAGE_FAIL) | 127;
     }
     io::done();
 }
Example #13
0
 public function displayMain()
 {
     global $smarty, $link;
     $errors = array();
     if (Tools::isSubmit('CreateUser')) {
         if (!Validate::isEmail(Tools::getRequest('email')) || User::userExists(Tools::getRequest('email'))) {
             $errors[] = 'The email is invalid or an account is already registered with this e-mail!';
         } elseif (empty($_POST['passwd'])) {
             $errors[] = 'The password is empty!';
         } else {
             $user = new User();
             $user->copyFromPost();
             $user->active = 1;
             if ($user->add()) {
                 $address = new Address();
                 $address->copyFromPost();
                 $address->id_user = $user->id;
                 $address->is_default = 1;
                 if ($address->add()) {
                     $user->logined(array('id_address' => $address->id));
                     if (Tools::getRequest("step") == 2) {
                         Tools::redirect($link->getPage('CheckoutView'));
                     } else {
                         Tools::redirect($link->getPage('MyaccountView'));
                     }
                     return;
                 } else {
                     $errors = $address->_errors;
                 }
             } else {
                 $errors = $user->_errors;
             }
         }
     }
     $countrys = Country::loadData(1, 500, null, null, array('active' => 1));
     $smarty->assign(array('id_default_country' => Configuration::get('TM_DEFAULT_COUNTRY_ID'), 'countrys' => $countrys, 'step' => Tools::getRequest("step"), 'errors' => $errors));
     return $smarty->fetch('join.tpl');
 }
Example #14
0
 public static function addEmployee($name, $emp_id, $address_1, $address_2, $landmark, $city, $state, $pincode, $phone, $fax, $email, $website, $description)
 {
     $defaultPassword = '******';
     if (!empty($_SESSION['user']['company'])) {
         //$retCode = User::add($name, '', $emp_id, $defaultPassword, $phone, $phone, $email,  $address_1, $address_2, $landmark, $city, $state, $pincode, $_SESSION['user']['company']);
         if (User::add($name, '', $emp_id, $defaultPassword, $phone, $phone, $email, $address_1, $address_2, $landmark, $city, $state, $pincode, $_SESSION['user']['company'])) {
             User::activate(User::getIdByEmail($email));
             $mEmployee = new User(User::getIdByEmail($email));
             $mAddedBy = new User();
             $mEmployee->SetAddedby($mAddedBy->getId());
             Mailer::sendEmployeeAddedMessage($name, $emp_id, $email, $defaultPassword, $_SESSION['user']['company'], $mAddedBy->getFullname());
             return Timeline::addTimelineEvent("staff_addition", "", "", $mEmployee->getId(), $mAddedBy->getId(), 1);
             return true;
         }
         return false;
     } else {
         return false;
     }
 }
Example #15
0
function __autoload($className)
{
    include_once "models/{$className}.php";
}
$users = new User("localhost", "root", "", "test");
if (!isset($_POST['action'])) {
    print json_encode(0);
    return;
}
switch ($_POST['action']) {
    case 'get_users':
        print $users->getUsers();
        break;
    case 'add_user':
        $user = new stdClass();
        $user = json_decode($_POST['user']);
        print $users->add($user);
        break;
    case 'delete_user':
        $user = new stdClass();
        $user = json_decode($_POST['user']);
        print $users->delete($user);
        break;
    case 'update_field_data':
        $user = new stdClass();
        $user = json_decode($_POST['user']);
        print $users->updateValue($user);
        break;
}
exit;
Example #16
0
File: Admin.php Project: eadz/chyrp
 /**
  * Function: import_movabletype
  * MovableType importing.
  */
 public function import_movabletype()
 {
     if (empty($_POST)) {
         redirect("/admin/?action=import");
     }
     if (!Visitor::current()->group->can("add_post")) {
         show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
     }
     $config = Config::current();
     $trigger = Trigger::current();
     $dbcon = $dbsel = false;
     if ($link = @mysql_connect($_POST['host'], $_POST['username'], $_POST['password'])) {
         $dbcon = true;
         $dbsel = @mysql_select_db($_POST['database'], $link);
     }
     if (!$dbcon or !$dbsel) {
         Flash::warning(__("Could not connect to the specified MovableType database."), "/admin/?action=import");
     }
     mysql_query("SET NAMES 'utf8'");
     $get_authors = mysql_query("SELECT * FROM mt_author ORDER BY author_id ASC", $link) or error(__("Database Error"), mysql_error());
     $users = array();
     while ($author = mysql_fetch_array($get_authors)) {
         # Try to figure out if this author is the same as the person doing the import.
         if ($author["author_name"] == Visitor::current()->login or $author["author_nickname"] == Visitor::current()->login or $author["author_nickname"] == Visitor::current()->full_name or $author["author_url"] == Visitor::current()->website or $author["author_email"] == Visitor::current()->email) {
             $users[$author["author_id"]] = Visitor::current();
         } else {
             $users[$author["author_id"]] = User::add($author["author_name"], $author["author_password"], $author["author_email"], $author["author_nickname"] != $author["author_name"] ? $author["author_nickname"] : "", $author["author_url"], $author["author_can_create_blog"] == "1" ? Visitor::current()->group : null, $author["author_created_on"], false);
         }
     }
     $get_posts = mysql_query("SELECT * FROM mt_entry ORDER BY entry_id ASC", $link) or error(__("Database Error"), mysql_error());
     $posts = array();
     while ($post = mysql_fetch_array($get_posts)) {
         $posts[$post["entry_id"]] = $post;
     }
     foreach ($posts as $post) {
         $body = $post["entry_text"];
         if (!empty($post["entry_text_more"])) {
             $body .= "\n\n<!--more-->\n\n" . $post["entry_text_more"];
         }
         $regexp_url = preg_quote($_POST['media_url'], "/");
         if (!empty($_POST['media_url']) and preg_match_all("/{$regexp_url}([^\\.\\!,\\?;\"\\'<>\\(\\)\\[\\]\\{\\}\\s\t ]+)\\.([a-zA-Z0-9]+)/", $body, $media)) {
             foreach ($media[0] as $matched_url) {
                 $filename = upload_from_url($matched_url);
                 $body = str_replace($matched_url, $config->url . $config->uploads_path . $filename, $body);
             }
         }
         $status_translate = array(1 => "draft", 2 => "public", 3 => "draft", 4 => "draft");
         $clean = oneof($post["entry_basename"], sanitize($post["entry_title"]));
         if (empty($post["entry_class"]) or $post["entry_class"] == "entry") {
             $new_post = Post::add(array("title" => $post["entry_title"], "body" => $body, "imported_from" => "movabletype"), $clean, Post::check_url($clean), "text", @$users[$post["entry_author_id"]], false, $status_translate[$post["entry_status"]], oneof(@$post["entry_authored_on"], @$post["entry_created_on"], datetime()), $post["entry_modified_on"], "", false);
             $trigger->call("import_movabletype_post", $post, $new_post, $link);
         } elseif (@$post["entry_class"] == "page") {
             $new_page = Page::add($post["entry_title"], $body, null, 0, true, 0, $clean, Page::check_url($clean));
             $trigger->call("import_movabletype_page", $post, $new_page, $link);
         }
     }
     mysql_close($link);
     Flash::notice(__("MovableType content successfully imported!"), "/admin/?action=import");
 }
require_once '../model/pemesanan.php';
require_once '../model/user.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //pemesanan
    $id_barang = $_POST["id_barang"];
    $status = $_POST["status"];
    $tgl_awal = $_POST["tglawal"];
    //user
    $name = $_POST["namauser"];
    $no_identitas = $_POST["no_identitas"];
    $pekerjaan = $_POST["pekerjaan"];
    $alamat = $_POST["alamat"];
    $telepon = $_POST["telepon"];
    $fakultas = $_POST["fakultas"];
    $jurusan = $_POST["jurusan"];
    $userModel = new User();
    $arr = $userModel->getWithNumber($no_identitas);
    if (empty($arr)) {
        $userModel->add($name, $no_identitas, $pekerjaan, $alamat, $telepon, $fakultas, $jurusan);
    }
    $arr2 = $userModel->getWithNumber($no_identitas);
    foreach ($arr2 as $key) {
        $id_user = $key["id_user"];
    }
    $pemesananModel = new Pemesanan();
    foreach ($id_barang as $asd) {
        $pemesananModel->add($asd, $id_user, $status, $tgl_awal);
    }
}
header("Location: ../view/pemesanan.php");
exit;
 protected function saveUser()
 {
     $form = Form::load('pilot.views.UserMain');
     $user = new User();
     if ($user_id = Application::param('user_id')) {
         $user->clauseSafe('user_id', $user_id);
         $user->clearJoins('Group');
     }
     $grp = new Group();
     if ($groups = $grp->collect(Application::param('Group'))) {
         foreach ($groups as $grp) {
             $user->add($grp);
         }
     }
     $this->saveObject($form, $user, $this->userTitle());
     if (!Application::param('user_id')) {
         $this->user_to_edit = $user;
         $this->state = 'change_user_password';
     }
 }
Example #19
0
			$add_user_error = false;

			$group = isset($_POST['group']) ? $_POST['group'] : '0';
			$visibility = isset($_POST['isVisible']) ? 'y' : 'n';
			$filterType = isset($_POST['useFilter']) ? $_POST['useFilter'] : 'tag';
			$filter = $filterType&&isset($_POST['feedFilter'])?$_POST['feedFilter']:'';
			$addUser = isset($_POST['addUser']) ? $_POST['addUser'] : '******';
			$username = isset($_POST['username']) ? $_POST['username'] : '';
			if($addUser=='-1' && empty($username)) $addUser = '******'; 

			if($addUser == '-1') {
				// 회원 추가
				$password = substr(md5(mktime()), 0, 10);
				$name = _f('임시 비밀번호 : %1', $password);
				$email = '*****@*****.**';
				if(!User::add($username, $password, $name, $email)) {
					$add_user_error = $username;
				} else {
					$addUser = User::getId($username);
				}
			}

			if(!$add_user_error) {
					$id = $event->on('Add.addFeed', array($_POST['feedURL'], $visibility, $filter, $filterType, $group, $addUser));
					if($id === false || !is_numeric($id) || empty($id)) {
						$id = Feed::add($_POST['feedURL'], $visibility, $filter, $filterType, $group, $addUser);	
					}

					addAppMessage(_t('블로그를 추가했습니다.'));

					if(Validator::getBool($config->useVerifier) && !isAdmin()) {
/** 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");
}
Example #21
0
		if( $identity !== $ident_conf )
		{
			kick(1, $vals, 7);
		}
		
		if( $password == null || $password == "" )
		{
			kick(1, $vals, 6);
		}

		if( $password !== $pass_conf )
		{
			kick(1, $vals, 8);
		}
		
		$stat = User::add($fname, $lname, $identity, $password, $role);
		
		if( $stat )
		{
			kick(2, null, 1);
		}
		else
		{
			kick(1, $vals, 9);
		}
	}
	else
	{
		kick(0, array('identity' => $identity), 3);
	}
	
Example #22
0
 /**
  * Function: register
  * Process registration. If registration is disabled or if the user is already logged in, it will error.
  */
 public function register()
 {
     $config = Config::current();
     if (!$config->can_register) {
         error(__("Registration Disabled"), __("I'm sorry, but this site is not allowing registration."));
     }
     if (logged_in()) {
         error(__("Error"), __("You're already logged in."));
     }
     if (!empty($_POST)) {
         $route = Route::current();
         if (empty($_POST['login'])) {
             Flash::warning(__("Please enter a username for your account."));
         } elseif (count(User::find(array("where" => array("login" => $_POST['login']))))) {
             Flash::warning(__("That username is already in use."));
         }
         if (empty($_POST['password1']) and empty($_POST['password2'])) {
             Flash::warning(__("Password cannot be blank."));
         } elseif ($_POST['password1'] != $_POST['password2']) {
             Flash::warning(__("Passwords do not match."));
         }
         if (empty($_POST['email'])) {
             Flash::warning(__("E-mail address cannot be blank."));
         } elseif (!preg_match("/^[_A-z0-9-]+((\\.|\\+)[_A-z0-9-]+)*@[A-z0-9-]+(\\.[A-z0-9-]+)*(\\.[A-z]{2,4})\$/", $_POST['email'])) {
             Flash::warning(__("Invalid e-mail address."));
         }
         if (!Flash::exists("warning")) {
             $user = User::add($_POST['login'], $_POST['password1'], $_POST['email']);
             Trigger::current()->call("user_registered", $user);
             $_SESSION['user_id'] = $user->id;
             Flash::notice(__("Registration successful."), "/");
         }
     }
     $this->display("forms/user/register", array(), __("Register"));
 }
Example #23
0
 /**
  * Сохраняет и обновляет параметры пользователя.
  * @return type
  */
 public function saveUser()
 {
     $this->messageSucces = $this->lang['ACT_SAVE_USER'];
     $this->messageError = $this->lang['ACT_NOT_SAVE_USER'];
     // Обновление.
     if (!empty($_POST['id'])) {
         // если пароль не передан значит не обновляем его
         if (empty($_POST['pass'])) {
             unset($_POST['pass']);
         } else {
             $_POST['pass'] = crypt($_POST['pass']);
         }
         //вычисляем надо ли перезаписать данные текущего пользователя после обновления
         //(только в том случае если из админки меняется запись текущего пользователя)
         $authRewrite = $_POST['id'] != User::getThis()->id ? true : false;
         // если происходит попытка создания нового администратора от лица модератора, то вывести ошибку
         if ($_POST['role'] == '1') {
             if (!USER::AccessOnly('1')) {
                 return false;
             }
         }
         if ($_POST['birthday']) {
             $_POST['birthday'] = date('Y-m-d', strtotime($_POST['birthday']));
         }
         if (User::update($_POST['id'], $_POST, $authRewrite)) {
             $this->data = $_POST;
         } else {
             return false;
         }
     } else {
         // добавление
         if ($_POST['role'] == '1') {
             if (!USER::AccessOnly('1')) {
                 return false;
             }
         }
         try {
             $_POST['id'] = User::add($_POST);
         } catch (Exception $exc) {
             $this->messageError = $this->lang['ACT_ERR_SAVE_USER'];
             return false;
         }
         //отправка письма с информацией о регистрации
         $siteName = MG::getSetting('sitename');
         $userEmail = $_POST['email'];
         $message = '
     Здравствуйте!<br>
       Вы получили данное письмо так как на сайте ' . $siteName . ' зарегистрирован новый пользователь с логином ' . $userEmail . '.<br>
       Отвечать на данное сообщение не нужно.';
         $emailData = array('nameFrom' => $siteName, 'emailFrom' => MG::getSetting('noReplyEmail'), 'nameTo' => 'Пользователю сайта ' . $siteName, 'emailTo' => $userEmail, 'subject' => 'Активация пользователя на сайте ' . $siteName, 'body' => $message, 'html' => true);
         Mailer::sendMimeMail($emailData);
         $_POST['date_add'] = date('d.m.Y H:i');
         $this->data = $_POST;
     }
     return true;
 }
Example #24
0
<?php

/// Copyright (c) 2004-2012, Needlworks  / Tatter Network Foundation
/// All rights reserved. Licensed under the GPL.
/// See the GNU General Public License for more details. (/documents/LICENSE, /documents/COPYRIGHT)
require ROOT . '/library/preprocessor.php';
$IV = array('GET' => array('name' => array('string'), 'email' => array('email')));
requireStrictRoute();
$result = User::add($_GET['email'], $_GET['name']);
if ($result === true) {
    Respond::PrintResult(array('error' => 0));
} else {
    Respond::PrintResult(array('error' => -1, 'result' => $result));
}
Example #25
0
 static function add_from_ldap($login, $password)
 {
     if (!function_exists('ldap_connect_and_login')) {
         return false;
     }
     $con = @ldap_connect_and_login($login, $password);
     if (!$con) {
         return false;
     }
     // create a new user based on LDAP data
     $search = ldap_search($con, LDAP_BASE_DN, "cn={$login}");
     if (!$search) {
         return false;
     }
     $entries = ldap_get_entries($con, $search);
     ldap_unbind($con);
     if (empty($entries)) {
         return false;
     }
     $data = userdata_from_ldap($entries[0]);
     if (!$data) {
         return false;
     }
     $data['login'] = $login;
     $data['password'] = '';
     $data['auth_method'] = 'ldap';
     $data['is_admin'] = false;
     return User::add($data);
 }
Example #26
0
 function addUser($email, $name, $comment, $senderName, $senderEmail)
 {
     requireModel('blog.user');
     requireModel('blog.blogSetting');
     global $database, $service, $blogURL, $hostURL, $user, $blog;
     $blogid = getBlogId();
     if (empty($email)) {
         return 1;
     }
     if (!preg_match('/^[^@]+@([-a-zA-Z0-9]+\\.)+[-a-zA-Z0-9]+$/', $email)) {
         return array(2, _t('이메일이 바르지 않습니다.'));
     }
     $isUserExists = User::getUserIdByEmail($email);
     if (empty($isUserExists)) {
         // If user is not exist
         User::add($email, $name);
     }
     $userid = User::getUserIdByEmail($email);
     $result = addBlog(getBlogId(), $userid, null);
     if ($result === true) {
         return sendInvitationMail(getBlogId(), $userid, User::getName($userid), $comment, $senderName, $senderEmail);
     }
     return $result;
 }
Example #27
0
 /** Import a user from a specific ldap server
  *
  * @param $params       array of parameters: method (IDENTIFIER_LOGIN or IDENTIFIER_EMAIL) + value
  * @param $action             synchoronize (true) or import (false)
  * @param $ldap_server        ID of the LDAP server to use
  * @param $display            display message information on redirect (false by default)
  *
  * @return  nothing
  **/
 static function ldapImportUserByServerId($params = array(), $action, $ldap_server, $display = false)
 {
     global $DB;
     static $conn_cache = array();
     $params = Toolbox::stripslashes_deep($params);
     $config_ldap = new self();
     $res = $config_ldap->getFromDB($ldap_server);
     $ldap_users = array();
     // we prevent some delay...
     if (!$res) {
         return false;
     }
     $search_parameters = array();
     //Connect to the directory
     if (isset($conn_cache[$ldap_server])) {
         $ds = $conn_cache[$ldap_server];
     } else {
         $ds = $config_ldap->connect();
     }
     if ($ds) {
         $conn_cache[$ldap_server] = $ds;
         $search_parameters['method'] = $params['method'];
         $search_parameters['fields'][self::IDENTIFIER_LOGIN] = $config_ldap->fields['login_field'];
         if ($params['method'] == self::IDENTIFIER_EMAIL) {
             $search_parameters['fields'][self::IDENTIFIER_EMAIL] = $config_ldap->fields['email1_field'];
         }
         //Get the user's dn & login
         $attribs = array('basedn' => $config_ldap->fields['basedn'], 'login_field' => $search_parameters['fields'][$search_parameters['method']], 'search_parameters' => $search_parameters, 'user_params' => $params, 'condition' => $config_ldap->fields['condition']);
         $infos = self::searchUserDn($ds, $attribs);
         if ($infos && $infos['dn']) {
             $user_dn = $infos['dn'];
             $login = $infos[$config_ldap->fields['login_field']];
             $groups = array();
             $user = new User();
             //Get information from LDAP
             if ($user->getFromLDAP($ds, $config_ldap->fields, $user_dn, addslashes($login), $action == self::ACTION_IMPORT)) {
                 // Add the auth method
                 // Force date sync
                 $user->fields["date_sync"] = $_SESSION["glpi_currenttime"];
                 $user->fields['is_deleted_ldap'] = 0;
                 if ($action == self::ACTION_IMPORT) {
                     $user->fields["authtype"] = Auth::LDAP;
                     $user->fields["auths_id"] = $ldap_server;
                     //Save information in database !
                     $input = $user->fields;
                     // Display message after redirect
                     if ($display) {
                         $input['add'] = 1;
                     }
                     $user->fields["id"] = $user->add($input);
                     return array('action' => self::USER_IMPORTED, 'id' => $user->fields["id"]);
                 }
                 $input = $user->fields;
                 //Get the ID by user name
                 if (!($id = User::getIdByfield('name', $login))) {
                     //In case user id as changed : get id by dn
                     $id = User::getIdByfield('user_dn', $user_dn);
                 }
                 $input['id'] = $id;
                 if ($display) {
                     $input['update'] = 1;
                 }
                 $user->update($input);
                 return array('action' => self::USER_SYNCHRONIZED, 'id' => $input['id']);
             }
             return false;
         }
         if ($action != self::ACTION_IMPORT) {
             $users_id = User::getIdByField('name', $params['value']);
             User::manageDeletedUserInLdap($users_id);
             return array('action' => self::USER_DELETED_LDAP, 'id' => $users_id);
         }
     } else {
         return false;
     }
 }
 public function orders($do = '', $id = '')
 {
     $this->data['heading'] = 'Administrasi: Pembelian';
     switch ($do) {
         case 'form':
             if (post('submit')) {
                 $userKey = User::primary();
                 $customerKey = Customer::primary();
                 $productKey = Product::primary();
                 $order = [$userKey => 1, 'status' => post('status') ?: 0];
                 if ($tanggal = post('tanggal')) {
                     $order['tanggal'] = formatTanggal($tanggal, 'Y-m-d');
                 } else {
                     $order['tanggal'] = date('Y-m-d');
                 }
                 try {
                     $upload = new Upload('pembayaran');
                     $order['pembayaran'] = $upload->doUpload();
                 } catch (Exception $e) {
                     setAlert('error', $e->getMessage());
                 }
                 if ($id_pelanggan = post($customerKey)) {
                     $order[$customerKey] = $id_pelanggan;
                 } else {
                     $pengguna = ['username' => post('username'), 'email' => post('email'), 'level' => 0, 'aktif' => 1];
                     $pelanggan = ['nama_lengkap' => post('nama_lengkap'), 'alamat' => post('alamat'), 'kota' => post('kota'), 'telp' => post('telp')];
                     if ($password = post('password') and $password == post('passconf')) {
                         $pengguna['password'] = $password;
                     }
                     if ($id_pengguna = User::add($pengguna)) {
                         $pelanggan[$userKey] = $id_pengguna;
                     }
                     if ($id_pengguna and $id_pelanggan = Customer::add($pelanggan)) {
                         $order[$customerKey] = $id_pelanggan;
                     }
                 }
                 if ($produks = post($productKey)) {
                     $produk_qty = post('produk_qty');
                     $produk_arr = [];
                     foreach ($produks as $i => $produk_id) {
                         $produk_arr[$produk_id] = $produk_qty[$i];
                     }
                     $order['produk'] = serialize($produk_arr);
                 }
                 if ($ongkir = post('ongkir') and $kurir = post('kurir')) {
                     $order['ongkir'] = $ongkir;
                     $order['kurir'] = $kurir;
                 }
                 if ($belanja = post('belanja') and $total = post('total')) {
                     $order['belanja'] = $belanja;
                     $order['total'] = $total;
                 }
                 if ($order['status'] === 0) {
                     $order['potongan'] = post('potongan') ?: 0;
                     $order['bayar'] = post('bayar') ?: 0;
                     $order['kembali'] = post('kembali') ?: 0;
                     if ($order['kembali'] < 0) {
                         $order['kembali'] = 0;
                     }
                     if ($order['bayar'] > 0) {
                         $order['status'] = 1;
                     }
                 }
                 if ($resi = post('resi')) {
                     $order['resi'] = $resi;
                 }
                 if (Order::save($order, $id)) {
                     if ($id) {
                         setAlert('success', 'Berhasil memperbarui data order <b>' . $order['nama'] . '</b>');
                     } else {
                         setAlert('success', 'Berhasil menambahkan order <b>' . $order['nama'] . '</b>');
                     }
                     return redirect('admin-shop/orders');
                 }
                 setAlert('error', 'Terjadi kesalahan dalam penyimpanan order');
                 return redirect($this->uri->path());
             }
             $order_data = $id ? Order::show($id)->fetchOne() : [];
             if (!User::is('admin') and ($order_data and $order_data->{$customerKey} != User::current($customerKey))) {
                 return redirect('admin-shop/orders');
             }
             $this->data['data'] = $order_data;
             return $this->render('order-form', $this->data);
             break;
         case 'delete':
             if (Order::del([Order::primary() => $id])) {
                 setAlert('success', 'Order berhasil terhapus');
             } else {
                 setAlert('error', 'Terjadi kesalahan dalam penghapusan order');
             }
             return redirect('admin-shop/orders');
             break;
         default:
             $filter = !User::is('admin') ? [Customer::primary() => User::current('id_pelanggan')] : [];
             $this->data['data'] = Order::show($filter, get('sort'));
             return $this->render('order-table', $this->data);
             break;
     }
 }
    Html::redirect($CFG_GLPI["root_doc"] . "/front/user.form.php?id=" . $user->fields['id']);
}
if (empty($_GET["name"])) {
    $_GET["name"] = "";
}
if (isset($_GET['getvcard'])) {
    if (empty($_GET["id"])) {
        Html::redirect($CFG_GLPI["root_doc"] . "/front/user.php");
    }
    $user->check($_GET['id'], READ);
    $user->generateVcard();
} else {
    if (isset($_POST["add"])) {
        $user->check(-1, CREATE, $_POST);
        // Pas de nom pas d'ajout
        if (!empty($_POST["name"]) && ($newID = $user->add($_POST))) {
            Event::log($newID, "users", 4, "setup", sprintf(__('%1$s adds the item %2$s'), $_SESSION["glpiname"], $_POST["name"]));
            if ($_SESSION['glpibackcreated']) {
                Html::redirect($user->getFormURL() . "?id=" . $newID);
            }
        }
        Html::back();
    } else {
        if (isset($_POST["delete"])) {
            $user->check($_POST['id'], DELETE);
            $user->delete($_POST);
            Event::log($_POST["id"], "users", 4, "setup", sprintf(__('%s deletes an item'), $_SESSION["glpiname"]));
            $user->redirectToList();
        } else {
            if (isset($_POST["restore"])) {
                $user->check($_POST['id'], PURGE);
Example #30
0
         }
     } else {
         echo "<script>alert('Username or Password incorrect. Please try again.');</script>";
         echo "<script>window.location.href = 'login.php'</script>";
         //header('Location:login.php');
     }
     break;
 case "register":
     $firstname = $_POST['firstname'];
     $lastname = $_POST['lastname'];
     $username = $_POST['username'];
     $password = $_POST['password'];
     $phone_m = $_POST['phone_m'];
     $phone_o = $_POST['phone_o'];
     $email = $_POST['email'];
     if (User::add($firstname, $lastname, $username, $password, $phone_m, $phone_o, $email)) {
         echo "<script>alert('User registered successfully!!!');</script>";
         echo "<script>window.location.href = '../user/login.php'</script>";
         //echo "<script>window.location.href = '../company/register.php'</script>";
         //header('Location:../company/register.php');
     } else {
         echo "<script>alert('Sorry, some error occured.');</script>";
         echo "<script>window.location.href = 'register.php'</script>";
     }
     break;
 case "logout":
     if ($mUser->logout()) {
         header('Location:login.php');
         exit;
     } else {
         header('Location:abc.php');