Exemple #1
0
 public function download_files_as_zip($idlist = array())
 {
     $zip = new ZipArchive();
     $randomid = generate_random_string(16);
     $filename = DIR_BASE . "tmp/" . $randomid;
     if ($zip->open($filename, ZIPARCHIVE::CREATE) != true) {
         exit("cannot open <{$filename}>\n");
     }
     $this->model_search_message->connect_to_pilergetd();
     foreach ($idlist as $id) {
         $piler_id = $this->model_search_message->get_piler_id_by_id($id);
         $rawemail = $this->model_search_message->get_raw_message($piler_id);
         $zip->addFromString($piler_id . ".eml", $rawemail);
         AUDIT(ACTION_DOWNLOAD_MESSAGE, '', '', $id, '');
     }
     $this->model_search_message->disconnect_from_pilergetd();
     $zip->close();
     header("Cache-Control: public, must-revalidate");
     header("Pragma: no-cache");
     header("Content-Type: application/zip");
     header("Expires: 0");
     header("Content-Length: " . filesize($filename));
     header("Content-Disposition: attachment; filename=archive-{$randomid}.zip");
     header("Content-Transfer-Encoding: binary\n");
     readfile($filename);
     unlink($filename);
 }
Exemple #2
0
 public function check_for_account($google_account = array())
 {
     $session = Registry::get('session');
     $query = $this->db->query("SELECT " . TABLE_USER . ".username, " . TABLE_USER . ".uid, " . TABLE_USER . ".realname, " . TABLE_USER . ".dn, " . TABLE_USER . ".password, " . TABLE_USER . ".isadmin, " . TABLE_USER . ".domain FROM " . TABLE_USER . ", " . TABLE_EMAIL . " WHERE " . TABLE_EMAIL . ".email=? AND " . TABLE_EMAIL . ".uid=" . TABLE_USER . ".uid", array($google_account['email']));
     if ($query->num_rows == 1) {
         $user = $query->row;
     } else {
         $d = explode('@', $google_account['email']);
         $user['uid'] = $this->model_user_user->get_next_uid();
         $user['username'] = $google_account['email'];
         $user['realname'] = $google_account['name'];
         $user['email'] = $google_account['email'];
         $user['domain'] = $d[1];
         $user['dn'] = '*';
         $user['isadmin'] = 0;
         $user['password'] = generate_random_string(12);
         $user['group'] = '';
         $user['folder'] = '';
         $this->model_user_user->add_user($user);
         $this->model_domain_domain->addDomain($user['domain'], $user['domain']);
     }
     $session->set("username", $user['username']);
     $session->set("uid", $user['uid']);
     $session->set("admin_user", 0);
     $session->set("email", $user['username']);
     $session->set("domain", $query->row['domain']);
     $session->set("realname", $query->row['realname']);
     $session->set("emails", $this->model_user_user->get_users_all_email_addresses($user['uid']));
     $session->set("folders", $this->model_folder_folder->get_all_folder_ids($user['uid']));
     $session->set("extra_folders", $this->model_folder_folder->get_all_extra_folder_ids($user['uid']));
     AUDIT(ACTION_LOGIN, $user['username'], '', '', 'successful auth against Google');
 }
