public function edit_level($id)
 {
     //Check we are on the admin end and user has management permission
     SwpmMiscUtils::check_user_permission_and_is_admin('membership level edit');
     //Check nonce
     if (!isset($_POST['_wpnonce_edit_swpmlevel_admin_end']) || !wp_verify_nonce($_POST['_wpnonce_edit_swpmlevel_admin_end'], 'edit_swpmlevel_admin_end')) {
         //Nonce check failed.
         wp_die(SwpmUtils::_("Error! Nonce verification failed for membership level edit from admin end."));
     }
     global $wpdb;
     $query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "swpm_membership_tbl WHERE id = %d", $id);
     $level = $wpdb->get_row($query, ARRAY_A);
     $form = new SwpmLevelForm($level);
     if ($form->is_valid()) {
         $wpdb->update($wpdb->prefix . "swpm_membership_tbl", $form->get_sanitized(), array('id' => $id));
         //@todo meta table and collect all relevant info and pass as argument
         $custom = apply_filters('swpm_admin_edit_membership_level', array(), $id);
         $this->save_custom_fields($id, $custom);
         $message = array('succeeded' => true, 'message' => '<p>' . SwpmUtils::_('Membership Level Updated Successfully.') . '</p>');
         SwpmTransfer::get_instance()->set('status', $message);
         wp_redirect('admin.php?page=simple_wp_membership_levels');
         exit(0);
     }
     $message = array('succeeded' => false, 'message' => SwpmUtils::_('Please correct the following:'), 'extra' => $form->get_errors());
     SwpmTransfer::get_instance()->set('status', $message);
 }
 public function edit_admin_end($id)
 {
     //Check we are on the admin end and user has management permission
     SwpmMiscUtils::check_user_permission_and_is_admin('member edit by admin');
     //Check nonce
     if (!isset($_POST['_wpnonce_edit_swpmuser_admin_end']) || !wp_verify_nonce($_POST['_wpnonce_edit_swpmuser_admin_end'], 'edit_swpmuser_admin_end')) {
         //Nonce check failed.
         wp_die(SwpmUtils::_("Error! Nonce verification failed for user edit from admin end."));
     }
     global $wpdb;
     $query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "swpm_members_tbl WHERE member_id = %d", $id);
     $member = $wpdb->get_row($query, ARRAY_A);
     $email_address = $member['email'];
     $user_name = $member['user_name'];
     unset($member['member_id']);
     unset($member['user_name']);
     $form = new SwpmForm($member);
     if ($form->is_valid()) {
         $member = $form->get_sanitized();
         $plain_password = isset($member['plain_password']) ? $member['plain_password'] : "";
         SwpmUtils::update_wp_user($user_name, $member);
         unset($member['plain_password']);
         $wpdb->update($wpdb->prefix . "swpm_members_tbl", $member, array('member_id' => $id));
         $message = array('succeeded' => true, 'message' => '<p>Member profile updated successfully.</p>');
         $error = apply_filters('swpm_admin_edit_custom_fields', array(), $member + array('member_id' => $id));
         if (!empty($error)) {
             $message = array('succeeded' => false, 'message' => SwpmUtils::_('Please correct the following:'), 'extra' => $error);
             SwpmTransfer::get_instance()->set('status', $message);
             return;
         }
         SwpmTransfer::get_instance()->set('status', $message);
         $send_notification = filter_input(INPUT_POST, 'account_status_change');
         if (!empty($send_notification)) {
             $settings = SwpmSettings::get_instance();
             $from_address = $settings->get_value('email-from');
             $headers = 'From: ' . $from_address . "\r\n";
             $subject = filter_input(INPUT_POST, 'notificationmailhead');
             $body = filter_input(INPUT_POST, 'notificationmailbody');
             $settings->set_value('account-change-email-body', $body)->set_value('account-change-email-subject', $subject)->save();
             $member['login_link'] = $settings->get_value('login-page-url');
             $member['user_name'] = $user_name;
             $member['password'] = empty($plain_password) ? SwpmUtils::_("Your current password") : $plain_password;
             $values = array_values($member);
             $keys = array_map('swpm_enclose_var', array_keys($member));
             $body = html_entity_decode(str_replace($keys, $values, $body));
             wp_mail($email_address, $subject, $body, $headers);
         }
         wp_redirect('admin.php?page=simple_wp_membership');
         exit(0);
     }
     $message = array('succeeded' => false, 'message' => SwpmUtils::_('Please correct the following:'), 'extra' => $form->get_errors());
     SwpmTransfer::get_instance()->set('status', $message);
 }
 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;
 }
 public static function update_category_list()
 {
     //Check we are on the admin end and user has management permission
     SwpmMiscUtils::check_user_permission_and_is_admin('category protection update');
     $selected = filter_input(INPUT_POST, 'membership_level_id');
     $selected_level_id = empty($selected) ? 1 : $selected;
     $category = $selected_level_id == 1 ? SwpmProtection::get_instance() : SwpmPermission::get_instance($selected_level_id);
     $args = array('ids' => array('filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY));
     $filtered = filter_input_array(INPUT_POST, $args);
     $ids = $filtered['ids'];
     $args = array('ids_in_page' => array('filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY));
     $filtered = filter_input_array(INPUT_POST, $args);
     $ids_in_page = $filtered['ids_in_page'];
     $category->remove($ids_in_page, 'category')->apply($ids, 'category')->save();
     $message = array('succeeded' => true, 'message' => '<p>' . SwpmUtils::_('Category protection updated!') . '</p>');
     SwpmTransfer::get_instance()->set('status', $message);
 }
 public static function initdb()
 {
     $settings = SwpmSettings::get_instance();
     $installed_version = $settings->get_value('swpm-active-version');
     //Set other default settings values
     $reg_prompt_email_subject = "Complete your registration";
     $reg_prompt_email_body = "Dear {first_name} {last_name}" . "\n\nThank you for joining us!" . "\n\nPlease complete your registration by visiting the following link:" . "\n\n{reg_link}" . "\n\nThank You";
     $reg_email_subject = "Your registration is complete";
     $reg_email_body = "Dear {first_name} {last_name}\n\n" . "Your registration is now complete!\n\n" . "Registration details:\n" . "Username: {user_name}\n" . "Password: {password}\n\n" . "Please login to the member area at the following URL:\n\n" . "{login_link}\n\n" . "Thank You";
     $upgrade_email_subject = "Subject for email sent after account upgrade";
     $upgrade_email_body = "Dear {first_name} {last_name}" . "\n\nYour Account Has Been Upgraded." . "\n\nThank You";
     $reset_email_subject = get_bloginfo('name') . ": New Password";
     $reset_email_body = "Dear {first_name} {last_name}" . "\n\nHere is your new password:"******"\n\nUsername: {user_name}" . "\nPassword: {password}" . "\n\nYou can change the password from the edit profile section of the site (after you log into the site)" . "\n\nThank You";
     $status_change_email_subject = "Account Updated!";
     $status_change_email_body = "Dear {first_name} {last_name}," . "\n\nYour account status has been updated!" . " Please login to the member area at the following URL:" . "\n\n {login_link}" . "\n\nThank You";
     $bulk_activate_email_subject = "Account Activated!";
     $bulk_activate_email_body = "Hi," . "\n\nYour account has been activated!" . "\n\nYou can now login to the member area." . "\n\nThank You";
     if (empty($installed_version)) {
         //Do fresh install tasks
         //Create the mandatory pages (if they are not there)
         SwpmMiscUtils::create_mandatory_wp_pages();
         //End of page creation
         $settings->set_value('reg-complete-mail-subject', stripslashes($reg_email_subject))->set_value('reg-complete-mail-body', stripslashes($reg_email_body))->set_value('reg-prompt-complete-mail-subject', stripslashes($reg_prompt_email_subject))->set_value('reg-prompt-complete-mail-body', stripslashes($reg_prompt_email_body))->set_value('upgrade-complete-mail-subject', stripslashes($upgrade_email_subject))->set_value('upgrade-complete-mail-body', stripslashes($upgrade_email_body))->set_value('reset-mail-subject', stripslashes($reset_email_subject))->set_value('reset-mail-body', stripslashes($reset_email_body))->set_value('account-change-email-subject', stripslashes($status_change_email_subject))->set_value('account-change-email-body', stripslashes($status_change_email_body))->set_value('email-from', trim(get_option('admin_email')));
         $settings->set_value('bulk-activate-notify-mail-subject', stripslashes($bulk_activate_email_subject));
         $settings->set_value('bulk-activate-notify-mail-body', stripslashes($bulk_activate_email_body));
     }
     if (version_compare($installed_version, SIMPLE_WP_MEMBERSHIP_VER) == -1) {
         //Do upgrade tasks
     }
     $settings->set_value('swpm-active-version', SIMPLE_WP_MEMBERSHIP_VER)->save();
     //save everything.
 }
 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);
 }
 function delete_level()
 {
     global $wpdb;
     if (isset($_REQUEST['id'])) {
         //Check we are on the admin end and user has management permission
         SwpmMiscUtils::check_user_permission_and_is_admin('membership level delete');
         //Check nonce
         if (!isset($_REQUEST['delete_swpmlevel_nonce']) || !wp_verify_nonce($_REQUEST['delete_swpmlevel_nonce'], 'nonce_delete_swpmlevel_admin_end')) {
             //Nonce check failed.
             wp_die(SwpmUtils::_("Error! Nonce verification failed for membership level delete from admin end."));
         }
         $id = sanitize_text_field($_REQUEST['id']);
         $id = absint($id);
         $query = $wpdb->prepare("DELETE FROM " . $wpdb->prefix . "swpm_membership_tbl WHERE id = %d", $id);
         $wpdb->query($query);
         echo '<div id="message" class="updated fade"><p>Selected record deleted successfully!</p></div>';
     }
 }
function swpm_save_new_pp_subscription_button_data()
{
    if (isset($_REQUEST['swpm_pp_subscription_save_submit'])) {
        //This is a PayPal subscription button save event. Process the submission.
        $button_id = wp_insert_post(array('post_title' => sanitize_text_field($_REQUEST['button_name']), 'post_type' => 'swpm_payment_button', 'post_content' => '', 'post_status' => 'publish'));
        $button_type = sanitize_text_field($_REQUEST['button_type']);
        add_post_meta($button_id, 'button_type', $button_type);
        add_post_meta($button_id, 'membership_level_id', sanitize_text_field($_REQUEST['membership_level_id']));
        add_post_meta($button_id, 'payment_currency', sanitize_text_field($_REQUEST['payment_currency']));
        add_post_meta($button_id, 'return_url', trim(sanitize_text_field($_REQUEST['return_url'])));
        add_post_meta($button_id, 'paypal_email', trim(sanitize_email($_REQUEST['paypal_email'])));
        add_post_meta($button_id, 'button_image_url', trim(sanitize_text_field($_REQUEST['button_image_url'])));
        //Subscription billing details
        add_post_meta($button_id, 'billing_amount', sanitize_text_field($_REQUEST['billing_amount']));
        add_post_meta($button_id, 'billing_cycle', sanitize_text_field($_REQUEST['billing_cycle']));
        add_post_meta($button_id, 'billing_cycle_term', sanitize_text_field($_REQUEST['billing_cycle_term']));
        add_post_meta($button_id, 'billing_cycle_count', sanitize_text_field($_REQUEST['billing_cycle_count']));
        add_post_meta($button_id, 'billing_reattempt', isset($_REQUEST['billing_reattempt']) ? '1' : '');
        //Trial billing details
        add_post_meta($button_id, 'trial_billing_amount', sanitize_text_field($_REQUEST['trial_billing_amount']));
        add_post_meta($button_id, 'trial_billing_cycle', sanitize_text_field($_REQUEST['trial_billing_cycle']));
        add_post_meta($button_id, 'trial_billing_cycle_term', sanitize_text_field($_REQUEST['trial_billing_cycle_term']));
        //Redirect to the edit interface of this button with $button_id
        $url = admin_url() . 'admin.php?page=simple_wp_membership_payments&tab=edit_button&button_id=' . $button_id . '&button_type=' . $button_type;
        SwpmMiscUtils::redirect_to_url($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');
     $body = html_entity_decode($body);
     $additional_args = array('password' => $password);
     $body = SwpmMiscUtils::replace_dynamic_tags($body, $user->member_id, $additional_args);
     $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);
 }
function swpm_handle_subsc_signup_stand_alone($ipn_data, $subsc_ref, $unique_ref, $swpm_id = '')
{
    global $wpdb;
    $settings = SwpmSettings::get_instance();
    $members_table_name = $wpdb->prefix . "swpm_members_tbl";
    $membership_level_table = $wpdb->prefix . "swpm_membership_tbl";
    $membership_level = $subsc_ref;
    $subscr_id = $unique_ref;
    swpm_debug_log_subsc("swpm_handle_subsc_signup_stand_alone(). Custom value: " . $ipn_data['custom'] . ", Unique reference: " . $unique_ref, true);
    $custom_vars = parse_str($ipn_data['custom']);
    if (empty($swpm_id)) {
        //Lets try to find an existing user profile for this payment
        $email = $ipn_data['payer_email'];
        $query_db = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$members_table_name} WHERE email = %s", $email), OBJECT);
        if (!$query_db) {
            //try to retrieve the member details based on the unique_ref
            swpm_debug_log_subsc("Could not find any record using the given email address (" . $email . "). Attempting to query database using the unique reference: " . $unique_ref, true);
            if (!empty($unique_ref)) {
                $query_db = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$members_table_name} WHERE subscr_id = %s", $unique_ref), OBJECT);
                if ($query_db) {
                    $swpm_id = $query_db->member_id;
                    swpm_debug_log_subsc("Found a match in the member database using unique reference. Member ID: " . $swpm_id, true);
                } else {
                    swpm_debug_log_subsc("Did not find a match for an existing member profile for the given reference. This must me a new payment from a new member.", true);
                }
            } else {
                swpm_debug_log_subsc("Unique reference is missing in the notification so we have to assume that this is not a payment for an existing member.", true);
            }
        } else {
            $swpm_id = $query_db->member_id;
            swpm_debug_log_subsc("Found a match in the member database. Member ID: " . $swpm_id, true);
        }
    }
    if (!empty($swpm_id)) {
        //This is payment from an existing member/user. Update the existing member account
        swpm_debug_log_subsc("Modifying the existing membership profile... Member ID: " . $swpm_id, true);
        //Upgrade the member account
        $account_state = 'active';
        //This is renewal or upgrade of a previously active account. So the status should be set to active
        $subscription_starts = date("Y-m-d");
        $resultset = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$members_table_name} where member_id=%d", $swpm_id), OBJECT);
        if (!$resultset) {
            swpm_debug_log_subsc("ERROR! Could not find a member account record for the given Member ID: " . $swpm_id, false);
            return;
        }
        $old_membership_level = $resultset->membership_level;
        swpm_debug_log_subsc("Upgrading the current membership level (" . $old_membership_level . ") of this member to the newly paid level (" . $membership_level . ")", true);
        $updatedb = $wpdb->prepare("UPDATE {$members_table_name} SET account_state=%s, membership_level=%d,subscription_starts=%s,subscr_id=%s WHERE member_id=%d", $account_state, $membership_level, $subscription_starts, $subscr_id, $swpm_id);
        $results = $wpdb->query($updatedb);
        do_action('swpm_membership_changed', array('member_id' => $swpm_id, 'from_level' => $old_membership_level, 'to_level' => $membership_level));
        //Set Email details for the account upgrade notification
        $email = $ipn_data['payer_email'];
        $subject = $settings->get_value('upgrade-complete-mail-subject');
        if (empty($subject)) {
            $subject = "Member Account Upgraded";
        }
        $body = $settings->get_value('upgrade-complete-mail-body');
        if (empty($body)) {
            $body = "Your account has been upgraded successfully";
        }
        $from_address = $settings->get_value('email-from');
        $additional_args = array();
        $email_body = SwpmMiscUtils::replace_dynamic_tags($body, $swpm_id, $additional_args);
        $headers = 'From: ' . $from_address . "\r\n";
    } else {
        // create new member account
        $default_account_status = $settings->get_value('default-account-status', 'active');
        $data = array();
        $data['user_name'] = '';
        $data['password'] = '';
        $data['first_name'] = $ipn_data['first_name'];
        $data['last_name'] = $ipn_data['last_name'];
        $data['email'] = $ipn_data['payer_email'];
        $data['membership_level'] = $membership_level;
        $data['subscr_id'] = $unique_ref;
        $data['gender'] = 'not specified';
        swpm_debug_log_subsc("Creating new member account. Membership level ID: " . $membership_level, true);
        $data['address_street'] = $ipn_data['address_street'];
        $data['address_city'] = $ipn_data['address_city'];
        $data['address_state'] = $ipn_data['address_state'];
        $data['address_zipcode'] = isset($ipn_data['address_zip']) ? $ipn_data['address_zip'] : '';
        $data['country'] = isset($ipn_data['address_country']) ? $ipn_data['address_country'] : '';
        $data['member_since'] = $data['subscription_starts'] = $data['last_accessed'] = date("Y-m-d");
        $data['account_state'] = $default_account_status;
        $reg_code = uniqid();
        $md5_code = md5($reg_code);
        $data['reg_code'] = $md5_code;
        $data['referrer'] = $data['extra_info'] = $data['txn_id'] = '';
        $data['subscr_id'] = $subscr_id;
        $data['last_accessed_from_ip'] = isset($user_ip) ? $user_ip : '';
        //Save the users IP address
        $data = array_filter($data);
        //Remove any null values.
        $wpdb->insert($members_table_name, $data);
        //Create the member record
        $results = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$members_table_name} where subscr_id=%s and reg_code=%s", $subscr_id, $md5_code), OBJECT);
        $id = $results->member_id;
        //Alternatively use $wpdb->insert_id;
        if (empty($id)) {
            swpm_debug_log_subsc("Error! Failed to insert a new member record. This request will fail.", false);
            return;
        }
        $separator = '?';
        $url = $settings->get_value('registration-page-url');
        if (strpos($url, '?') !== false) {
            $separator = '&';
        }
        $reg_url = $url . $separator . 'member_id=' . $id . '&code=' . $md5_code;
        swpm_debug_log_subsc("Member signup URL: " . $reg_url, true);
        $subject = $settings->get_value('reg-prompt-complete-mail-subject');
        if (empty($subject)) {
            $subject = "Please complete your registration";
        }
        $body = $settings->get_value('reg-prompt-complete-mail-body');
        if (empty($body)) {
            $body = "Please use the following link to complete your registration. \n {reg_link}";
        }
        $from_address = $settings->get_value('email-from');
        $body = html_entity_decode($body);
        $additional_args = array('reg_link' => $reg_url);
        $email_body = SwpmMiscUtils::replace_dynamic_tags($body, $id, $additional_args);
        $headers = 'From: ' . $from_address . "\r\n";
    }
    wp_mail($email, $subject, $email_body, $headers);
    swpm_debug_log_subsc("Member signup/upgrade completion email successfully sent to: " . $email, true);
}
function swpm_save_new_pp_buy_now_button_data()
{
    if (isset($_REQUEST['swpm_pp_buy_now_save_submit'])) {
        //This is a PayPal buy now button save event. Process the submission.
        //TODO - Do some extra validation check?
        //Save the button data
        $button_id = wp_insert_post(array('post_title' => sanitize_text_field($_REQUEST['button_name']), 'post_type' => 'swpm_payment_button', 'post_content' => '', 'post_status' => 'publish'));
        $button_type = sanitize_text_field($_REQUEST['button_type']);
        add_post_meta($button_id, 'button_type', $button_type);
        add_post_meta($button_id, 'membership_level_id', sanitize_text_field($_REQUEST['membership_level_id']));
        add_post_meta($button_id, 'payment_amount', trim(sanitize_text_field($_REQUEST['payment_amount'])));
        add_post_meta($button_id, 'payment_currency', sanitize_text_field($_REQUEST['payment_currency']));
        add_post_meta($button_id, 'return_url', trim(sanitize_text_field($_REQUEST['return_url'])));
        add_post_meta($button_id, 'paypal_email', trim(sanitize_email($_REQUEST['paypal_email'])));
        add_post_meta($button_id, 'button_image_url', trim(sanitize_text_field($_REQUEST['button_image_url'])));
        //Redirect to the edit interface of this button with $button_id
        //$url = admin_url() . 'admin.php?page=simple_wp_membership_payments&tab=edit_button&button_id=' . $button_id . '&button_type=' . $button_type;
        //Redirect to the manage payment buttons interface
        $url = admin_url() . 'admin.php?page=simple_wp_membership_payments&tab=payment_buttons';
        SwpmMiscUtils::redirect_to_url($url);
    }
}
 public static function is_current_url_a_system_page()
 {
     $current_page_url = SwpmMiscUtils::get_current_page_url();
     //Check if the current page is the membership renewal page.
     $renewal_url = SwpmSettings::get_instance()->get_value('renewal-page-url');
     if (empty($renewal_url)) {
         return false;
     }
     if (SwpmMiscUtils::compare_url($renewal_url, $current_page_url)) {
         return true;
     }
     //Check if the current page is the membership logn page.
     $login_page_url = SwpmSettings::get_instance()->get_value('login-page-url');
     if (empty($login_page_url)) {
         return false;
     }
     if (SwpmMiscUtils::compare_url($login_page_url, $current_page_url)) {
         return true;
     }
     //Check if the current page is the membership join page.
     $registration_page_url = SwpmSettings::get_instance()->get_value('registration-page-url');
     if (empty($registration_page_url)) {
         return false;
     }
     if (SwpmMiscUtils::compare_url($registration_page_url, $current_page_url)) {
         return true;
     }
     return false;
 }
