function swpm_alr_do_after_login_redirection()
{
    if (class_exists('SwpmLog')) {
        SwpmLog::log_simple_debug("After login redirection addon. Checking if member need to be redirected.", true);
    }
    $auth = SwpmAuth::get_instance();
    if ($auth->is_logged_in()) {
        //Member is logged in. Lets check if redirection needs to be done.
        //First check if a the swpm_redirect_to argument is set (meaning the user needs to be redirected to the last page).
        if (isset($_REQUEST['swpm_redirect_to']) && !empty($_REQUEST['swpm_redirect_to'])) {
            $redirect_to = esc_url_raw(sanitize_text_field($_REQUEST['swpm_redirect_to']));
            //Redirect to the membership level specific after login page.
            wp_redirect($redirect_to);
            exit;
        }
        //Check if there is a membership level specific after login redirection
        $level = $auth->get('membership_level');
        $level_id = $level;
        $key = 'swpm_alr_after_login_page_field';
        $after_login_page_url = SwpmMembershipLevelCustom::get_value_by_key($level_id, $key);
        if (!empty($after_login_page_url)) {
            //Redirect to the membership level specific after login page.
            wp_redirect($after_login_page_url);
            exit;
        }
        //No redirection found. So stay on the current page.
    }
}
 protected function send_reg_email()
 {
     global $wpdb;
     if (empty($this->member_info)) {
         return false;
     }
     $member_info = $this->member_info;
     $settings = SwpmSettings::get_instance();
     $subject = $settings->get_value('reg-complete-mail-subject');
     $body = $settings->get_value('reg-complete-mail-body');
     $from_address = $settings->get_value('email-from');
     $login_link = $settings->get_value('login-page-url');
     $headers = 'From: ' . $from_address . "\r\n";
     $member_info['membership_level_name'] = SwpmPermission::get_instance($member_info['membership_level'])->get('alias');
     $member_info['password'] = $member_info['plain_password'];
     $member_info['login_link'] = $login_link;
     $values = array_values($member_info);
     $keys = array_map('swpm_enclose_var', array_keys($member_info));
     $body = html_entity_decode($body);
     $body = str_replace($keys, $values, $body);
     $email = sanitize_email(filter_input(INPUT_POST, 'email', FILTER_UNSAFE_RAW));
     wp_mail(trim($email), $subject, $body, $headers);
     SwpmLog::log_simple_debug('Member notification email sent to: ' . $email, true);
     if ($settings->get_value('enable-admin-notification-after-reg')) {
         $to_email_address = $settings->get_value('admin-notification-email');
         $headers = 'From: ' . $from_address . "\r\n";
         $subject = "Notification of New Member Registration";
         $body = "A new member has registered. The following email was sent to the member." . "\n\n-------Member Email----------\n" . $body . "\n\n------End------\n";
         $admin_notification = empty($to_email_address) ? $from_address : $to_email_address;
         wp_mail(trim($admin_notification), $subject, $body, $headers);
         SwpmLog::log_simple_debug('Admin notification email sent to: ' . $admin_notification, true);
     }
     return true;
 }
 protected function send_reg_email()
 {
     global $wpdb;
     if (empty($this->member_info)) {
         return false;
     }
     $member_info = $this->member_info;
     $settings = SwpmSettings::get_instance();
     $subject = $settings->get_value('reg-complete-mail-subject');
     $body = $settings->get_value('reg-complete-mail-body');
     $from_address = $settings->get_value('email-from');
     $login_link = $settings->get_value('login-page-url');
     $headers = 'From: ' . $from_address . "\r\n";
     $member_info['membership_level_name'] = SwpmPermission::get_instance($member_info['membership_level'])->get('alias');
     $member_info['password'] = $member_info['plain_password'];
     $member_info['login_link'] = $login_link;
     $values = array_values($member_info);
     $keys = array_map('swpm_enclose_var', array_keys($member_info));
     $body = html_entity_decode($body);
     $body = str_replace($keys, $values, $body);
     $swpm_user = SwpmMemberUtils::get_user_by_user_name($member_info['user_name']);
     $member_id = $swpm_user->member_id;
     $body = SwpmMiscUtils::replace_dynamic_tags($body, $member_id);
     //Do the standard merge var replacement.
     $email = sanitize_email(filter_input(INPUT_POST, 'email', FILTER_UNSAFE_RAW));
     //Send notification email to the member
     wp_mail(trim($email), $subject, $body, $headers);
     SwpmLog::log_simple_debug('Member notification email sent to: ' . $email, true);
     if ($settings->get_value('enable-admin-notification-after-reg')) {
         //Send notification email to the site admin
         $admin_notification = $settings->get_value('admin-notification-email');
         $admin_notification = empty($admin_notification) ? $from_address : $admin_notification;
         $notify_emails_array = explode(",", $admin_notification);
         $headers = 'From: ' . $from_address . "\r\n";
         $subject = "Notification of New Member Registration";
         $admin_notify_body = $settings->get_value('reg-complete-mail-body-admin');
         if (empty($admin_notify_body)) {
             $admin_notify_body = "A new member has completed the registration.\n\n" . "Username: {user_name}\n" . "Email: {email}\n\n" . "Please login to the admin dashboard to view details of this user.\n\n" . "You can customize this email message from the Email Settings menu of the plugin.\n\n" . "Thank You";
         }
         $admin_notify_body = SwpmMiscUtils::replace_dynamic_tags($admin_notify_body, $member_id);
         //Do the standard merge var replacement.
         foreach ($notify_emails_array as $to_email) {
             $to_email = trim($to_email);
             wp_mail($to_email, $subject, $admin_notify_body, $headers);
             SwpmLog::log_simple_debug('Admin notification email sent to: ' . $to_email, true);
         }
     }
     return true;
 }
