public function form() { \CI::form_validation()->set_rules('to_email', 'lang:recipient_email', 'trim|required'); \CI::form_validation()->set_rules('to_name', 'lang:recipient_name', 'trim|required'); \CI::form_validation()->set_rules('from', 'lang:sender_name', 'trim|required'); \CI::form_validation()->set_rules('personal_message', 'lang:personal_message', 'trim'); \CI::form_validation()->set_rules('beginning_amount', 'lang:amount', 'trim|required|numeric'); $data['page_title'] = lang('add_gift_card'); if (\CI::form_validation()->run() == FALSE) { $this->view('gift_card_form', $data); } else { $save['code'] = generate_code(); // from the string helper $save['to_email'] = \CI::input()->post('to_email'); $save['to_name'] = \CI::input()->post('to_name'); $save['from'] = \CI::input()->post('from'); $save['personal_message'] = \CI::input()->post('personal_message'); $save['beginning_amount'] = \CI::input()->post('beginning_amount'); \CI::GiftCards()->saveCard($save); if (\CI::input()->post('sendNotification')) { \GoCart\Emails::giftCardNotification($save); } \CI::session()->set_flashdata('message', lang('message_saved_gift_card')); redirect('admin/gift-cards'); } }
function user_login($mysqli, $login, $password) { // Получим данные пользователя $user_data = user_get_data_by_login($mysqli, $login); // Сравниваем пароли if ($user_data['password'] === md5(md5($password))) { // Пароли сошлись // Генерируем случайное число и шифруем его $hash = md5(generate_code(10)); // Запрос $query = "UPDATE users SET hash='{$hash}' WHERE id='{$user_data['id']}'"; // Записываем в БД новый хеш авторизации и ID if ($result = $mysqli->query($query)) { // Запись прошла успешно // Запишем событие в журнал event_add($mysqli, 15, "Пользователь принял смену.", $_POST['login']); // Запишем в куки id setcookie("id", $user_data['id'], time() + 60 * 60 * 24 * 30); // и хэш setcookie("hash", $hash, time() + 60 * 60 * 24 * 30); // Переадресовываем на главную header("Location: index.php"); exit; // Сообщим об успешном входе return "Добро пожаловать"; } return "Ошибка записи в БД"; } else { return "Неправильная комбинация имени пользователя и пароля"; } }
function entry_captcha() { //session_start(); //生成验证码图片 Header("Content-type: image/PNG"); $im = imagecreate(44, 18); // 画一张指定宽高的图片 $back = ImageColorAllocate($im, 245, 245, 245); // 定义背景颜色 imagefill($im, 0, 0, $back); //把背景颜色填充到刚刚画出来的图片中 $vcodes = ""; //srand((double)microtime()*1000000); //生成4位数字 $vcodes = generate_code(4); for ($i = 0; $i < 4; $i++) { $font = ImageColorAllocate($im, rand(100, 255), rand(0, 100), rand(100, 255)); // 生成随机颜色 $authnum = $vcodes[$i]; imagestring($im, 5, 2 + $i * 10, 1, $authnum, $font); } $_SESSION['captcha'] = strtolower($vcodes); for ($i = 0; $i < 100; $i++) { $randcolor = ImageColorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); imagesetpixel($im, rand() % 70, rand() % 30, $randcolor); // 画像素点函数 } ImagePNG($im); ImageDestroy($im); }
function deal_code_form($id = false) { $this->load->helper('form'); $this->load->library('form_validation'); $data['page_title'] = 'Add Deal Code'; //default values are empty if the deal_type is new $data['id'] = ''; $data['code_no'] = ''; if ($id) { } $this->form_validation->set_rules('code_no', 'Number of codes', 'trim|required|is_numeric'); if ($this->form_validation->run() == FALSE) { $this->load->view($this->config->item('admin_folder') . '/deal_code_form', $data); } else { $code_nums = $this->input->post('code_no'); $k = $code_nums; $this->load->helper('string'); while ($k) { $code = generate_code(6); if (!$this->Dealsign_model->check_deal_code($code)) { $data = array('id' => '', 'deal_code' => $code, 'is_used' => 0); $this->Dealsign_model->save_deal_code($data); $k--; } } $this->session->set_flashdata('message', '<b>' . $code_nums . '</b> codes has been generated successfully'); //go back to the deal_city list redirect($this->config->item('admin_folder') . '/dealsign/deal_codes'); } }
function process_form() { // INITIAL DATA FETCHING global $school_name, $email; // so that the show_form function can use these values later $school_name = htmlentities(trim($_POST['school_name'])); $email = htmlentities($_POST['email']); $name_msg = validate_school_name($school_name); $recaptcha_msg = validate_recaptcha(); $email_msg = validate_coach_email($email); if ($name_msg !== true) { alert($name_msg, -1); } else { if ($recaptcha_msg !== true) { alert($recaptcha_msg, -1); } else { if ($email_msg !== true) { alert($email_msg, -1); } else { // ** All information has been validated at this point ** $access_code = generate_code(5); // Create database entry DB::insert('schools', array('name' => $school_name, 'coach_email' => $email, 'access_code' => $access_code)); // Get user id (MySQL AUTO_INCREMENT id) $id = DB::insertId(); global $LMT_EMAIL; $lmt_year = htmlentities(map_value('year')); $lmt_date = htmlentities(map_value('date')); // Send the email $url = get_site_url() . '/LMT/Registration/Signin?ID=' . $id . '&Code=' . $access_code; $subject = "LMT {$lmt_year} Account"; $body = <<<HEREDOC To: {$school_name} Thank you for registering your school for the LMT! The contest will be held on [b]{$lmt_date} [/b] at Lexington High School. You may register teams for LMT {$lmt_year} via the link below. This link will also enable you to modify teams as long as registration is open. [b][url]{$url} [/url][/b] If you have any questions, please contact us at [email]{$LMT_EMAIL} [/email]. HEREDOC; lmt_send_email(array($email => $school_name), $subject, $body); // Show the post-registration message echo <<<HEREDOC <h1>Coach Registration</h1> <div class="text-centered"> Your account was created. Please check your email inbox for a confirmation email. </div> HEREDOC; die; } } } }
function forms() { $data = $this->earndb->get_last_faktur(); print_r($data); //generate kode faktur baru --> generate_code_helper $faktur = generate_code($data); print_r($faktur); $this->load->view('earn_form_inside', array('faktur' => $faktur)); }
function lostPassword($username, $email) { $randomPassword = generate_code(10); if (changePassword($username, $randomPassword, $randomPassword)) { if (sendLostPasswordEmail($username, $email, $randomPassword)) { return true; } } return false; }
function GetID($prefix) { //第一步:初始化种子 //microtime(); 是个数组 /*$seedstr =split(" ",microtime(),5); $seed =$seedstr[0]*10000; //第二步:使用种子初始化随机数发生器 srand($seed); */ //第三步:生成指定范围内的随机数 $random = rand(1000, 10000); $random .= generate_code(); $filename = date("Ymd", time()) . $random . $prefix; return $filename; }
function chec_code($code) { $code = trim($code); //удаляем пробелы $array_mix = preg_split('//', generate_code(), -1, PREG_SPLIT_NO_EMPTY); $m_code = preg_split('//', $code, -1, PREG_SPLIT_NO_EMPTY); $result = array_intersect($array_mix, $m_code); if (strlen(generate_code()) != strlen($code)) { return FALSE; } if (sizeof($result) == sizeof($array_mix)) { return TRUE; } else { return FALSE; } }
function form() { $this->form_validation->set_rules('to_email', 'lang:recipient_email', 'trim|required'); $this->form_validation->set_rules('to_name', 'lang:recipient_name', 'trim|required'); $this->form_validation->set_rules('from', 'lang:sender_name', 'trim|required'); $this->form_validation->set_rules('personal_message', 'lang:personal_message', 'trim'); $this->form_validation->set_rules('beginning_amount', 'lang:amount', 'trim|required|numeric'); $data['page_title'] = lang('add_giftcard'); if ($this->form_validation->run() == FALSE) { $this->load->view($this->config->item('admin_folder') . '/giftcard_form', $data); } else { $this->load->helper('utility_helper'); $save['code'] = generate_code(); // from the utility helper $save['to_email'] = $this->input->post('to_email'); $save['to_name'] = $this->input->post('to_name'); $save['from'] = $this->input->post('from'); $save['personal_message'] = $this->input->post('personal_message'); $save['beginning_amount'] = $this->input->post('beginning_amount'); $save['activated'] = 1; $this->Gift_card_model->save_card($save); if ($this->input->post('send_notification')) { //get the canned message for gift cards $row = $this->db->where('id', '1')->get('canned_messages')->row_array(); // set replacement values for subject & body $row['subject'] = str_replace('{from}', $save['from'], $row['subject']); $row['subject'] = str_replace('{site_name}', $this->config->item('company_name'), $row['subject']); $row['content'] = str_replace('{code}', $save['code'], $row['content']); $row['content'] = str_replace('{amount}', $save['beginning_amount'], $row['content']); $row['content'] = str_replace('{from}', $save['from'], $row['content']); $row['content'] = str_replace('{personal_message}', nl2br($save['personal_message']), $row['content']); $row['content'] = str_replace('{url}', $this->config->item('base_url'), $row['content']); $row['content'] = str_replace('{site_name}', $this->config->item('company_name'), $row['content']); $this->load->library('email'); $config['mailtype'] = 'html'; $this->email->initialize($config); $this->email->from($this->config->item('email')); $this->email->to($save['to_email']); $this->email->subject($row['subject']); $this->email->message($row['content']); $this->email->send(); } $this->session->set_flashdata('message', lang('message_saved_giftcard')); redirect($this->config->item('admin_folder') . '/giftcards'); } }
function img_code() { header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", 10000) . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header("Content-Type:image/png"); //защита от кэшировани¤...кстати сказать не очень надежна¤... $linenum = 2; //линии $img_arr = array("codegen.png", "codegen0.png"); $font_arr = array(); $font_arr[0]["fname"] = "verdana.ttf"; //ttf шрифты, можно заменить на свои $font_arr[0]["size"] = 16; //размер $font_arr[1]["fname"] = "times.ttf"; //ttf шрифты, можно заменить на свои $font_arr[1]["size"] = 16; //размер $n = rand(0, sizeof($font_arr) - 1); $img_fn = $img_arr[rand(0, sizeof($img_arr) - 1)]; $im = imagecreatefrompng(code_dir . $img_fn); //создаем изображение со случайным фоном for ($i = 0; $i < $linenum; $i++) { //рисуем линии $color = imagecolorallocate($im, rand(0, 150), rand(0, 100), rand(0, 150)); imageline($im, rand(0, 20), rand(1, 50), rand(150, 180), rand(1, 50), $color); } $color = imagecolorallocate($im, rand(0, 200), 0, rand(0, 200)); imagettftext($im, $font_arr[$n]["size"], rand(-4, 4), rand(10, 45), rand(20, 35), $color, code_dir . $font_arr[$n]["fname"], generate_code()); //накладываем код for ($i = 0; $i < $linenum; $i++) { $color = imagecolorallocate($im, rand(0, 255), rand(0, 200), rand(0, 255)); imageline($im, rand(0, 20), rand(1, 50), rand(150, 180), rand(1, 50), $color); } ImagePNG($im); ImageDestroy($im); //ну вот и создано изображение! }
public function register() { $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean|is_unique[user.user_name]'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|is_unique[user.user_email]'); $this->form_validation->set_message('is_unique', 'The %s has been registered'); if ($this->form_validation->run()) { $code = generate_code(12); $name = $this->input->post('name'); $password = $this->input->post('password'); $email = $this->input->post('email'); $data = array('user_name' => $name, 'user_password' => enkripsi($password), 'user_email' => $email, 'user_status' => 'active', 'user_created_date' => now(), 'user_image' => 'default.jpg', 'user_registation_reff' => 'web'); $iduser = $this->model_user->store($data); $row = $this->model_user->find($iduser); set_userdata('session_user', $row); set_userdata('user_level', 'member'); $outs['msg'] = 'Registration success'; $outs['flag'] = 1; } else { $outs['msg'] = validation_errors(); $outs['flag'] = 0; } echo json_encode($outs); }
public function add_data() { // USE HTML PURIFIER // Build a nice little associative array for the data // Loop for each name to make sure multiple entries are dealt with. $warehouses = $this->input->post('name'); $i = 0; $data = array(); foreach ($warehouses as $warehouse) { $location2 = $this->input->post('location2'); $location1 = $this->input->post('location1'); $temp = array('name' => $warehouse, 'location1' => $location1[$i], 'location2' => $location2[$i]); $data[] = $temp; $i++; } // Validation $everythingGood = 1; // We believe in the good! foreach ($data as $datum) { $errors = $this->validate($datum); if ($errors === true) { // Check for redundancy. $there = $this->sharedDB_model->get('warehouse', array('id'), array('name' => $datum['name'])); if (count($there) > 0) { echo "<div class='alert alert-error fade in'>"; echo "<button type='button' class='close' data-dismiss='alert'>×</button><strong>Oh Snap! </strong>"; echo "The data you tried to enter already exist in the database."; echo "!</div>\n"; die; } // Everything is good! } else { // There are errors. Set the error flag $everythingGood = $everythingGood * 0; // Show error message/s foreach ($errors as $error) { echo "<div class='alert alert-error fade in'>"; echo "<button type='button' class='close' data-dismiss='alert'>×</button><strong>Oh Snap! </strong>"; echo $error; echo "!</div>\n"; } // Stop operation. break; } } // Check if everything is good and if it is, sanitize and filter everything. if ($everythingGood == 1) { // Filter rules $filterRules = array('name' => 'trim|sanitize_string', 'location1' => 'trim|sanitize_string', 'location2' => 'trim|sanitize_string'); // Sanitize and filter data. $sanitizedData = array(); foreach ($data as $datum) { $datum = $this->validation->sanitize($datum); $sanitizedData[] = $this->validation->filter($datum, $filterRules); } // Sanitization and all complete. Insert data into the database now. $dbGood = 1; foreach ($sanitizedData as $sanitizedDatum) { // Generate Code. $this->load->helper('generate_code'); $sanitizedDatum['code'] = generate_code($this->router->class); if ($this->sharedDB_model->insert('warehouse', $sanitizedDatum) == 1) { $dbGood = $dbGood * 1; } else { $dbGood = $dbGood * 0; } } // Check if all data has been inserted into the database and show success message! if ($dbGood == 1) { echo "<div class='alert alert-success fade in'>"; echo "<button type='button' class='close' data-dismiss='alert'>×</button><strong>Well Done! </strong>"; echo "All warehouse successfully inserted into the database!"; echo "!</div>\n"; } } }
function add_download_package($package, $order_id) { // get customer stuff $customer = $this->go_cart->customer(); if (!empty($customer['id'])) { $new_package['customer_id'] = $customer['id']; } else { $new_package['customer_id'] = 0; } $new_package['order_id'] = $order_id; $new_package['code'] = generate_code(); // save master package record $this->db->insert('download_packages', $new_package); $package_id = $this->db->insert_id(); // save the db data here $files_list = array(); // use this to prevent inserting duplicates // in case a file is shared across products $ids = array(); // build files records list foreach ($package as $product_list) { foreach ($product_list as $f) { if (!isset($ids[$f->file_id])) { $file['package_id'] = $package_id; $file['file_id'] = $f->file_id; $file['link'] = md5($f->file_id . time() . $new_package['customer_id']); // create a unique download key for each file $files_list[] = $file; } } } $this->db->insert_batch('download_package_files', $files_list); // save the master record to include links in the order email $this->go_cart->save_order_downloads($new_package); }
function process_form() { // INITIAL DATA FETCHING global $name, $email, $cell, $yog, $mailings; // so that the show_form function can use these values later $name = htmlentities(ucwords(trim(strtolower($_POST['name']), ' \\-\''))); foreach (array('-', '\'') as $delimiter) { if (strpos($name, $delimiter) !== false) { $name = implode($delimiter, array_map('ucfirst', explode($delimiter, $name))); } } // forces characters after spaces, hyphens and apostrophes to be capitalized $name = preg_replace('/[\\s\']*\\-+[\\s\']*/', '-', $name); // removes hyphens not between two characters $name = preg_replace('/[\\s\\-]*\'+[\\s\\-]*/', '\'', $name); // removes apostrophes not between two characters $name = preg_replace('/\\s+/', ' ', $name); // removes multiple consecutive spaces $name = preg_replace('/\\-+/', '-', $name); // removes multiple consecutive hyphens $name = preg_replace('/\'+/', '\'', $name); // removes multiple consecutive apostrophes $email = htmlentities(strtolower($_POST['email'])); $cell = htmlentities($_POST['cell']); $yog = $_POST['yog']; $pass = $_POST['pass1']; $mailings = '0'; if ($_POST['mailings'] == 'Yes') { $mailings = '1'; } // CHECK THAT THE NAME IS VALID if (($name = sanitize_username($name)) === false) { alert('Your name must have only letters, hyphens, apostrophes, and spaces, and be between 3 and 30 characters long', -1); show_form(); return; } if (strpos($name, ' ') == false) { alert('Please enter both your first <span class="i">and</span> last name', -1); show_form(); return; } // CHECK THAT THE EMAIL ADDRESS IS VALID if (!val('e', $email)) { alert('That\'s not a valid email address', -1); show_form(); return; } // CHECK AND FORMAT CELL PHONE NUMBER if ($cell != '' && ($cell = format_phone_number($cell)) === false) { //Validate the format of the cell phone number (if it's not left blank) alert('That\'s not a valid cell phone number', -1); show_form(); return; } // CHECK THAT THE YOG IS VALID $grade = intval(getGradeFromYOG($yog)); if ($grade < 9 || $grade > 12) { alert('That is not a valid YOG (' . $grade . 'you have to be in high school)', -1); show_form(); return; } // CHECK THAT THE PASSWORDS MATCH, MEET MINIMUM LENGTH if ($pass != $_POST['pass2']) { alert('The passwords that you entered do not match', -1); show_form(); return; } if (strlen($pass) < 6) { alert('Please choose a password that has at least 6 characters', -1); show_form(); return; } // CHECK THAT THEY ENTERED THE RECAPTCHA CORRECTLY // CURRENTLY BROKEN: NEED TO UPDATE RECAPTCHA /* $recaptcha_msg = validate_recaptcha(); if ($recaptcha_msg !== true) { alert($recaptcha_msg, -1); show_form(); return; } */ // CHECK THAT AN ACCOUNT WITH THAT EMAIL DOES NOT ALREADY EXIST // this is done *after* checking the reCaptcha to prevent bots from harvesting our email // addresses via a brute-force attack. if (DBExt::queryCount('users', 'LOWER(email)=LOWER(%s)', $email) != 0) { alert('An account with that email address already exists', -1); show_form(); return; } // CHECK THAT AN ACCOUNT WITH THE SAME NAME IN THE SAME GRADE DOES NOT EXIST // - with the exception that if it's permissions = 'E', they probably mistyped their email and are redoing it. if (DBExt::queryCount('users', 'LOWER(name)=%s AND yog=%i AND permissions!="E"', strtolower($name), $yog) != 0) { alert('An account in your grade with that name already exists', -1); show_form(); return; } // ** All information has been validated at this point ** $verification_code = generate_code(5); // for verifying ownership of the email address // Check if email address has been pre-approved if (isset($_SESSION['PREAPPROVED']) && $email === $_SESSION['PREAPPROVED']) { $approved = '1'; // skip Captain approval $verification_code = '1'; // skip email verification (already done) } else { $approved = '0'; } // Create database entry $passhash = hash_pass($email, $pass); if ($cell == '') { $cell = 'None'; } else { $cell = preg_replace('#[^\\d]#', '', $_POST['cell']); } // remove non-numbers from cell phone # again DB::insert('users', array('name' => $name, 'email' => $email, 'passhash' => $passhash, 'cell' => $cell, 'yog' => $yog, 'mailings' => $mailings, 'approved' => $approved, 'email_verification' => $verification_code, 'registration_ip' => htmlentities(strtolower($_SERVER['REMOTE_ADDR'])))); set_login_data(DB::insertId()); // LOG THEM IN // For pre-approved members: if ($approved == '1') { global $WEBMASTER_EMAIL; $to = array($email => $name); $subject = 'Account Created'; $body = <<<HEREDOC Welcome to the LHS Math Club website, {$name}! Your account has been created. If you have any questions about the site, please email the webmaster at {$WEBMASTER_EMAIL} HEREDOC; send_email($to, $subject, $body, $WEBMASTER_EMAIL); $_SESSION['HOME_welcome'] = 'Welcome to the LHS Math Club website, ' . $name . '!'; header('Location: Home'); } $_SESSION['ACCOUNT_do_send_verification_email'] = true; header('Location: Verify_Email'); }
function vip_card_no($num = 4) { return date('ymdHis') . generate_code($num); }
/** * Задает код для восстановления пароля пользователя * @param - id пользователя * @return string * */ function set_user_recovery_code($user_id) { $this->load->helper('safety'); $code = generate_code(20); $this->update_user(array('recovery_code' => $code), $user_id); return $code; }
$data['if']['captcha'] = 1; $data['captcha']['img'] = cs_html_img('mods/captcha/generate.php?time=' . cs_time()); } } if (empty($op_users['def_register']) or $op_users['def_register'] == '2') { if ($op_users['def_register'] != '2') { $data['if']['reg_mail'] = 1; } else { $data['if']['reg_mail'] = 0; } echo cs_subtemplate(__FILE__, $data, 'users', 'register_code'); } else { echo cs_subtemplate(__FILE__, $data, 'users', 'register_mail'); } } else { $code_id = generate_code(30); // 30 Zeichen lang $register['users_key'] = $code_id; $active = empty($op_users['def_register']) ? $register['users_active'] = 1 : ($register['users_active'] = 0); $def_timezone = empty($cs_main['def_timezone']) ? 0 : $cs_main['def_timezone']; $def_dstime = empty($cs_main['def_dstime']) ? 0 : $cs_main['def_dstime']; create_user(2, $register['nick'], $register['password'], $register['lang'], $register['email'], 'fam', $def_timezone, $def_dstime, $register['newsletter'], $active, 20, $register['users_key']); $ip = cs_getip(); if (!empty($register['send_mail']) or !empty($op_users['def_register']) or $op_users['def_register'] == '2') { $content = $cs_lang['mail_reg_start'] . $cs_lang['mail_reg_nick'] . $register['nick']; $content .= $cs_lang['mail_reg_password'] . $register['password']; $content .= $cs_lang['mail_reg_ip'] . $ip; if (!empty($op_users['def_register'])) { $content .= "\n" . $cs_lang['mail_key'] . ': '; $content .= $cs_main['php_self']['website'] . str_replace('&', '&', cs_url('users', 'activate', 'key=' . $register['users_key'] . '&email=' . $register['email'])); }
function giftcard() { if (!$this->gift_cards_enabled) { redirect('/'); } // Load giftcard settings $gc_settings = $this->Settings_model->get_settings("gift_cards"); $this->load->library('form_validation'); $data['allow_custom_amount'] = (bool) $gc_settings['allow_custom_amount']; $data['preset_values'] = explode(",", $gc_settings['predefined_card_amounts']); if ($data['allow_custom_amount']) { $this->form_validation->set_rules('custom_amount', 'lang:custom_amount', 'numeric'); } $this->form_validation->set_rules('amount', 'lang:amount', 'required'); $this->form_validation->set_rules('preset_amount', 'lang:preset_amount', 'numeric'); $this->form_validation->set_rules('gc_to_name', 'lang:recipient_name', 'trim|required'); $this->form_validation->set_rules('gc_to_email', 'lang:recipient_email', 'trim|required|valid_email'); $this->form_validation->set_rules('gc_from', 'lang:sender_email', 'trim|required'); $this->form_validation->set_rules('message', 'lang:custom_greeting', 'trim|required'); if ($this->form_validation->run() == FALSE) { $data['error'] = validation_errors(); $data['page_title'] = lang('giftcard'); $data['gift_cards_enabled'] = $this->gift_cards_enabled; $this->load->view('giftcards', $data); } else { // add to cart $card['price'] = set_value(set_value('amount')); $card['id'] = -1; // just a placeholder $card['sku'] = lang('giftcard'); $card['base_price'] = $card['price']; // price gets modified by options, show the baseline still... $card['name'] = lang('giftcard'); $card['code'] = generate_code(); // from the string helper $card['excerpt'] = sprintf(lang('giftcard_excerpt'), set_value('gc_to_name')); $card['weight'] = 0; $card['quantity'] = 1; $card['shippable'] = false; $card['taxable'] = 0; $card['fixed_quantity'] = true; $card['is_gc'] = true; // !Important $card['track_stock'] = false; // !Imporortant $card['gc_info'] = array("to_name" => set_value('gc_to_name'), "to_email" => set_value('gc_to_email'), "from" => set_value('gc_from'), "personal_message" => set_value('message')); // add the card data like a product $this->go_cart->insert($card); redirect('cart/view_cart'); } }
function submitOrder($transaction = false) { foreach ($this->items as $item) { if ($item->type == 'gift card') { //touch giftcard \CI::GiftCards()->updateAmountUsed($item->description, $item->total_price); continue; } elseif ($item->type == 'coupon') { //touch coupon \CI::Coupons()->touchCoupon($item->description); continue; } elseif ($item->type == 'product') { //update inventory if ($item->track_stock) { \CI::Products()->touchInventory($item->product_id, $item->quantity); } //if this is a giftcard purchase, generate it and send it where it needs to go. if ($item->is_giftcard) { //process giftcard $options = CI::Orders()->getItemOptions(GC::getCart()->id); $giftCard = []; foreach ($options[$item->id] as $option) { if ($option->option_name == 'gift_card_amount') { $giftCard[$option->option_name] = $option->price; } else { $giftCard[$option->option_name] = $option->value; } } $giftCard['code'] = generate_code(); $giftCard['activated'] = 1; //save the card \CI::GiftCards()->saveCard($giftCard); //send the gift card notification \GoCart\Emails::giftCardNotification($giftCard); } } } if (!$transaction) { $transaction = $this->transaction(); } //add transaction info to the order $this->cart->order_number = $transaction->order_number; $this->cart->transaction_id = $transaction->id; $this->cart->status = config_item('order_status'); $this->cart->ordered_on = date('Y-m-d H:i:s'); $orderNumber = $this->cart->order_number; $this->saveCart(); //refresh the cart $this->getCart(true); //get the order as it would be on the order complete page $order = \CI::Orders()->getOrder($orderNumber); //send the cart email \GoCart\Emails::Order($order); //return the order number return $orderNumber; }
/** * 验证码 * * @author Garbin * @return void */ function _captcha($width, $height) { import('captcha.lib'); $word = generate_code(); $_SESSION['captcha'] = base64_encode($word); $code = new Captcha(array('width' => $width, 'height' => $height)); $code->display($word); }
<?php include '../includes/config.php'; if (isset($_POST) && isset($_SESSION)) { $file = rawurldecode($_POST['uploadID']); if (isset($_SESSION[$file]) && $_SESSION[$file] == $file) { $file_db = $db->select('uploads', "url=? LIMIT 1", array($file)); if ($file_db) { $delete_key = generate_code($file_db['url'], $CONF); $data = array("delete_key" => $delete_key); $post_id = $db->update($data, 'uploads', 'url=?', array($file)); unset($_POST); echo json_encode(array('result' => array('url' => get_page_url("u", $CONF) . '/' . $file_db['url'] . '/' . $delete_key))); } else { echo json_encode(array('error' => $CONF['errors']['NoFile'])); } } else { echo json_encode(array('error' => $CONF['errors']['InvRequest'])); } } else { echo json_encode(array('error' => $CONF['errors']['InvRequest'])); }
public function promo_code_insert_merchant($code_user_id) { $query = $this->db->get_where('promo_code', array('code_type' => 'merchant', 'code_user_id' => $code_user_id), 1); if ($query->num_rows() == 0) { $user_info = $this->m_custom->getMerchantInfo($code_user_id); $code_candie = $this->m_custom->web_setting_get('merchant_promo_code_get_candie'); $name = substr(generate_code($user_info['slug']), 0, 5); $postfix = str_pad($code_user_id, 4, '0', STR_PAD_LEFT); $code_no = '5' . $name . $postfix; $new_id = $this->m_custom->promo_code_insert($code_no, 'merchant', $code_user_id, $code_candie); if ($new_id) { return $new_id; } } return FALSE; }
/** * recoverPassword * * @param mixed $email Email * @param mixed $requestID Request ID * * @return boolean */ protected function doPasswordRecovery($email, $requestID) { $result = false; $profile = \XLite\Core\Database::getRepo('XLite\\Model\\Profile')->findByLogin($email); if (!isset($profile) || !$profile->isAdmin()) { \XLite\Core\TopMessage::addError('There is no user with specified email address'); } elseif ($profile->getPasswordResetKey() != $requestID || \XLite\Core\Converter::time() > $profile->getPasswordResetKeyDate()) { \XLite\Core\TopMessage::addError('Your "Password reset key" has expired. Please enter the email address associated with your user account to get a new "Password reset key".'); $profile->setPasswordResetKey(''); $profile->setPasswordResetKeyDate(0); $profile->update(); } else { $pass = generate_code(); $profile->setPassword(md5($pass)); $profile->setForceChangePassword(true); $profile->setPasswordResetKey(''); $profile->setPasswordResetKeyDate(0); $result = $profile->update(); if ($result) { \XLite\Core\Auth::getInstance()->loginProfile($profile); } } return $result; }
function new_po() { $lastpo = $this->belidb->get_last_po(); $this->template->add_js('var baseurl="' . base_url() . 'beli/";', 'embed'); $this->template->load_view('beli_wrapper_view', array('newpo' => generate_code($lastpo), 'forms' => 'beli_form_ajax', 'title' => 'Order Pembelian / Purchase Order (PO)')); }
/** * Установка/обновление игрового сервера. Общая функция. */ private function _install_server($server_id = 0, $update_server = false) { if (!$server_id) { return; } $this->_cmd_output("--Server #" . $server_id . " install started"); $server_installed = false; $stop_install = false; // Данные лога установки $log = ''; $this->_install_result = ''; $this->control->clear_commands(); /* Получение данных об игровой модификации */ //~ $this->game_types->get_gametypes_list(array('id' => $this->servers_data[$server_id]['game_type'])); /* Получение данных об игре */ $this->games->get_games_list(array('code' => $this->servers_data[$server_id]['game'])); if ($this->games->games_list[0]['code'] != $this->servers_data[$server_id]['game']) { $this->_cmd_output('---Game code not doesn\'t match'); $stop_install = false; } // Полю installed устанавливаем значение 2, что сервер начал устанавливаться $this->servers->edit_game_server($server_id, array('installed' => '2')); /* Создание директории на выделенном сервере */ try { $this->_mkdir($server_id); } catch (Exception $e) { $this->_cmd_output('---Mkdir failed: ' . $e->getMessage()); $stop_install = false; } if (!$stop_install) { /* Операция установки игрового сервера * В зависимости от заданных данных сервер устанавливается * из локального репозитория, либо удаленного репозитория, либо * через SteamCMD. * * Наибольший приоритет имеет локальный репозиторий, после * удаленный, а после SteamCMD. */ if ($this->games->games_list[0]['local_repository']) { /* Установка из локального репозитория */ $rep_info = pathinfo($this->games->games_list[0]['local_repository']); $this->_cmd_output("---Install from local repository"); try { if (isset($rep_info['extension'])) { // Распаковка архива $this->_wget_files($server_id, $this->games->games_list[0]['local_repository'], 'local'); $this->_unpack_files($server_id, $this->games->games_list[0]['local_repository']); } else { // Копирование директории $this->_copy_files($server_id, $this->games->games_list[0]['local_repository']); } $server_installed = true; } catch (Exception $e) { $this->_cmd_output("---Install from local repository failed. Message: " . $e->getMessage()); $server_installed = false; } } elseif ($this->games->games_list[0]['remote_repository']) { /* Установка из удаленного репозитория */ $this->_cmd_output("---Install from remote repository"); try { $this->_wget_files($server_id, $this->games->games_list[0]['remote_repository'], 'remote'); $this->_unpack_files($server_id, $this->games->games_list[0]['remote_repository']); $server_installed = true; } catch (Exception $e) { $this->_cmd_output("---Install from remote repository failed. Message: " . $e->getMessage()); $server_installed = false; } } elseif ($this->games->games_list[0]['app_id']) { /* Установка через SteamCMD */ $this->_cmd_output("---Install from SteamCMD"); try { $server_installed = $this->_install_from_steamcmd($server_id); } catch (Exception $e) { $this->_cmd_output("---Install from steamcmd failed. Message: " . $e->getMessage()); $server_installed = false; } } else { /* * Не удалость выбрать тип установки * отсутствуют данные локального репозитория, удаленного репозитория и steamcmd */ $log .= "App_id and Repository data not specified \n"; $this->_cmd_output("---Server #" . $server_id . " install failed. App_id and Repository data not specified"); $server_installed = false; } } /* * Завершение установки. * Установка прав на директории, задание ркон пароля */ if ($server_installed == true) { /* Загружаем дополнительный файлы игровой модификации */ $this->game_types->get_gametypes_list(array('id' => $this->servers_data[$server_id]['game_type'])); if (isset($this->game_types->game_types_list[0]['local_repository']) && $this->game_types->game_types_list[0]['local_repository']) { try { $this->_wget_files($server_id, $this->game_types->game_types_list[0]['local_repository'], 'local'); $this->_unpack_files($server_id, $this->game_types->game_types_list[0]['local_repository']); } catch (Exception $e) { $this->_cmd_output('---Install modification from local repository failed. Message: ' . $e->getMessage()); } } elseif (isset($this->game_types->game_types_list[0]['remote_repository']) && $this->game_types->game_types_list[0]['remote_repository']) { try { $this->_wget_files($server_id, $this->game_types->game_types_list[0]['remote_repository'], 'remote'); $this->_unpack_files($server_id, $this->game_types->game_types_list[0]['remote_repository']); } catch (Exception $e) { $this->_cmd_output('---Install modification from remote repository failed. Message: ' . $e->getMessage()); } } /* Устанавливаем 777 права на директории, в которые загружается контент (карты, модели и пр.) * и 666 на конфиг файлы, которые можно редактировать через админпанель */ $this->_cmd_output('---Change privileges'); if (strtolower($this->servers_data[$server_id]['os']) != 'windows') { if ($this->servers_data[$server_id]['su_user'] != '') { $command[] = 'chown -R ' . $this->servers_data[$server_id]['su_user'] . ' ' . $this->servers_data[$server_id]['script_path'] . '/' . $this->servers_data[$server_id]['dir']; $log .= 'chown -R ' . $this->servers_data[$server_id]['su_user'] . ' ' . $this->servers_data[$server_id]['script_path'] . '/' . $this->servers_data[$server_id]['dir'] . "\n"; } if (isset($command) && !empty($command)) { try { $log .= "\n---\nCHMOD\n" . $log . "\n" . send_command($command, $this->servers_data[$server_id]); } catch (Exception $e) { $this->_cmd_output('---CHMOD failed. Message: ' . $e->getMessage()); $log .= $e->getMessage() . "\n"; } } } /* Устанавливаем серверу rcon пароль */ if (!$update_server) { $this->_cmd_output('---Set rcon password'); $this->load->helper('safety'); $new_rcon = generate_code(8); try { $this->servers->change_rcon($new_rcon, $this->servers_data[$server_id]); } catch (Exception $e) { $this->_cmd_output('---Rcon set failed. Message: ' . $e->getMessage()); } /* Конфигурирование сервера * Здесь задаются параметры запуска и различные базовые настройки */ $this->_cmd_output('----Configuring server'); $this->installer->set_game_variables($this->servers_data[$server_id]['start_code'], $this->servers_data[$server_id]['engine'], $this->servers_data[$server_id]['engine_version']); $this->installer->set_os($this->servers_data[$server_id]['os']); $this->installer->server_data = $this->servers_data[$server_id]; /* Правка конфигов. Здесь происходит редактирование параметров * в конфигурации. * Для некоторых игр такие параметры как порт, IP, RCON пароль * задаются в конфигах. */ try { $this->installer->change_config(); } catch (Exception $e) { $this->_cmd_output('---Change config failed. Message: ' . $e->getMessage()); } $this->_cmd_output('----Set aliases'); $aliases_values = array(); $aliases_values = $this->servers_data[$server_id]['aliases']; $server_data['rcon'] = $new_rcon; $server_data['aliases'] = json_encode($this->installer->get_default_parameters($aliases_values)); if (!$this->servers_data[$server_id]['start_command']) { $server_data['start_command'] = $this->installer->get_start_command(); } // Путь к картам $server_data['maps_path'] = $this->installer->get_maps_path(); // Список портов $ports = $this->installer->get_ports(); $server_data['query_port'] = $ports[1]; $server_data['rcon_port'] = $ports[2]; unset($ports); // Прочие данные $this->installer->change_server_data($server_data); } $server_data['installed'] = 1; $this->servers->edit_game_server($server_id, $server_data); $log_data['type'] = 'server_command'; $log_data['command'] = 'install'; $log_data['server_id'] = $server_id; $log_data['msg'] = 'Server install successful'; $log_data['log_data'] = "Results:" . PHP_EOL . var_export($this->control->get_commands_result(), true) . PHP_EOL; $this->panel_log->save_log($log_data); $this->_cmd_output('---Server install #' . $server_id . ' success'); } else { $server_data = array('installed' => '0'); $this->servers->edit_game_server($server_id, $server_data); $log_data['type'] = 'server_command'; $log_data['command'] = 'install'; $log_data['server_id'] = $server_id; $log_data['msg'] = 'Server install failed'; $log_data['log_data'] = "Results:" . PHP_EOL . var_export($this->control->get_commands_result(), true) . PHP_EOL; $this->panel_log->save_log($log_data); $this->_cmd_output('---Server install #' . $server_id . ' failed'); } }
public function add_data() { // USE HTML PURIFIER // Load the shared DB helper to insert the data into the database. $this->load->model('sharedDB_model'); // Build a nice little associative array for the data // Loop for each name to make sure multiple entries are dealt with. $names = $this->input->post('name'); $i = 0; $data = array(); foreach ($names as $name) { $reg_number = $this->input->post('reg_number'); $alternate_id = $this->input->post('alternate_id'); $grade_level = $this->input->post('grade_level'); $type = $this->input->post('type'); $temp = array('name' => $name, 'reg_number' => $reg_number[$i], 'alternate_id' => $alternate_id[$i], 'type' => $type[$i], 'grade_level' => $grade_level[$i]); // If customer type isn't student, mark grade level id as 0. // Get ID of customer type = student first. $customerTypeID = $this->sharedDB_model->get('customer_type', array('id'), array('name' => 'Student')); $customerTypeID = $customerTypeID[0]['id']; if ($temp['type'] != $customerTypeID) { $temp['grade_level'] = 0; } $data[] = $temp; $i++; } // Validation $everythingGood = 1; // We believe in the good! foreach ($data as $datum) { $errors = $this->validate($datum); if ($errors === true) { // Check for redundancy. $there = $this->sharedDB_model->get('customers', array('id'), array('name' => $datum['name'], 'reg_number' => $datum['reg_number'], 'type' => $datum['type'])); if (count($there) > 0) { echo "<div class='alert alert-error fade in'>"; echo "<button type='button' class='close' data-dismiss='alert'>×</button><strong>Oh Snap! </strong>"; echo "The data you tried to enter already exist in the database."; echo "!</div>\n"; die; } // Everything is good! break; } else { // There are errors. Set the error flag $everythingGood = $everythingGood * 0; // Show error message/s foreach ($errors as $error) { echo "<div class='alert alert-error fade in'>"; echo "<button type='button' class='close' data-dismiss='alert'>×</button><strong>Oh Snap! </strong>"; echo $error; echo "!</div>\n"; } // Stop operation. break; } } // Check if everything is good and if it is, sanitize and filter everything. if ($everythingGood == 1) { // Filter rules $filterRules = array('name' => 'trim|sanitize_string', 'reg_number' => 'trim|sanitize_string', 'alternate_id' => 'trim|sanitize_string', 'type' => 'trim|sanitize_numbers', 'grade_level' => 'trim|sanitize_numbers'); // Sanitize and filter data. $sanitizedData = array(); foreach ($data as $datum) { $datum = $this->validation->sanitize($datum); $sanitizedData[] = $this->validation->filter($datum, $filterRules); } // Sanitization and all complete. Insert data into the database now. $dbGood = 1; foreach ($sanitizedData as $sanitizedDatum) { // Generate Code. $this->load->helper('generate_code'); $sanitizedDatum['code'] = generate_code($this->router->class); if ($this->sharedDB_model->insert('customers', $sanitizedDatum) == 1) { $dbGood = $dbGood * 1; } else { $dbGood = $dbGood * 0; } } // Check if all data has been inserted into the database and show success message! if ($dbGood == 1) { echo "<div class='alert alert-success fade in'>"; echo "<button type='button' class='close' data-dismiss='alert'>×</button><strong>Well Done! </strong>"; echo "All customer/s successfully inserted into the database!"; echo "!</div>\n"; } } }
public function add_transaction() { $data = $this->input->post('invoice'); $customerID = $data['customer']; $stock = $data['inventory']; $invoice = array(); // GET PAYMENT TYPE AS WELL // VALIDATE. AND SANITIZE // VALIDATE. AND SANITIZE $customerDetails = $this->sharedDB_model->get('customers', array('id', 'code', 'reg_number', 'alternate_id', 'name', 'type'), array('id' => $customerID)); $customerDetails = $customerDetails[0]; $invoice['customer'] = $customerDetails; $invoice['customer']['type'] = $this->sharedDB_model->get('customer_type', array('name'), array('id' => $invoice['customer']['type'])); $invoice['customer']['type'] = $invoice['customer']['type'][0]['name']; $invoice['inventory'] = array(); $i = 0; foreach ($stock as $sto) { /* * So we have an array called $sto which contains two things: * 1) Stock ID. * 2) Quantity * * Let me be clear. It's stock ID and not inventory ID. * * First we need to find stock code, CP, SP, quantity, warehouse and supplier. * Then, the corresponding inventory ID, code and name. * */ $invoice['inventory'][$i] = $this->sharedDB_model->get('stock', array('id', 'code', 'inventory_id', 'cp', 'sp', 'warehouse', 'supplier'), array('id' => $sto['id'])); $invoice['inventory'][$i] = $invoice['inventory'][$i][0]; $dummy = $this->sharedDB_model->get('inventory', array('code', 'name'), array('id' => $invoice['inventory'][$i]['inventory_id'])); $dummy = $dummy[0]; $invoice['inventory'][$i]['quantity'] = $sto['quantity']; $invoice['inventory'][$i]['name'] = $dummy['name']; $invoice['inventory'][$i]['inventory_code'] = $dummy['code']; // Warehouse $invoice['inventory'][$i]['warehouse'] = $this->sharedDB_model->get('warehouse', array('id', 'code', 'name', 'location1', 'location2'), array('id' => $invoice['inventory'][$i]['warehouse'])); $invoice['inventory'][$i]['warehouse'] = $invoice['inventory'][$i]['warehouse'][0]; // Supplier $invoice['inventory'][$i]['supplier'] = $this->sharedDB_model->get('suppliers', array('id', 'code', 'name', 'address1', 'address2', 'phone1', 'phone2', 'phone3', 'email', 'website'), array('id' => $invoice['inventory'][$i]['supplier'])); $invoice['inventory'][$i]['supplier'] = $invoice['inventory'][$i]['supplier'][0]; $i++; } $sanitizedDatum = array(); $sanitizedDatum['invoice'] = json_encode($invoice); $sanitizedDatum['customer'] = $invoice['customer']['id']; // Generate Code. $this->load->helper('generate_code'); $sanitizedDatum['code'] = generate_code($this->router->class); if ($this->sharedDB_model->insert('invoices', $sanitizedDatum) == 1) { // Also decrease the stock quantity by the quantity set to the corresponding inventory. // Not done above to make sure data has actually been inserted into the database. foreach ($invoice['inventory'] as $invent) { // Correct this $currentStock = $this->sharedDB_model->get('stock', array('quantity'), array('id' => $invent['id'])); $currentStock = $currentStock[0]['quantity']; $newStock = $currentStock - $invent['quantity']; $this->sharedDB_model->update('stock', array('quantity' => $newStock), array('id' => $invent['id'])); } echo '1'; // Confirmition message sent to the view so that it can clear all fields on screen. } }
function lostPassword($username, $email) { global $seed; if (!valid_username($username) || !user_exists($username) || !valid_email($email)) { return false; } $query = sprintf("select loginid from login where username = '******' and email = '%s' limit 1", $username, $email); $result = mysql_query($query); if (mysql_num_rows($result) != 1) { return false; } $newpass = generate_code(8); $query = sprintf("update login set password = '******' where username = '******'", mysql_real_escape_string(sha1($newpass . $seed)), mysql_real_escape_string($username)); if (mysql_query($query)) { if (sendLostPasswordEmail($username, $email, $newpass)) { return true; } else { return false; } } else { return false; } return false; }
$messsage_erreur_code = ''; $affichage_recup = 'none'; $affichage = 'normal'; if (isset($_GET['c']) and $_GET['c'] != '') { //récupération du cadeau //Vérification du mot de passe $QrySelect = 'SELECT id, nom, email, used FROM ProfilsNoel where pass =\'' . mysql_real_escape_string(addslashes(strtoupper($_GET['c'])), $link_mysql) . '\''; $QrySelectRes = mysql_query($QrySelect, $link_mysql); if (mysql_num_rows($QrySelectRes) == 1) { $RowSelect = mysql_fetch_assoc($QrySelectRes); $id = stripslashes($RowSelect['id']); $nom = stripslashes($RowSelect['nom']); $email = stripslashes($RowSelect['email']); if ($RowSelect['used'] == '1') { //Le code a déjà été utilisé, on en regénère un nouveau qu'on envoi par mail et on en informe la personne $pass = generate_code($link_mysql); //On marque le code comme utilisé $QryUsed = 'UPDATE ProfilsNoel SET pass = \'' . $pass . '\', used = 0 WHERE id = \'' . $RowSelect['id'] . '\''; mysql_query($QryUsed, $link_mysql); envoi_mail_code($email, $nom, $pass); $messsage_erreur .= 'Ce code a déjà été utilisé, c\'est triste.<br> Mais heureusement tu vas en recevoir un nouveau par email dans quelques minutes. C\'est cool, hein ? <br> <p>Ton code personnel a été envoyé par mail à <strong>' . $email . '</strong>.</p>'; $affichage = 'normal'; } else { //récupération du profil $QryProfil = 'SELECT id, nom, genre, commentaire FROM ProfilsNoel WHERE id_profil_recoit = \'' . $RowSelect['id'] . '\''; $QryProfilRes = mysql_query($QryProfil, $link_mysql); $RowProfil = mysql_fetch_assoc($QryProfilRes); $id_gagnant = $RowProfil['id'];