function swpm_alr_append_query_arg_if_applicable($login_url)
{
    //Check if the redirect to last page settings is enabled.
    $swpm_alr_settings = get_option('swpm_alr_settings');
    if (empty($swpm_alr_settings['redirect_to_last_page_enabled'])) {
        $swpm_alr_settings['redirect_to_last_page_enabled'] = '';
    }
    if ($swpm_alr_settings['redirect_to_last_page_enabled'] != '1') {
        //The redirect to last page option is disabled. No need to add the query arg.
        return $login_url;
    }
    //The feature is enabled. Lets add the necessary query arg to the login url.
    $current_url = SwpmMiscUtils::get_current_page_url();
    if (!empty($current_url)) {
        //Add this URL to the redirect to query arg.
        $current_url = urlencode($current_url);
        $login_url = add_query_arg('swpm_redirect_to', $current_url, $login_url);
    }
    return $login_url;
}
 public function do_admin_notices()
 {
     $this->notices();
     //Show any execution specific notices in the admin interface.
     //Show any other general warnings/notices to the admin.
     if (SwpmMiscUtils::is_swpm_admin_page()) {
         //we are in an admin page for SWPM plugin.
         $msg = '';
         //Show notice if running in sandbox mode.
         $settings = SwpmSettings::get_instance();
         $sandbox_enabled = $settings->get_value('enable-sandbox-testing');
         if ($sandbox_enabled) {
             $msg .= '<p>' . SwpmUtils::_('You have the sandbox payment mode enabled in plugin settings. Make sure to turn off the sandbox mode when you want to do live transactions.') . '</p>';
         }
         if (!empty($msg)) {
             //Show warning messages if any.
             echo '<div id="message" class="error">';
             echo $msg;
             echo '</div>';
         }
     }
 }
 function delete()
 {
     if (isset($_REQUEST['member_id'])) {
         //Check we are on the admin end and user has management permission
         SwpmMiscUtils::check_user_permission_and_is_admin('member deletion by admin');
         //Check nonce
         if (!isset($_REQUEST['delete_swpmuser_nonce']) || !wp_verify_nonce($_REQUEST['delete_swpmuser_nonce'], 'delete_swpmuser_admin_end')) {
             //Nonce check failed.
             wp_die(SwpmUtils::_("Error! Nonce verification failed for user delete from admin end."));
         }
         $id = sanitize_text_field($_REQUEST['member_id']);
         $id = absint($id);
         SwpmMembers::delete_user_by_id($id);
     }
 }