function swpm_alr_do_after_login_redirection()
{
    if (class_exists('BLog')) {
        SwpmLog::log_simple_debug("After login redirection addon. Checking if member need to be redirected.", true);
    }
    $auth = SwpmAuth::get_instance();
    if ($auth->is_logged_in()) {
        $level = $auth->get('membership_level');
        $level_id = $level;
        $key = 'swpm_alr_after_login_page_field';
        $after_login_page_url = SwpmMembershipLevelCustom::get_value_by_key($level_id, $key);
        if (!empty($after_login_page_url)) {
            wp_redirect($after_login_page_url);
            exit;
        }
    }
}
 public function delete_pending_account()
 {
     global $wpdb;
     $interval = SwpmSettings::get_instance()->get_value('delete-pending-account');
     if (empty($interval)) {
         return;
     }
     for ($counter = 0;; $counter += 100) {
         $query = $wpdb->prepare("SELECT member_id\n                                     FROM \n                                        {$wpdb->prefix}swpm_members_tbl \n                                    WHERE account_state='pending' \n                                         AND subscription_starts < DATE_SUB(NOW(), INTERVAL %d MONTH) LIMIT %d, 100", $interval, $counter);
         $results = $wpdb->get_results($query);
         if (empty($results)) {
             break;
         }
         $to_delete = array();
         foreach ($results as $result) {
             $to_delete[] = $result->member_id;
         }
         if (count($to_delete) > 0) {
             SwpmLog::log_simple_debug("Auto deleting pending account.", true);
             $query = "DELETE FROM {$wpdb->prefix}swpm_members_tbl \n                          WHERE member_id IN (" . implode(',', $to_delete) . ")";
             $wpdb->query($query);
         }
     }
 }
 public function handle_stripe_ipn()
 {
     SwpmLog::log_simple_debug("Stripe Buy Now IPN received. Processing request...", true);
     //SwpmLog::log_simple_debug(print_r($_REQUEST, true), true);//Useful for debugging purpose
     //Include the Stripe library.
     include SIMPLE_WP_MEMBERSHIP_PATH . 'lib/stripe-gateway/init.php';
     //Read and sanitize the request parameters.
     $button_id = sanitize_text_field($_REQUEST['item_number']);
     $button_id = absint($button_id);
     $button_title = sanitize_text_field($_REQUEST['item_name']);
     $payment_amount = sanitize_text_field($_REQUEST['item_price']);
     $price_in_cents = $payment_amount * 100;
     //The amount (in cents). This value is used in Stripe API.
     $currency_code = sanitize_text_field($_REQUEST['currency_code']);
     $stripe_token = sanitize_text_field($_POST['stripeToken']);
     $stripe_token_type = sanitize_text_field($_POST['stripeTokenType']);
     $stripe_email = sanitize_email($_POST['stripeEmail']);
     //Retrieve the CPT for this button
     $button_cpt = get_post($button_id);
     if (!$button_cpt) {
         //Fatal error. Could not find this payment button post object.
         SwpmLog::log_simple_debug("Fatal Error! Failed to retrieve the payment button post object for the given button ID: " . $button_id, false);
         wp_die("Fatal Error! Payment button (ID: " . $button_id . ") does not exist. This request will fail.");
     }
     $membership_level_id = get_post_meta($button_id, 'membership_level_id', true);
     //Validate and verify some of the main values.
     $true_payment_amount = get_post_meta($button_id, 'payment_amount', true);
     if ($payment_amount != $true_payment_amount) {
         //Fatal error. Payment amount may have been tampered with.
         $error_msg = 'Fatal Error! Received payment amount (' . $payment_amount . ') does not match with the original amount (' . $true_payment_amount . ')';
         SwpmLog::log_simple_debug($error_msg, false);
         wp_die($error_msg);
     }
     $true_currency_code = get_post_meta($button_id, 'payment_currency', true);
     if ($currency_code != $true_currency_code) {
         //Fatal error. Currency code may have been tampered with.
         $error_msg = 'Fatal Error! Received currency code (' . $currency_code . ') does not match with the original code (' . $true_currency_code . ')';
         SwpmLog::log_simple_debug($error_msg, false);
         wp_die($error_msg);
     }
     //Validation passed. Go ahead with the charge.
     //Sandbox and other settings
     $settings = SwpmSettings::get_instance();
     $sandbox_enabled = $settings->get_value('enable-sandbox-testing');
     if ($sandbox_enabled) {
         SwpmLog::log_simple_debug("Sandbox payment mode is enabled. Using test API key details.", true);
         $secret_key = get_post_meta($button_id, 'stripe_test_secret_key', true);
         //Use sandbox API key
     } else {
         $secret_key = get_post_meta($button_id, 'stripe_live_secret_key', true);
         //Use live API key
     }
     //Set secret API key in the Stripe library
     \Stripe\Stripe::setApiKey($secret_key);
     // Get the credit card details submitted by the form
     $token = $stripe_token;
     // Create the charge on Stripe's servers - this will charge the user's card
     try {
         $charge = \Stripe\Charge::create(array("amount" => $price_in_cents, "currency" => strtolower($currency_code), "source" => $token, "description" => $button_title));
     } catch (\Stripe\Error\Card $e) {
         // The card has been declined
         SwpmLog::log_simple_debug("Stripe Charge Error! The card has been declined. " . $e->getMessage(), false);
         $body = $e->getJsonBody();
         $error = $body['error'];
         $error_string = print_r($error, true);
         SwpmLog::log_simple_debug("Error details: " . $error_string, false);
         wp_die("Stripe Charge Error! Card charge has been declined. " . $e->getMessage() . $error_string);
     }
     //Everything went ahead smoothly with the charge.
     SwpmLog::log_simple_debug("Stripe Buy Now charge successful.", true);
     //Grab the charge ID and set it as the transaction ID.
     $txn_id = $charge->id;
     //$charge->balance_transaction;
     //The charge ID can be used to retrieve the transaction details using hte following call.
     //\Stripe\Charge::retrieve($charge->id);
     $custom = sanitize_text_field($_REQUEST['custom']);
     $custom_var = SwpmTransactions::parse_custom_var($custom);
     $swpm_id = isset($custom_var['swpm_id']) ? $custom_var['swpm_id'] : '';
     //Create the $ipn_data array.
     $ipn_data = array();
     $ipn_data['mc_gross'] = $payment_amount;
     $ipn_data['first_name'] = '';
     $ipn_data['last_name'] = '';
     $ipn_data['payer_email'] = $stripe_email;
     $ipn_data['membership_level'] = $membership_level_id;
     $ipn_data['txn_id'] = $txn_id;
     $ipn_data['subscr_id'] = $txn_id;
     $ipn_data['swpm_id'] = $swpm_id;
     $ipn_data['ip'] = $custom_var['user_ip'];
     $ipn_data['custom'] = $custom;
     $ipn_data['gateway'] = 'stripe';
     $ipn_data['status'] = 'completed';
     $ipn_data['address_street'] = '';
     $ipn_data['address_city'] = '';
     $ipn_data['address_state'] = '';
     $ipn_data['address_zipcode'] = '';
     $ipn_data['country'] = '';
     //Handle the membership signup related tasks.
     swpm_handle_subsc_signup_stand_alone($ipn_data, $membership_level_id, $txn_id, $swpm_id);
     //Save the transaction record
     SwpmTransactions::save_txn_record($ipn_data);
     SwpmLog::log_simple_debug('Transaction data saved.', true);
     //Trigger the stripe IPN processed action hook (so other plugins can can listen for this event).
     do_action('swpm_stripe_ipn_processed', $ipn_data);
     do_action('swpm_payment_ipn_processed', $ipn_data);
     //Redirect the user to the return URL (or to the homepage if a return URL is not specified for this payment button).
     $return_url = get_post_meta($button_id, 'return_url', true);
     if (empty($return_url)) {
         $return_url = SIMPLE_WP_MEMBERSHIP_SITE_HOME_URL;
     }
     SwpmLog::log_simple_debug("Redirecting customer to: " . $return_url, true);
     SwpmLog::log_simple_debug("End of Stripe Buy Now IPN processing.", true, true);
     SwpmMiscUtils::redirect_to_url($return_url);
 }
 public function reset_password($email)
 {
     $email = sanitize_email($email);
     if (!is_email($email)) {
         $message = '<div class="swpm-reset-pw-error">' . SwpmUtils::_("Email address not valid.") . '</div>';
         $message = array('succeeded' => false, 'message' => $message);
         SwpmTransfer::get_instance()->set('status', $message);
         return;
     }
     global $wpdb;
     $query = 'SELECT member_id,user_name,first_name, last_name FROM ' . $wpdb->prefix . 'swpm_members_tbl ' . ' WHERE email = %s';
     $user = $wpdb->get_row($wpdb->prepare($query, $email));
     if (empty($user)) {
         $message = '<div class="swpm-reset-pw-error">' . SwpmUtils::_("No user found with that email address.") . '</div>';
         $message .= '<div class="swpm-reset-pw-error-email">' . SwpmUtils::_("Email Address: ") . $email . '</div>';
         $message = array('succeeded' => false, 'message' => $message);
         SwpmTransfer::get_instance()->set('status', $message);
         return;
     }
     $settings = SwpmSettings::get_instance();
     $password = wp_generate_password();
     $password_hash = SwpmUtils::encrypt_password(trim($password));
     //should use $saned??;
     $wpdb->update($wpdb->prefix . "swpm_members_tbl", array('password' => $password_hash), array('member_id' => $user->member_id));
     //Update wp user password
     add_filter('send_password_change_email', array(&$this, 'dont_send_password_change_email'), 1, 3);
     //Stop wordpress from sending a reset password email to admin.
     SwpmUtils::update_wp_user($user->user_name, array('plain_password' => $password));
     $body = $settings->get_value('reset-mail-body');
     $subject = $settings->get_value('reset-mail-subject');
     $search = array('{user_name}', '{first_name}', '{last_name}', '{password}');
     $replace = array($user->user_name, $user->first_name, $user->last_name, $password);
     $body = html_entity_decode($body);
     $body = str_replace($search, $replace, $body);
     $from = $settings->get_value('email-from');
     $headers = "From: " . $from . "\r\n";
     wp_mail($email, $subject, $body, $headers);
     SwpmLog::log_simple_debug("Member password has been reset. Password reset email sent to: " . $email, true);
     $message = '<div class="swpm-reset-pw-success">' . SwpmUtils::_("New password has been sent to your email address.") . '</div>';
     $message .= '<div class="swpm-reset-pw-success-email">' . SwpmUtils::_("Email Address: ") . $email . '</div>';
     $message = array('succeeded' => false, 'message' => $message);
     SwpmTransfer::get_instance()->set('status', $message);
 }
 public function shutdown()
 {
     SwpmLog::writeall();
 }
 public function swpm_general_post_submit_check_callback()
 {
     //Log file reset handler
     if (isset($_REQUEST['swmp_reset_log'])) {
         if (SwpmLog::reset_swmp_log_files()) {
             echo '<div id="message" class="updated fade"><p>Debug log files have been reset!</p></div>';
         } else {
             echo '<div id="message" class="updated fade"><p>Debug log files could not be reset!</p></div>';
         }
     }
     //Show settings updated message
     if (isset($_REQUEST['settings-updated'])) {
         echo '<div id="message" class="updated fade"><p>' . SwpmUtils::_('Settings updated!') . '</p></div>';
     }
 }
 private function validate()
 {
     $auth_cookie_name = is_ssl() ? SIMPLE_WP_MEMBERSHIP_SEC_AUTH : SIMPLE_WP_MEMBERSHIP_AUTH;
     if (!isset($_COOKIE[$auth_cookie_name]) || empty($_COOKIE[$auth_cookie_name])) {
         return false;
     }
     $cookie_elements = explode('|', $_COOKIE[$auth_cookie_name]);
     if (count($cookie_elements) != 3) {
         return false;
     }
     //SwpmLog::log_auth_debug("validate() - " . $_COOKIE[$auth_cookie_name], true);
     list($username, $expiration, $hmac) = $cookie_elements;
     $expired = $expiration;
     // Allow a grace period for POST and AJAX requests
     if (defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD']) {
         $expired += HOUR_IN_SECONDS;
     }
     // Quick check to see if an honest cookie has expired
     if ($expired < time()) {
         $this->lastStatusMsg = SwpmUtils::_("Session Expired.");
         //do_action('auth_cookie_expired', $cookie_elements);
         SwpmLog::log_auth_debug("validate() - Session Expired", true);
         return false;
     }
     global $wpdb;
     $query = " SELECT * FROM " . $wpdb->prefix . "swpm_members_tbl WHERE user_name = %s";
     $user = $wpdb->get_row($wpdb->prepare($query, $username));
     if (empty($user)) {
         $this->lastStatusMsg = SwpmUtils::_("Invalid User Name");
         return false;
     }
     $pass_frag = substr($user->password, 8, 4);
     $key = SwpmAuth::b_hash($username . $pass_frag . '|' . $expiration);
     $hash = hash_hmac('md5', $username . '|' . $expiration, $key);
     if ($hmac != $hash) {
         $this->lastStatusMsg = SwpmUtils::_("Please login again.");
         SwpmLog::log_auth_debug("validate() - Bad Hash", true);
         return false;
     }
     if ($expiration < time()) {
         $GLOBALS['login_grace_period'] = 1;
     }
     $this->userData = $user;
     return $this->check_constraints();
 }
 function bulk_set_status($members, $status, $notify = false)
 {
     $ids = implode(',', array_map('absint', $members));
     if (empty($ids)) {
         return;
     }
     global $wpdb;
     $query = "UPDATE " . $wpdb->prefix . "swpm_members_tbl " . " SET account_state = '" . $status . "' WHERE member_id in (" . $ids . ")";
     $wpdb->query($query);
     if ($notify) {
         $settings = SwpmSettings::get_instance();
         $emails = $wpdb->get_col("SELECT email FROM " . $wpdb->prefix . "swpm_members_tbl " . " WHERE member_id IN ( {$ids}  ) ");
         $subject = $settings->get_value('bulk-activate-notify-mail-subject');
         if (empty($subject)) {
             $subject = "Account Activated!";
         }
         $body = $settings->get_value('bulk-activate-notify-mail-body');
         if (empty($body)) {
             $body = "Hi, Your account has been activated successfully!";
         }
         $from_address = $settings->get_value('email-from');
         $to_email_list = implode(',', $emails);
         $headers = 'From: ' . $from_address . "\r\n";
         $headers .= 'bcc: ' . $to_email_list . "\r\n";
         wp_mail(array(), $subject, $body, $headers);
         SwpmLog::log_simple_debug("Bulk activation email notification sent. Activation email sent to the following email: " . $to_email_list, true);
     }
 }
 function debug_log($message, $success, $end = false)
 {
     SwpmLog::log_simple_debug($message, $success, $end);
 }
