Subversion Repositories cheapmusic

Rev

Rev 122 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
// Email sending functions
include_once 'includes/email_functions.php';
include_once 'includes/password.php';

// Include Session Handling
require_once ('includes/session.php');
global $systemConf;
if (empty($_POST["nonce"]) || NonceUtil::check($systemConf["nonce_secret"], $_POST["nonce"]) === false) {
    // Redirect to the home page
    MySessionHandler::commit(session_id());
    header("Location:../index.php");
    exit;
}

// Include config file
require_once 'includes/config.php';

// Load and initialize user class
require_once 'includes/User.class.php';
$user = new User();

if (isset($_POST['signupSubmit'])) {
    $valErr = 0;
    $captchaErr = 0;

    // Store post data into session
    $_SESSION['signup_post_data'] = $_POST;

    if (!empty($_POST['g-recaptcha-response'])) {
        $secretKey = GR_SECRET_KEY;
        $ch = curl_init('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['g-recaptcha-response']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $verifyResponse = curl_exec($ch);
        $responseData = json_decode($verifyResponse);

        if ($responseData->success) {
            if ($responseData->score < 0.6) {
                $captchaErr = 1;
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'Robot verification failed, please try again.';
            }
        }
        else {
            $captchaErr = 1;
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Robot verification failed, please try again.';
        }
    }
    else {
        $captchaErr = 1;
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Robot verification failed, please try again.';
    }

    if ($captchaErr == 1) {
        // Redirect back to the registration page
        $_SESSION['sessData'] = $sessData;
        MySessionHandler::commit(session_id());
        header("Location:registration.php");
        exit;
    }

    // Get user inputs
    $first_name = sanitizeInput($_POST['first_name']);
    $last_name = sanitizeInput($_POST['last_name']);
    $email = sanitizeInput($_POST['email']);
    $zip = sanitizeInput($_POST['zip']);
    $password = sanitizeInput($_POST['password']);
    $confirm_password = sanitizeInput($_POST['confirm_password']);

    if (empty($first_name)) {
        $valErr = 1;
        $sessData['field_error']['first_name'] = 'Please enter your first name.';
    }
    /*
    if(empty($last_name)){
    $valErr = 1;
    $sessData['field_error']['last_name'] = 'Please enter your last name.';
    }
    */
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $valErr = 1;
        $sessData['field_error']['email'] = 'Please enter a valid email.';
    }
    if (empty($password)) {
        $valErr = 1;
        $sessData['field_error']['password'] = 'Please enter account password.';
    }
    if (empty($confirm_password)) {
        $valErr = 1;
        $sessData['field_error']['confirm_password'] = 'Please confirm your password.';
    }
    elseif ($password !== $confirm_password) {
        $valErr = 1;
        $sessData['field_error']['confirm_password'] = 'Confirm password does not match the password.';
    }

    if ($valErr == 0) {
        // Check whether user exists in the database
        $cond['where'] = array(
            'email' => $email
        );
        $cond['return_type'] = 'count';
        $userCount = $user->getRows($cond);
        if ($userCount > 0) {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Email already exists, please use another email.';
        }
        else {
            // Email verification code
            $uniqidStr = md5(uniqid(mt_rand()));

            // Insert user data in the database
            $userData = array(
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                'password' => password_hash($password, PASSWORD_DEFAULT) ,
                'zip' => $zip,
                'activation_code' => $uniqidStr
            );
            $insert = $user->insert($userData);

            // Set status based on data insert
            if ($insert) {
                // Remove post data from session
                unset($_SESSION['signup_post_data']);

                // Send account verification email
                @emailVerification($userData);

                $sessData['status']['type'] = 'success';
                $sessData['status']['msg'] = 'Your registration was successful. Please check your email inbox (and spam folder) to verify and activate your account.';

                // Remove post data from session
                unset($_SESSION['signup_post_data']);
            }
            else {
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'Some problem occurred, please try again.';
            }
        }
    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Please fill all mandatory fields.';
    }

    // Store signup status into the session
    $_SESSION['sessData'] = $sessData;
    $redirectURL = ($sessData['status']['type'] == 'success') ? 'index.php' : 'registration.php';

    // Redirect to the home/login page
    MySessionHandler::commit(session_id());
    header("Location:" . $redirectURL);
    exit;
}
elseif (isset($_POST['loginSubmit'])) {
    // Get user inputs
    $email = sanitizeInput($_POST['email']);
    $password = sanitizeInput($_POST['password']);

    // Check whether login details are empty
    if (!empty($email) && !empty($password)) {
        // Get user data from user class
        $conditions['where'] = array(
            'email' => $email,
            'status' => '1'
        );
        $conditions['return_type'] = 'single';
        $userData = $user->getRows($conditions);

        if (!empty($userData) && password_verify($password, $userData['password'])) {
            // Set user data and status based on login credentials
            if ($userData['activated'] == '0') {
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'Your account activation is pending, please check your email inbox to verify and activate your account.';
            }
            else {
                // If remember me is checked
                if (isset($_POST['rememberMe']) && $_POST['rememberMe'] == 1) {
                    setcookie('rememberUserId', $userData['id'], time() + (30 * 86400) , "/");
                    setcookie('hash', password_hash($userData['password'] . $userData['id'], PASSWORD_DEFAULT) , time() + (30 * 86400) , "/");
                }

                $sessData['userLoggedIn'] = true;
                $sessData['userID'] = $userData['id'];
                $sessData['status']['type'] = 'success';
                $sessData['status']['msg'] = 'Welcome ' . $userData['first_name'] . '!';
            }
        }
        else {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Wrong email or password, please try again.';
        }
    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Enter email and password.';
    }

    // Store login status into the session
    $_SESSION['sessData'] = $sessData;

    // Redirect to the home page
    MySessionHandler::commit(session_id());
    header("Location:index.php");
    exit;
}
elseif (isset($_POST['forgotSubmit'])) {
    $frmDisplay = '';

    // Get user inputs
    $email = sanitizeInput($_POST['email']);

    // Check whether email is empty
    if (!empty($email)) {
        // Check whether user exists in the database
        $cond['where'] = array(
            'email' => $email
        );
        $cond['return_type'] = 'count';
        $userCount = $user->getRows($cond);
        if ($userCount > 0) {
            // Generat unique string
            $uniqidStr = md5(uniqid(mt_rand()));

            // Update data with forgot pass code
            $conditions = array(
                'email' => $email
            );
            $data = array(
                'forgot_pass_identity' => $uniqidStr
            );
            $update = $user->update($data, $conditions);

            if ($update) {
                // Get user details
                $con['where'] = array(
                    'email' => $email
                );
                $con['return_type'] = 'single';
                $userDetails = $user->getRows($con);

                // Send reset password email
                @forgotPassEmail($userDetails);

                $sessData['status']['type'] = 'success';
                $sessData['status']['msg'] = 'Please check your email inbox (and spam folder), we have sent a password reset link to your registered email.';
                $frmDisplay = '?frmDis=0';
            }
            else {
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'Some problem occurred, please try again.';
            }
        }
        else {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Given email is not associated with any account.';
        }

    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Enter email to create a new password for your account.';
    }

    // Store reset password status into the session
    $_SESSION['sessData'] = $sessData;

    // Redirect to the forgot pasword page
    MySessionHandler::commit(session_id());
    header("Location:forgotPassword.php" . $frmDisplay);
}
elseif (isset($_POST['resetSubmit'])) {
    $fp_code = sanitizeInput($_POST['fp_code']);

    // Get user inputs
    $password = sanitizeInput($_POST['password']);
    $confirm_password = sanitizeInput($_POST['confirm_password']);

    if (!empty($password) && !empty($confirm_password) && !empty($fp_code)) {
        // Password and confirm password comparison
        if ($password !== $confirm_password) {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Confirm password does not match the password.';
        }
        else {
            //check whether identity code exists in the database
            $cond['where'] = array(
                'forgot_pass_identity' => $fp_code
            );
            $cond['return_type'] = 'count';
            $userCount = $user->getRows($cond);
            if ($userCount > 0) {
                // Update data with new password
                $conditions = array(
                    'forgot_pass_identity' => $fp_code
                );
                $data = array(
                    'password' => password_hash($password, PASSWORD_DEFAULT)
                );
                $update = $user->update($data, $conditions);
                if ($update) {
                    $sessData['status']['type'] = 'success';
                    $sessData['status']['msg'] = 'Your account password has been reset. Please login with your new password.';
                }
                else {
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'Some problem occurred, please try again.';
                }
            }
            else {
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'You are not authorized to reset the password for this account.';
            }
        }
    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'All fields are mandatory, please fill all the fields.';
    }

    // Store reset password status into the session
    $_SESSION['sessData'] = $sessData;
    $redirectURL = ($sessData['status']['type'] == 'success') ? 'index.php' : 'resetPassword.php?fp_code=' . $fp_code;

    // Redirect to the login/reset pasword page
    MySessionHandler::commit(session_id());
    header("Location:" . $redirectURL);
    exit;
}
elseif (isset($_REQUEST['verifyEmail']) && $_REQUEST['verifyEmail'] == 1) {
    $ac_code = $_REQUEST['ac_code'];

    // Check whether activation code exists in the database
    $cond['where'] = array(
        'activation_code' => $ac_code
    );
    $cond['return_type'] = 'count';
    $userCount = $user->getRows($cond);
    if ($userCount > 0) {
        // Update data with new password
        $conditions = array(
            'activation_code' => $ac_code
        );
        $data = array(
            'activated' => '1'
        );
        $update = $user->update($data, $conditions);
        if ($update) {
            $sessData['status']['type'] = 'success';
            $sessData['status']['msg'] = 'Email verification for your account was successful. Please login to your account.';
        }
        else {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Some problem occurred, please try again.';
        }
    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'You have used the wrong verification link, please check your email inbox and try again.';
    }

    // Store account activation status into the session
    $_SESSION['sessData'] = $sessData;
    $redirectURL = 'index.php';

    // Redirect to the login page
    MySessionHandler::commit(session_id());
    header("Location:" . $redirectURL);
    exit;
}
elseif (isset($_POST['updateProfile']) && !empty($_SESSION['sessData']['userID'])) {
    $valErr = 0;

    $sessData = $_SESSION['sessData'];
    unset($sessData['field_error']);
    unset($sessData['status']);
    $sessUserId = $sessData['userID'];

    //echo "<pre>", print_r($_POST, 1), "</pre>";
    //exit;
    // Get user inputs
    $first_name = sanitizeInput($_POST['first_name']);
    $last_name = sanitizeInput($_POST['last_name']);
    $email = sanitizeInput($_POST['email']);
    $zip = sanitizeInput($_POST['zip']);
    $theme = strtolower(sanitizeInput($_POST['theme']));
    $cardView = $_POST['cardView'];
    $conditionNew = isset($_POST['filterConditionNew']) ? 1 : 0;
    $conditionUsed = isset($_POST['filterConditionUsed']) ? 1 : 0;
    $mediaCD = isset($_POST['filterMediaTypeCD']) ? 1 : 0;
    $mediaRecord = isset($_POST['filterMediaTypeRecord']) ? 1 : 0;
    $mediaDigital = isset($_POST['filterMediaTypeDigital']) ? 1 : 0;
    $mediaBook = isset($_POST['filterMediaTypeBook']) ? 1 : 0;
    $wlEmail = $_POST['wlEmail'];
    $wlFreq = $_POST['wlFreq'];

    if (empty($first_name)) {
        $valErr = 1;
        $sessData['field_error']['first_name'] = 'Please enter your first name.';
    }
    /*
    if(empty($last_name)){
    $valErr = 1;
    $sessData['field_error']['last_name'] = 'Please enter your last name.';
    }
    */
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $valErr = 1;
        $sessData['field_error']['email'] = 'Please enter a valid email.';
    }

    if ($valErr == 0) {
        // Check whether user exists in the database
        $cond['where'] = array(
            'email' => $email
        );
        $cond['where_not'] = array(
            'id' => $sessUserId
        );
        $cond['return_type'] = 'count';
        $userCount = $user->getRows($cond);
        if ($userCount > 0) {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Email already exists, please use another email.';
        }
        else {
            // Get user information
            $conditions['where'] = array(
                'id' => $sessData['userID'],
            );
            $conditions['return_type'] = 'single';
            $userData = $user->getRows($conditions);
            $prevPicture = $userData['picture'];

            // Prepare user data
            $userData = array(
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                'zip' => $zip,
                'conditionNew' => $conditionNew,
                'conditionUsed' => $conditionUsed,
                'mediaCD' => $mediaCD,
                'mediaRecord' => $mediaRecord,
                'mediaDigital' => $mediaDigital,
                'mediaBook' => $mediaBook,
                'theme' => $theme,
                'cardView' => $cardView,
                'wlEmailFlag' => $wlEmail,
                'wlFreq' => $wlFreq
            );

            // Profile picture upload
            $fileErr = 0;
            if (!empty($_FILES['picture']['name'])) {
                $targetDir = UPLOAD_PATH . 'profile_picture/';
                $fileName = time() . '_' . basename($_FILES["picture"]["tmp_name"]);
                $targetFilePath = $targetDir . $fileName;
                $fileType = strtolower(pathinfo($_FILES["picture"]["name"], PATHINFO_EXTENSION));
                $allowTypes = array(
                    'jpg',
                    'png',
                    'jpeg',
                    'gif'
                );
                if (in_array($fileType, $allowTypes)) {
                    if ($_FILES["picture"]["size"] > 500000) {
                        $fileErr = 1;
                        $sessData['status']['type'] = 'error';
                        $sessData['status']['msg'] = 'Please upload a smaller image file.';
                    }
                    else {
                        $check = getimagesize($_FILES["picture"]["tmp_name"]);
                        if ($check === false) {
                            $fileErr = 1;
                            $sessData['status']['type'] = 'error';
                            $sessData['status']['msg'] = 'Please upload only gif/jpg/png files.';
                        }
                    }
                }
                else {
                    $fileErr = 1;
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'Please upload only gif/jpg/png files.';
                }

                if ($fileErr == 0) {
                    if (move_uploaded_file($_FILES["picture"]["tmp_name"], $targetFilePath)) {
                        $userData['picture'] = $fileName;

                        // Delete previous profile picture
                        @unlink(UPLOAD_PATH . 'profile_picture/' . $prevPicture);
                    }
                    else {
                        $fileErr = 1;
                        $sessData['status']['type'] = 'error';
                        $sessData['status']['msg'] = 'Could not upload picture.';
                        @unlink($_FILES["picture"]["tmp_name"]);
                    }
                }
                else {
                    @unlink($_FILES["picture"]["tmp_name"]);
                }
            }

            if ($fileErr == 0) {
                // Update user data in the database
                $conditions = array(
                    'id' => $sessUserId
                );

                $update = $user->update($userData, $conditions);

                // Set status based on data insert
                if ($update) {
                    $sessData['status']['type'] = 'success';
                    $sessData['status']['msg'] = 'Your profile information has been updated.';
                }
                else {
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'Some problem occurred, please try again.';
                }
            }
        }
    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Please fill all mandatory fields.';
    }

    // Store signup status into the session
    $_SESSION['sessData'] = $sessData;
    $redirectURL = 'editAccount.php';

    // Redirect to the profile page
    MySessionHandler::commit(session_id());
    header("Location:" . $redirectURL);
    exit;
}
elseif (isset($_POST['updatePassword']) && !empty($_SESSION['sessData']['userID'])) {
    $sessData = $_SESSION['sessData'];
    unset($sessData['field_error']);
    unset($sessData['status']);
    $sessUserId = $sessData['userID'];

    // Get user inputs
    $old_password = sanitizeInput($_POST['old_password']);
    $password = sanitizeInput($_POST['password']);
    $confirm_password = sanitizeInput($_POST['confirm_password']);

    if (!empty($password) && !empty($confirm_password)) {
        // Password and confirm password comparison
        if ($password !== $confirm_password) {
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Confirm password does not match the password.';
        }
        else {
            // Check whether identity code exists in the database
            $cond['where'] = array(
                'id' => $sessUserId
            );
            $cond['return_type'] = 'single';
            $userData = $user->getRows($cond);

            if ((!empty($userData) && !empty($sessData['loginType']) && $sessData['loginType'] == 'social') || (!empty($userData) && password_verify($old_password, $userData['password']))) {
                // Update data with new password
                $conditions = array(
                    'id' => $sessUserId
                );
                $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                $data = array(
                    'password' => $passwordHash
                );
                $update = $user->update($data, $conditions);
                if ($update) {
                    if (!empty($_COOKIE['rememberUserId'])) {
                        setcookie('hash', password_hash($passwordHash . $sessUserId, PASSWORD_DEFAULT) , time() + (30 * 86400) , "/");
                    }
                    $sessData['status']['type'] = 'success';
                    $sessData['status']['msg'] = 'Your account password has been updated.';
                }
                else {
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'Some problem occurred, please try again.';
                }
            }
            else {
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'The given old password does not match your current account password.';
            }
        }
    }
    else {
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Please fill all mandatory fields.';
    }

    // Store reset password status into the session
    $_SESSION['sessData'] = $sessData;
    $redirectURL = 'changePassword.php';

    // Redirect to the pasword settings page
    MySessionHandler::commit(session_id());
    header("Location:" . $redirectURL);
    exit;
}
elseif (!empty($_REQUEST['logoutSubmit'])) {
    // Include social login handler
    if (!empty($_SESSION['sessData']['loginType']) && ($_SESSION['sessData']['loginType'] == 'social') && !empty($_SESSION['google_access_token'])) {
        require_once 'includes/socialLogin.php';
    }

    // Remove cookie data
    setcookie("rememberUserId", "", time() - 3600, "/");
    setcookie("hash", "", time() - 3600, "/");
    unset($_COOKIE['rememberUserId']);
    unset($_COOKIE['hash']);

    // Remove session data
    unset($_SESSION['facebook_access_token']);
    unset($_SESSION['FBRLH_state']);
    if (isset($_SESSION['google_access_token'])) {
        // Reset OAuth access token
        $gClient->revokeToken();
    }
    unset($_SESSION['google_access_token']);
    unset($_SESSION['twitter_access_token']);
    unset($_SESSION['twitter_token_secret']);
    unset($_SESSION['sessData']);
    session_destroy();

    // Store logout status into the session
    $sessData['status']['type'] = 'success';
    $sessData['status']['msg'] = 'You have logged off your account.';
    $_SESSION['sessData'] = $sessData;

    // Redirect to the home page
    MySessionHandler::commit(session_id());
    header("Location:../index.php");
    exit;
}
else {
    // Redirect to the home page
    MySessionHandler::commit(session_id());
    header("Location:../index.php");
    exit;
}

// sanitize user input
function sanitizeInput($data) {
    $data = trim(preg_replace('/[\t\n\r\s]+/', ' ', $data));
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}