Exemple #3
0
function store_file($challenge_id, $file)
{
    if ($file['error']) {
        message_error('Could not upload file: ' . file_upload_error_description($file['error']));
    }
    if ($file['size'] > max_file_upload_size()) {
        message_error('File too large.');
    }
    $file_id = db_insert('files', array('added' => time(), 'added_by' => $_SESSION['id'], 'title' => $file['name'], 'size' => $file['size'], 'md5' => md5_file($file['tmp_name']), 'download_key' => hash('sha256', generate_random_string(128)), 'challenge' => $challenge_id));
    if (file_exists(CONST_PATH_FILE_UPLOAD . $file_id)) {
        message_error('File already existed! This should never happen!');
    }
    // do we put the file on AWS S3?
    if (CONFIG_AWS_S3_KEY_ID && CONFIG_AWS_S3_SECRET && CONFIG_AWS_S3_BUCKET) {
        try {
            // Instantiate the S3 client with your AWS credentials
            $client = S3Client::factory(array('key' => CONFIG_AWS_S3_KEY_ID, 'secret' => CONFIG_AWS_S3_SECRET));
            $file_key = '/challenges/' . $file_id;
            // Upload an object by streaming the contents of a file
            $result = $client->putObject(array('Bucket' => CONFIG_AWS_S3_BUCKET, 'Key' => $file_key, 'SourceFile' => $file['tmp_name']));
            // We can poll the object until it is accessible
            $client->waitUntil('ObjectExists', array('Bucket' => CONFIG_AWS_S3_BUCKET, 'Key' => $file_key));
        } catch (Exception $e) {
            delete_file($file_id);
            message_error('Caught exception uploading file to S3: ' . $e->getMessage());
        }
    } else {
        move_uploaded_file($file['tmp_name'], CONST_PATH_FILE_UPLOAD . $file_id);
        if (!file_exists(CONST_PATH_FILE_UPLOAD . $file_id)) {
            delete_file($file_id);
            message_error('File upload failed!');
        }
    }
}
Exemple #4
0
 public function download_attachments_as_zip($piler_id = '')
 {
     $zip = new ZipArchive();
     $pid = array();
     $randomid = generate_random_string(16);
     $filename = DIR_BASE . "tmp/" . $randomid;
     if ($zip->open($filename, ZIPARCHIVE::CREATE) != true) {
         exit("cannot open <{$filename}>\n");
     }
     $attachments = $this->model_search_message->get_attachment_list($piler_id);
     foreach ($attachments as $a) {
         $attachment = $this->model_search_message->get_attachment_by_id($a['id']);
         $fp = fopen(DIR_BASE . 'tmp/' . $a['id'], "w+");
         if ($fp) {
             fwrite($fp, $attachment['attachment']);
             fclose($fp);
             $zip->addFile(DIR_BASE . 'tmp/' . $a['id'], $attachment['filename']);
         }
     }
     $zip->close();
     foreach ($attachments as $a) {
         unlink(DIR_BASE . 'tmp/' . $a['id']);
     }
     header("Cache-Control: public, must-revalidate");
     header("Pragma: no-cache");
     header("Content-Type: application/zip");
     header("Expires: 0");
     header("Content-Length: " . filesize($filename));
     header("Content-Disposition: attachment; filename=" . $piler_id . ".zip");
     header("Content-Transfer-Encoding: binary\n");
     readfile($filename);
     unlink($filename);
 }
 public function userGetCoupon(Request $request, $id, $coupon_id)
 {
     try {
         DB::transaction(function () use($id, $coupon_id) {
             $coupon = Coupon::where('id', $coupon_id)->get()->first();
             // 检查是否可领取(开始领取时间?是否已经激活?)
             if ($coupon->begin_gain_time < date('Y')) {
                 throw new Exception('未到优惠券领取时间');
             }
             $count = UserCoupon::where(['user_id' => $id, 'coupon_id' => $coupon_id])->count();
             // 检查是否超出可领取数量限制
             if ($count >= $coupon->limit_gain_number) {
                 throw new Exception('超出可领取数量限制');
             }
             // 生成11位随机码(检查数据库是否有重复?有重复则提示用户重新输入)
             $coupon_code = generate_random_string('0123456789');
             if (!$coupon_code) {
                 throw new Exception('优惠码重复,请重新申请');
             }
             // 设置用户优惠券状态为未使用
             $user_coupon['user_id'] = $id;
             $user_coupon['coupon_id'] = $coupon_id;
             $user_coupon['coupon_code'] = $coupon_code;
             $user_coupon['coupon_status'] = 0;
             $user_coupon['created'] = time();
             $user_cou = UserCoupon::create($user_coupon);
             if (!$user_cou->id) {
                 throw new Exception('模拟用户优惠券失败');
             }
         });
         return redirect()->route('admin.test.user.index_coupon', $id)->with('message', '成功获取模拟优惠!');
     } catch (Exception $e) {
         return redirect()->back()->withInput($request->input())->with('fail', '获取模拟优惠券失败,数据库操作返回异常!' . $e->getMessage());
     }
 }
Exemple #6
0
function generate_token()
{
    $token = "";
    do {
        $token = generate_random_string(128);
    } while (count_rows("Sessions", "`Token` = '{$token}'", 1));
    return $token;
}
Exemple #7
0
 public function login($type = 'public', $redirect = true)
 {
     // Initialize
     global $config;
     // Get user row
     if (!($user_row = DB::queryFirstRow("SELECT * FROM users WHERE username = %s", strtolower($_POST['username'])))) {
         $this->invalid_login($type);
     }
     // Check password
     $client = new encrypt();
     if ($client->get_password_hash($_POST['password'], $user_row['id']) != $user_row['password']) {
         $this->invalid_login($type);
     }
     // Get session ID
     do {
         $session_id = generate_random_string(60);
         $exists = DB::queryFirstRow("SELECT * FROM auth_sessions WHERE auth_hash = %s", hash('sha512', $session_id)) ? 1 : 0;
     } while ($exists > 0);
     // Check for 2FA
     $require_2fa = false;
     if ($config['enable_2fa'] == 'all') {
         $require_2fa = true;
     } elseif ($config['enable_2fa'] == 'admin' && $user_row['group_id'] == 1) {
         $require_2fa = true;
     }
     // Generate 2FA hash, if needed
     if ($require_2fa === true) {
         $status_2fa = 0;
         $hash_2fa = generate_random_string(60);
         // Send e-mail
         $url = "http://" . $_SERVER['HTTP_HOST'] . '/2fa/' . $hash_2fa;
         mail($user_row['email'], "2FA Authentication - {$config['site_name']}", "You are receiving this e-mail because you just tried to login to {$config['site_name']}, which required 2FA.  To proceed with your login, please click on the below URL:\r\n\r\n\t{$url}\r\n\r\nThank you,\r\n{$config['site_name']}\r\n");
     } else {
         $status_2fa = 1;
         $hash_2fa = '';
     }
     // Create session
     DB::insert('auth_sessions', array('userid' => $user_row['id'], 'last_active' => time(), 'auth_hash' => hash('sha512', $session_id), '2fa_status' => $status_2fa, '2fa_hash' => $hash_2fa));
     // Set cookie
     $cookie_name = COOKIE_NAME . 'auth_hash';
     setcookie($cookie_name, $session_id);
     // Update alerts
     DB::query("UPDATE alerts SET is_new = 0 WHERE is_new = 2 AND userid = %d", $user_row['id']);
     DB::query("UPDATE alerts SET is_new = 2 WHERE is_new = 1 AND userid = %d", $user_row['id']);
     // Redirect user
     if ($status_2fa == 0) {
         $route = $type == 'admin' ? 'admin/2fa' : '2fa';
         $template = new template($route);
         echo $template->parse();
         exit(0);
     } elseif ($type == 'admin' && $redirect === true) {
         header("Location: " . SITE_URI . "/admin/index");
         exit(0);
     }
     // Return
     return $user_row['id'];
 }