function swpm_do_mailchimp_signup($args)
{
    $first_name = sanitize_text_field($args['first_name']);
    $last_name = sanitize_text_field($args['last_name']);
    $email = sanitize_email($args['email']);
    $membership_level = sanitize_text_field($args['membership_level']);
    $level_id = $membership_level;
    $key = 'swpm_mailchimp_list_name';
    $mc_list_name = SwpmMembershipLevelCustom::get_value_by_key($level_id, $key);
    SwpmLog::log_simple_debug("Mailchimp integration addon. After registration hook. Debug data: " . $mc_list_name . "|" . $email . "|" . $first_name . "|" . $last_name, true);
    if (empty($mc_list_name)) {
        //This level has no mailchimp list name specified for it
        return;
    }
    SwpmLog::log_simple_debug("Mailchimp integration - Doing list signup...", true);
    include_once 'lib/SWPM_MCAPI.class.php';
    $swpm_mc_settings = get_option('swpm_mailchimp_settings');
    $api_key = $swpm_mc_settings['mc_api_key'];
    if (empty($api_key)) {
        SwpmLog::log_simple_debug("MailChimp API Key value is not saved in the settings. Go to MailChimp settings and enter the API Key.", false);
        return;
    }
    $api = new SWPM_MCAPI($api_key);
    $target_list_name = $mc_list_name;
    $list_filter = array();
    $list_filter['list_name'] = $target_list_name;
    $all_lists = $api->lists($list_filter);
    $lists_data = $all_lists['data'];
    $found_match = false;
    foreach ($lists_data as $list) {
        SwpmLog::log_simple_debug("Checking list name : " . $list['name'], true);
        if (strtolower($list['name']) == strtolower($target_list_name)) {
            $found_match = true;
            $list_id = $list['id'];
            SwpmLog::log_simple_debug("Found a match for the list name on MailChimp. List ID :" . $list_id, true);
        }
    }
    if (!$found_match) {
        SwpmLog::log_simple_debug("Could not find a list name in your MailChimp account that matches with the target list name: " . $target_list_name, false);
        return;
    }
    SwpmLog::log_simple_debug("List ID to subscribe to:" . $list_id, true);
    //Create the merge_vars data
    $merge_vars = array('FNAME' => $first_name, 'LNAME' => $last_name, 'INTERESTS' => '');
    //$signup_date_field_name = $swpm_mc_settings['mc_signup_date'];//get from settings if needed;
    //if (!empty($signup_date_field_name)) {//Add the signup date
    //    $todays_date = date("Y-m-d");
    //    $merge_vars[$signup_date_field_name] = $todays_date;
    //}
    //if (count($pieces) > 2) {//Add the interest groups data to the merge_vars
    //    $group_data = array(array('name' => $interest_group_name, 'groups' => $interest_groups));
    //    $merge_vars['GROUPINGS'] = $group_data;
    //}
    $retval = $api->listSubscribe($list_id, $email, $merge_vars);
    if ($api->errorCode) {
        SwpmLog::log_simple_debug("Unable to load listSubscribe()!", false);
        SwpmLog::log_simple_debug("\tCode=" . $api->errorCode, false);
        SwpmLog::log_simple_debug("\tMsg=" . $api->errorMessage, false);
    } else {
        SwpmLog::log_simple_debug("MailChimp Signup was successful.", true);
    }
}