Exemple #8
0
function generate_complex_array(array $nodesPerLayer = array(5, 5, 5, 5))
{
    $layer = [];
    $n = array_shift($nodesPerLayer);
    for ($i = 0; $i < $n; ++$i) {
        $layer[generate_random_string()] = empty($nodesPerLayer) ? generate_random_string() : generate_complex_array($nodesPerLayer);
    }
    return $layer;
}
function change_password($users, $passwords, $user, $old, $new)
{
    if (verify_password($users, $passwords, $user, $old)) {
        $new_salt = generate_random_string(20);
        $passwords[array_keys($users, $user)][0] = hash_password($new, $new_salt);
        $passwords[array_keys($users, $user)][1] = $new_salt;
        logout();
    }
}
Exemple #10
0
 public function download_files_as_zip($idlist = array())
 {
     $zip = new ZipArchive();
     $pid = array();
     $randomid = generate_random_string(16);
     $filename = DIR_BASE . "tmp/" . $randomid;
     if ($zip->open($filename, ZIPARCHIVE::CREATE) != true) {
         exit("cannot open <{$filename}>\n");
     }
     $imgs = array();
     foreach ($idlist as $id) {
         $piler_id = $this->model_search_message->get_piler_id_by_id($id);
         array_push($pid, $piler_id);
         $attachments = $this->model_search_message->get_attachment_list($piler_id);
         $images = array();
         foreach ($attachments as $a) {
             if (preg_match("/image/", $a['type'])) {
                 $attachment = $this->model_search_message->get_attachment_by_id($a['id']);
                 $fp = fopen(DIR_BASE . 'tmp/' . $a['id'], "w+");
                 if ($fp) {
                     fwrite($fp, $attachment['attachment']);
                     fclose($fp);
                     $images[] = array('id' => $a['id'], 'name' => $attachment['filename']);
                     $imgs[] = array('name' => $a['id']);
                 }
             }
         }
         $message = $this->model_search_message->extract_message($piler_id);
         $page = $message['from'] . "<br />\n";
         $page .= $message['to'] . "<br />\n";
         $page .= $message['subject'] . "<br />\n";
         $page .= $message['date'] . "<br />\n";
         $page .= "<hr />\n" . $message['message'];
         $this->create_pdf_from_eml($piler_id, $page, $images);
         foreach ($imgs as $img) {
             unlink(DIR_BASE . 'tmp/' . $img['name']);
         }
         $zip->addFile(DIR_BASE . 'tmp/' . $piler_id . '.pdf', $piler_id . '.pdf');
         AUDIT(ACTION_DOWNLOAD_MESSAGE, '', '', $id, '');
     }
     $zip->close();
     foreach ($pid as $piler_id) {
         unlink(DIR_BASE . 'tmp/' . $piler_id . '.pdf');
     }
     header("Cache-Control: public, must-revalidate");
     header("Pragma: no-cache");
     header("Content-Type: application/zip");
     header("Expires: 0");
     header("Content-Length: " . filesize($filename));
     header("Content-Disposition: attachment; filename=archive-{$randomid}.zip");
     header("Content-Transfer-Encoding: binary\n");
     readfile($filename);
     unlink($filename);
 }
Exemple #11
0
 public function create_pending_session($wallet_id, $product_id = 0, $amount = 0, $currency = 'btc')
 {
     // Initialize
     global $config, $template;
     $userid = LOGIN === true ? $GLOBALS['userid'] : 0;
     $expire_time = time() + $config['payment_expire_seconds'];
     // Get hash
     do {
         $hash = generate_random_string(120);
         if ($row = DB::queryFirstRow("SELECT * FROM coin_pending_payment WHERE pay_hash = %s", hash('sha512', 120))) {
             $exists = 1;
         } else {
             $exists = 0;
         }
     } while ($exists > 0);
     // Get product, if needed
     if ($product_id > 0) {
         if (!($prow = DB::queryFirstRow("SELECT * FROM products WHERE id = %d", $product_id))) {
             trigger_error("Product does not exist, ID# {$product_id}", E_USER_ERROR);
         }
         $amount = $prow['amount'];
         $currency = $prow['currency'];
         $item_name = $prow['display_name'];
     } else {
         $item_name = '';
     }
     // Get amount
     if ($currency == 'fiat') {
         $amount_btc = $amount / $config['exchange_rate'];
     } else {
         $amount_btc = $amount;
         $amount = $amount_btc * $config['exchange_rate'];
     }
     // Get payment address
     if ($userid > 0) {
         $client = new bip32();
         $payment_address = $client->get_user_address($wallet_id, $userid);
         // Delete any existing pending payments
         DB::query("DELETE FROM coin_pending_payment WHERE payment_address = %s AND status = 'pending'", $payment_address);
     } else {
         $payment_address = '';
     }
     // Add to db
     DB::insert('coin_pending_payment', array('wallet_id' => $wallet_id, 'pay_hash' => $hash, 'userid' => $userid, 'item_id' => $product_id, 'amount' => $amount, 'amount_btc' => $amount_btc, 'expire_time' => $expire_time, 'payment_address' => $payment_address));
     // Template variables
     $template->assign('payment_address', $payment_address);
     $template->assign('currency', $currency);
     $template->assign('amount', fmoney_coin($amount_btc));
     $template->assign('amount_fiat', fmoney($amount));
     $template->assign('product_id', $product_id);
     $template->assign('product_name', $item_name);
     // Return hash
     return $hash;
 }
Exemple #12
0
function login_cookie_create($user, $token_series = false)
{
    $time = time();
    $ip = get_ip(true);
    if (!$token_series) {
        $token_series = generate_random_string(16);
    }
    $token = generate_random_string(64);
    db_insert('cookie_tokens', array('added' => $time, 'ip_created' => $ip, 'ip_last' => $ip, 'user_id' => $user['id'], 'token_series' => $token_series, 'token' => $token));
    $cookie_content = array('t' => $token, 'ts' => $token_series);
    setcookie('login_tokens', json_encode($cookie_content), $time + CONFIG_COOKIE_TIMEOUT, '/', null, CONFIG_SSL_COMPAT, true);
}
function page()
{
    global $logger, $session, $db, $user;
    //handle the check
    $postData = $_POST;
    if (time() < $session->csrf_expire) {
        if ($session->csrf_token === $postData['csrf_token']) {
            $email = $postData['email'];
            $password = $postData['password'];
            if ($postData['remember']) {
                $remember = true;
            } else {
                $remember = false;
            }
            //ok, we're going to search for the user based on the email
            $result = $db->select("id, email, password, token, active")->from('users')->where('email', $email)->fetch_first();
            //if we have a record...
            if ($db->affected_rows > 0) {
                //found a matching user, now lets check the password
                if (password_verify($password, $result['password']) && $result['active']) {
                    //valid user!
                    //do we have a token? if not, create one and then initialize the user object
                    if ($result['token'] == '' || $result['token'] == Null) {
                        $token = generate_random_string(32);
                        $db->where('id', $result['id'])->update('users', array('token' => $token))->execute();
                    } else {
                        $token = $result['token'];
                    }
                    $session->setCookie('user', $token, $remember);
                    $session->user_token = $token;
                    $session->logged_in = true;
                    $redirect = '/pages/dashboard.php';
                    page_cleanup($redirect);
                } else {
                    // passwords don't match, let's set a formError and return to the index page
                    $session->setFormError('email', 'That email/password combination was not found!');
                    page_cleanup("/index.php");
                }
            } else {
                // user not found, let's set a formError and return to the index page
                $session->setFormError('email', 'That email/password combination was not found.');
                page_cleanup("/index.php");
            }
        } else {
            $session->setFormError('email', 'There was a token mismatch. Hack attempt foiled.');
            page_cleanup("/index.php");
        }
    } else {
        $session->setFormError('email', 'Timed out. Please don\'t let the form sit so long.');
        page_cleanup("/index.php");
    }
    //print "Session: ".$session->csrf_token."<br>Form: ".$_POST['csrf_token']."";
}
Exemple #14
0
 function autologin()
 {
     $this->load->helper('jazz_string');
     $this->load->model('mdl_login');
     $result = false;
     $cookie = $this->getcookie();
     if ($cookie) {
         $username = $cookie[0];
         $old_hash = $cookie[1];
         $result = $this->mdl_login->validate_cookie($username, $old_hash);
     }
     if (!$result) {
         $this->show();
     } else {
         $hash = generate_random_string(26);
         $result = $this->mdl_login->get_where_custom('jazz_users', 'user_email', $username)->row();
         modules::run('user/save_session_data', $result);
         modules::run('user/save_user_activity', $result);
         $this->deletecookie($username, $old_hash);
         $this->setcookie($username, $hash);
         redirect('dashboard');
     }
 }
Exemple #15
0
 public function message_as_rfc822_attachment($piler_id = '', $msg = '', $rcpt = '')
 {
     if ($piler_id == '' || $msg == '' || $rcpt == '') {
         return '';
     }
     $boundary = generate_random_string(24);
     $hdr = substr($msg, 0, 8192);
     $subject = "";
     $s = strstr($hdr, "Subject:");
     if ($s) {
         $l1 = strlen($s);
         $l2 = strlen(strstr($s, "\n"));
         if ($l1 > $l2 + 10) {
             $subject = substr($s, 0, $l1 - $l2) . EOL;
         }
     }
     $s = "";
     $s .= "Received: by piler" . EOL . PILER_HEADER_FIELD . $piler_id . EOL;
     $s .= "Date: " . date("r") . EOL;
     $s .= "Message-ID: <" . generate_random_string(25) . '@' . SITE_NAME . ">" . EOL;
     $s .= "From: " . SMTP_FROMADDR . EOL;
     $s .= "To: " . $rcpt . EOL;
     if ($subject) {
         $s .= $subject;
     } else {
         $s .= "Subject: Retrieved message from the email archive" . EOL;
     }
     $s .= "MIME-Version: 1.0" . EOL;
     $s .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"" . EOL . EOL . EOL;
     $s .= "--{$boundary}" . EOL;
     $s .= "Content-Type: message/rfc822; name=\"" . $piler_id . "\"" . EOL;
     $s .= "Content-Disposition: attachment; filename=\"" . $piler_id . "\"" . EOL . EOL;
     $s .= $msg . EOL;
     $s .= "--{$boundary}" . EOL;
     return $s;
 }
 /**
  * If the given arguments correspond to an existing user record, generate a new
  * password and send it with an email.
  *
  * @param string $username
  * @param string $email
  * @return string|bool Returns the new password on success or FALSE on failure.
  */
 public function regenerate_password($username, $email)
 {
     $this->load->helper('general');
     $result = $this->db->select('ea_users.id')->from('ea_users')->join('ea_user_settings', 'ea_user_settings.id_users = ea_users.id', 'inner')->where('ea_users.email', $email)->where('ea_user_settings.username', $username)->get();
     if ($result->num_rows() == 0) {
         return FALSE;
     }
     $user_id = $result->row()->id;
     // Create a new password and send it with an email to the given email address.
     $new_password = generate_random_string();
     $salt = $this->db->get_where('ea_user_settings', array('id_users' => $user_id))->row()->salt;
     $hash_password = hash_password($salt, $new_password);
     $this->db->update('ea_user_settings', array('password' => $hash_password), array('id_users' => $user_id));
     return $new_password;
 }
 public function printLogin()
 {
     $_SESSION['login_key'] = $login_key = generate_random_string(32);
     require TEMPLATE_DIR . '/login_form.template.php';
 }
Exemple #18
0
 public static function set_csrf()
 {
     self::set('mariana-csrf', generate_random_string(rand(15, 30)));
 }
 /**
  * @dataProvider providerGenerateRandomString
  */
 public function testGenerateRandomString($len, $chars, $regex)
 {
     $rv = generate_random_string($len, $chars);
     $this->assertRegExp($regex, $rv);
     $this->assertTrue($len == strlen($rv));
 }
 public function providerEncryptRandom()
 {
     $charlist = ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*()_+-=[]{}\\|/?,.<>;:"' . "'";
     $result = array();
     for ($i = 0; $i < 20; $i++) {
         $string = generate_random_string(mt_rand(20, 40), $charlist);
         $key = generate_random_string(mt_rand(4, 8));
         $result[] = array($string, $key);
     }
     return $result;
 }
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // get auth data
    if (isset($_POST['auth_key']) && is_valid_id($_POST['id'])) {
        $auth = db_select_one('reset_password', array('id', 'user_id', 'auth_key'), array('auth_key' => $_POST['auth_key'], 'user_id' => $_POST['id']));
        if (!$auth['user_id']) {
            message_error('No reset data found');
        }
    }
    // stage 1, part 2
    if ($_POST['action'] == 'reset_password') {
        if (CONFIG_RECAPTCHA_ENABLE_PUBLIC) {
            validate_captcha();
        }
        $user = db_select_one('users', array('id', 'team_name', 'email'), array('email' => $_POST[md5(CONFIG_SITE_NAME . 'EMAIL')]));
        if ($user['id']) {
            $auth_key = hash('sha256', generate_random_string(128));
            db_insert('reset_password', array('added' => time(), 'user_id' => $user['id'], 'ip' => get_ip(true), 'auth_key' => $auth_key));
            $email_subject = 'Password recovery for team ' . htmlspecialchars($user['team_name']);
            // body
            $email_body = htmlspecialchars($user['team_name']) . ', please follow the link below to reset your password:'******'reset_password?action=choose_password&auth_key=' . $auth_key . '&id=' . $user['id'] . "\r\n" . "\r\n" . 'Regards,' . "\r\n" . CONFIG_SITE_NAME;
            // send details to user
            send_email(array($user['email']), $email_subject, $email_body);
        }
        message_generic('Success', 'If the email you provided was found in the database, an email has now been sent to it with further instructions!');
    } else {
        if ($_POST['action'] == 'choose_password' && is_valid_id($auth['user_id'])) {
            $new_password = $_POST[md5(CONFIG_SITE_NAME . 'PWD')];
            if (empty($new_password)) {
                message_error('You can\'t have an empty password');
            }
            $new_passhash = make_passhash($new_password);
Exemple #22
0
function generate_verifier($length = 8) {
    return generate_random_string($length);
}
function generate_word()
{
    return generate_random_string(rand(3, 10));
}
Exemple #24
0
 function add_merchant()
 {
     if (!check_correct_login_type($this->main_group_id)) {
         redirect('/', 'refresh');
     }
     $login_id = $this->ion_auth->user()->row()->id;
     $tables = $this->config->item('tables', 'ion_auth');
     if (isset($_POST) && !empty($_POST)) {
         $_POST['slug'] = generate_slug($_POST['company']);
         $slug = $_POST['slug'];
     }
     // validate form input
     if (empty($_FILES['userfile']['name'])) {
         $this->form_validation->set_rules('userfile', 'Merchant Logo', 'required');
     }
     //$this->form_validation->set_rules('company_main', $this->lang->line('create_merchant_validation_company_main_label'), "trim|required|min_length[3]");
     $this->form_validation->set_rules('company', $this->lang->line('create_merchant_validation_company_label'), "trim|required|min_length[3]");
     $this->form_validation->set_rules('slug', $this->lang->line('create_merchant_validation_company_label'), 'trim|is_unique[' . $tables['users'] . '.slug]');
     $this->form_validation->set_rules('address', $this->lang->line('create_merchant_validation_address_label'), 'required');
     //$this->form_validation->set_rules('postcode', $this->lang->line('create_merchant_validation_postcode_label'), 'required|numeric');
     $this->form_validation->set_rules('me_state_id', $this->lang->line('create_merchant_validation_state_label'), 'callback_check_state_id');
     //$this->form_validation->set_rules('me_category_id', $this->lang->line('create_merchant_category_label'), 'callback_check_main_category');
     $this->form_validation->set_rules('me_sub_category_id', $this->lang->line('create_merchant_sub_category_label'), 'callback_check_sub_category');
     if ($this->form_validation->run() == true) {
         $username = generate_random_string($slug);
         $email = generate_random_string($slug, 1);
         $password = $this->config->item('password_example');
         //$company_main = $this->input->post('company_main');
         $company_main = '';
         $company = $this->input->post('company');
         $address = $this->input->post('address');
         //$postcode = $this->input->post('postcode');
         $postcode = '';
         $state = $this->input->post('me_state_id');
         $country = 'Malaysia';
         $profile_image = NULL;
         //$me_is_halal = $this->input->post('me_is_halal') == NULL ? 0 : 1;
         $me_halal_way = $this->input->post('me_halal_way');
         if (!empty($_FILES['userfile']['name'])) {
             $upload_rule = array('upload_path' => $this->album_merchant_profile, 'allowed_types' => $this->config->item('allowed_types_image'), 'max_size' => $this->config->item('max_size'), 'max_width' => $this->config->item('max_width'), 'max_height' => $this->config->item('max_height'));
             $this->load->library('upload', $upload_rule);
             if (!$this->upload->do_upload()) {
                 $this->session->set_flashdata('message', $this->upload->display_errors());
             } else {
                 //$image_data = array('upload_data' => $this->upload->data());
                 $profile_image = $this->upload->data('file_name');
             }
         }
         $additional_data = array('username' => $username, 'company_main' => $company_main, 'company' => $company, 'slug' => $slug, 'address' => $address, 'postcode' => $postcode, 'country' => $country, 'me_state_id' => $state, 'me_category_id' => $this->config->item('food_category_id'), 'me_sub_category_id' => $this->input->post('me_sub_category_id'), 'main_group_id' => $this->config->item('group_id_merchant'), 'password_visible' => $password, 'me_addby_user' => $login_id, 'me_notyet_active' => 1, 'profile_image' => $profile_image, 'me_halal_way' => $me_halal_way);
         $group_ids = array($this->config->item('group_id_merchant'));
         $new_id = $this->ion_auth->register($username, $password, $email, $additional_data, $group_ids);
         if ($new_id) {
             $this->m_user->candie_history_insert(35, $new_id, 'users');
             $this->session->set_flashdata('message', 'Merchant account successfully created, Please add a photo for this merchant. Thank You.');
             redirect("user/upload_for_merchant/" . $new_id, 'refresh');
         } else {
             goto add_merchant_fail;
         }
     } else {
         add_merchant_fail:
         $this->data['message'] = validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message'));
         $this->data['company_main'] = array('name' => 'company_main', 'id' => 'company_main', 'type' => 'text', 'value' => $this->form_validation->set_value('company_main'));
         $this->data['company'] = array('name' => 'company', 'id' => 'company', 'type' => 'text', 'value' => $this->form_validation->set_value('company'));
         $this->data['address'] = array('name' => 'address', 'id' => 'address', 'value' => $this->form_validation->set_value('address'));
         $this->data['postcode'] = array('name' => 'postcode', 'id' => 'postcode', 'type' => 'text', 'value' => $this->form_validation->set_value('postcode'));
         $this->data['state_list'] = $this->m_custom->get_static_option_array('state', '0', 'Please Select');
         $this->data['me_state_id'] = array('name' => 'me_state_id', 'id' => 'me_state_id', 'value' => $this->form_validation->set_value('me_state_id'));
         $me_category_id = $this->form_validation->set_value('me_category_id') == '' ? '' : $this->form_validation->set_value('me_category_id');
         $this->data['category_list'] = $this->m_custom->getCategoryList('0', 'Please Select');
         $this->data['me_category_id'] = array('name' => 'me_category_id', 'id' => 'me_category_id', 'value' => $me_category_id, 'onChange' => "get_SubCategory()");
         $this->data['sub_category_list'] = $this->m_custom->getSubCategoryList('0', 'Please Select', 1);
         //$this->data['sub_category_list'] = $this->m_custom->getSubCategoryList(NULL, NULL, $me_category_id);
         $this->data['me_sub_category_id'] = array('name' => 'me_sub_category_id', 'id' => 'me_sub_category_id', 'value' => $this->form_validation->set_value('me_sub_category_id'));
         //            $this->data['me_is_halal'] = array(
         //                'name' => 'me_is_halal',
         //                'id' => 'me_is_halal',
         //                'value' => '1', //Just to have some value, checkbox have to have value
         //            );
         $this->data['halal_way_list'] = $this->ion_auth->get_static_option_list('halal_way');
         $this->data['me_halal_way'] = array('name' => 'me_halal_way', 'id' => 'me_halal_way');
         $this->data['temp_folder'] = $this->temp_folder;
         $this->data['page_path_name'] = 'user/add_merchant';
         $this->load->view('template/layout', $this->data);
     }
 }
 /**
  * Generates 30 character random username with leading type-letter
  *
  * @return string
  */
 public function generate_username()
 {
     return $this->get_customer_letter() . generate_random_string(self::LENGTH_USERNAME - 1);
 }
Exemple #26
0
function jethro_password_hash($str)
{
    if (function_exists('password_hash')) {
        return password_hash($str, PASSWORD_DEFAULT);
    } else {
        $salt = NULL;
        if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH) {
            $salt = '$2y$10$' . generate_random_string(22);
        } else {
            if (defined('CRYPT_SHA512') && CRYPT_SHA512) {
                $salt = '$6$' . generate_random_string(16);
            } else {
                if (defined('CRYPT_SHA256') && CRYPT_SHA256) {
                    $salt = '$5$' . generate_random_string(16);
                }
            }
        }
        $res = crypt($str, $salt);
        if (strlen($res) < 4) {
            trigger_error("Crypt function returned invalid result {$res} for salt {$salt}", E_USER_ERROR);
        }
        return $res;
    }
}
Exemple #27
0
 public function __construct($parts = array())
 {
     // Initialize
     global $config, $template;
     // Set variables
     if ($config['is_setup'] == 1 && preg_match("/^admin/", trim($_GET['route'], '/'))) {
         $panel = 'admin';
         $require_login = true;
     } else {
         $panel = 'public';
         $require_login = false;
     }
     // Check IP restrictions
     if ($panel == 'admin' && isset($config['ipallow']) && $config['ipallow'] != '') {
         $ok = false;
         $ips = explode("\n", $config['ipallow']);
         foreach ($ips as $ip) {
             if (preg_match("/^{$ip}/", $_SERVER['REMOTE_ADDR'])) {
                 $ok = true;
                 break;
             }
         }
         if ($ok === false) {
             echo "Access dened by IP restrictions.";
             exit(0);
         }
     }
     // Continue setup, if needed
     if (DBNAME == '' && isset($_POST['submit']) && $_POST['submit'] == tr('Continue to Next Step')) {
         // Initialize
         $template = new template('admin/setup/first_time2');
         require_once SITE_PATH . '/data/lib/sqlparser.php';
         // Check database connection
         if (!mysqli_connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpass'], $_POST['dbname'], $_POST['dbport'])) {
             $template->add_message("Unable to connect to mySQL database using information supplied.  Please double check the mySQL information, and try again.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/config.php')) {
             $template->add_message("Unable to write to file at /data/config.php.  Please change file permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/backups')) {
             $template->add_message("Unable to write to directory at /data/backups/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/log')) {
             $template->add_message("Unable to write to directory at /data/log/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/tpl_c')) {
             $template->add_message("Unable to write to directory at /data/tpl_c/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         // Check for errors
         if ($template->has_errors == 1) {
             $template->route = 'admin/setup/first_time';
             echo $template->parse();
             exit(0);
         }
         // Define MeekroDB settings
         DB::$dbName = $_POST['dbname'];
         DB::$user = $_POST['dbuser'];
         DB::$password = $_POST['dbpass'];
         DB::$host = $_POST['dbhost'];
         DB::$port = $_POST['dbport'];
         // Parse sql
         $sql_lines = SqlParser::parse(file_get_contents(SITE_PATH . '/data/sql/install.sql'));
         foreach ($sql_lines as $line) {
             DB::query($line);
         }
         // Save config.php file
         $conf = "<?php\n";
         $conf .= "define('DBNAME', '" . $_POST['dbname'] . "');\n";
         $conf .= "define('DBUSER', '" . $_POST['dbuser'] . "');\n";
         $conf .= "define('DBPASS', '" . $_POST['dbpass'] . "');\n";
         $conf .= "define('DBHOST', '" . $_POST['dbhost'] . "');\n";
         $conf .= "define('DBPORT', '" . $_POST['dbport'] . "');\n";
         $conf .= "define('COOKIE_NAME', '" . generate_random_string(6) . "');\n";
         $conf .= "define('ENCRYPT_PASS', '" . generate_random_string(32) . "');\n";
         $conf .= "define('TESTNET', 0);\n";
         $conf .= "?>\n";
         // Save config file
         file_put_contents(SITE_PATH . '/data/config.php', $conf);
         // Parse template
         echo $template->parse();
         exit(0);
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '2') {
         // Initialize
         $template = new template('admin/setup/first_time3');
         if (strlen($_POST['username']) < 4) {
             $template->add_message('Administrator username must be at least 4 characters in length.', 'error');
         }
         // Create user
         $user = new user();
         $user->create(1);
         // Update config vars
         update_config_var('site_name', $_POST['site_name']);
         update_config_var('company_name', $_POST['company_name']);
         // Check for errors
         if ($template->has_errors == 1) {
             $template->route = 'admin/setup/first_time2';
         } else {
             // Login
             $auth = new auth();
             $auth->login('admin', false);
         }
         echo $template->parse();
         exit(0);
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '3') {
         // Initialize
         $template = new template('admin/setup/first_time4');
         // Update config vars
         update_config_var('btc_rpc_host', $_POST['btc_rpc_host']);
         update_config_var('btc_rpc_user', $_POST['btc_rpc_user']);
         update_config_var('btc_rpc_pass', $_POST['btc_rpc_pass']);
         update_config_var('btc_rpc_port', $_POST['btc_rpc_port']);
         // Test connection
         $client = new transaction();
         if (!$client->get_info()) {
             $template->route = 'admin/setup/first_time3';
             $template->add_message('Unable to connect to RPC using the provided settings.  Please check the connection information, restart bitcoind, and try again.  If you have just started bitcoind for the first time, you will need to wait a while for all blocks to download before continuing.', 'error');
             $template->parse();
             exit(0);
         }
         // Parse template
         echo $template->parse();
         exit(0);
         // Complete setup, if needed
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '4') {
         // Initialize
         $template = new template('admin/setup/first_time5');
         // Update config vars
         update_config_var('is_setup', '1');
         // Get exchange date
         $rate = get_coin_exchange_rate($config['currency']);
         if ($rate != 0) {
             update_config_var('exchange_rate', $rate);
         }
         // Add wallet
         $bip32 = new bip32();
         $bip32->add_wallet();
         // Display template
         if ($template->has_errors != 1) {
             //$template->add_message("Successfully completed first time setup.");
         }
         echo $template->parse();
         exit(0);
     }
     // Check if setup
     if ($config['is_setup'] == 0) {
         $template = new template('admin/setup/first_time');
         echo $template->parse();
         exit(0);
     }
     // Check login
     $auth = new auth();
     if ($userid = $auth->check_login($panel, $require_login)) {
         define('LOGIN', true);
         $GLOBALS['userid'] = $userid;
     } else {
         define('LOGIN', false);
         $GLOBALS['userid'] = 0;
     }
     // Check admin permission, if needed
     if ($panel == 'admin') {
         $group_id = DB::queryFirstField("SELECT group_id FROM users WHERE id = %d", $GLOBALS['userid']);
         if ($group_id != 1) {
             trigger_error("You do not have permission to access this area.", E_USER_ERROR);
         }
     }
     // Parse template
     $template = new template();
     echo $template->parse();
     // Exit
     exit(0);
 }
function regenerate_submission_token()
{
    $_SESSION[CONST_SUBMISSION_TOKEN_KEY] = generate_random_string(64);
}
Exemple #29
0
 public function setFeedUUID()
 {
     $uuid = generate_random_string(60);
     while ($others = $GLOBALS['system']->getDBObjectData('person', array('feed_uuid' => $uuid))) {
         $uuid = generate_random_string(60);
     }
     $this->setValue('feed_uuid', $uuid);
     return $uuid;
 }
Exemple #30
0
function generate_picture_name($wwww = '')
{
    if (!$wwww) {
        return generate_random_string(3) . time();
    } else {
        $xxxx = explode('.', $wwww);
        $yyyy = array_pop($xxxx);
        return generate_random_string(3) . time() . '.' . $yyyy;
    }
}