function pmpro_upgrade_1_8_9_3_ajax()
{
    global $wpdb;
    $debug = false;
    $run = true;
    //some vars
    $all_levels = pmpro_getAllLevels(true, true);
    //keeping track of which user we're working on
    $last_user_id = get_option('pmpro_upgrade_1_8_9_3_last_user_id', 0);
    //get all active users during the period where things may have been broken
    $user_ids = $wpdb->get_col("SELECT user_id FROM {$wpdb->pmpro_memberships_users} WHERE status = 'active' AND modified > '2016-05-19' AND user_id > {$last_user_id} ORDER BY user_id LIMIT 10");
    //track progress
    $first_load = get_transient('pmpro_updates_first_load');
    if ($first_load) {
        $total_users = $wpdb->get_var("SELECT COUNT(user_id) FROM {$wpdb->pmpro_memberships_users} WHERE status = 'active' AND modified > '2016-05-19' ORDER BY user_id");
        update_option('pmpro_upgrade_1_8_9_3_total', $total_users, 'no');
        $progress = 0;
    } else {
        $total_users = get_option('pmpro_upgrade_1_8_9_3_total', 0);
        $progress = get_option('pmpro_upgrade_1_8_9_3_progress', 0);
    }
    update_option('pmpro_upgrade_1_8_9_3_progress', $progress + count($user_ids), 'no');
    global $pmpro_updates_progress;
    if ($total_users > 0) {
        $pmpro_updates_progress = "[" . $progress . "/" . $total_users . "]";
    } else {
        $pmpro_updates_progress = "";
    }
    if (empty($user_ids)) {
        //done with this update
        pmpro_removeUpdate('pmpro_upgrade_1_8_9_3_ajax');
        delete_option('pmpro_upgrade_1_8_9_3_last_user_id');
        delete_option('pmpro_upgrade_1_8_9_3_total');
        delete_option('pmpro_upgrade_1_8_9_3_progress');
    } else {
        foreach ($user_ids as $user_id) {
            $last_user_id = $user_id;
            //keeping track of the last user we processed
            $user = get_userdata($user_id);
            //user not found for some reason
            if (empty($user)) {
                if ($debug) {
                    echo "User #" . $user_id . " not found.\n";
                }
                continue;
            }
            //get level
            $user->membership_level = pmpro_getMembershipLevelForUser($user->ID);
            //has a start and end date already
            if (!empty($user->membership_level->enddate) && !empty($user->membership_level->startdate)) {
                if ($debug) {
                    echo "User #" . $user_id . ", " . $user->user_email . " already has a start and end date.\n";
                }
                continue;
            }
            //get order
            $last_order = new MemberOrder();
            $last_order->getLastMemberOrder();
            /*
            	Figure out if this user should have been given an end date.
            	The level my have an end date.
            	They might have used a discount code.
            	They might be using the set-expiration-dates code.
            	They might have custom code setting the end date.
            
            	Let's setup some vars as if we are at checkout.
            	Then pass recreate the level with the pmpro_checkout_level filter.
            	And use the end date there if there is one.
            */
            global $pmpro_level, $discount_code, $discount_code_id;
            //level
            $level_id = $user->membership_level->id;
            $_REQUEST['level'] = $level_id;
            //gateway
            if (!empty($last_order) && !empty($last_order->gateway)) {
                $_REQUEST['gateway'] = $last_order->gateway;
            } else {
                $_REQUEST['gateway'] = pmpro_getGateway();
            }
            //discount code
            $discount_code_id = $user->membership_level->code_id;
            $discount_code = $wpdb->get_var("SELECT code FROM {$wpdb->pmpro_discount_codes} WHERE id = '" . $discount_code_id . "' LIMIT 1");
            //get level
            if (!empty($discount_code_id)) {
                $sqlQuery = "SELECT l.id, cl.*, l.name, l.description, l.allow_signups FROM {$wpdb->pmpro_discount_codes_levels} cl LEFT JOIN {$wpdb->pmpro_membership_levels} l ON cl.level_id = l.id LEFT JOIN {$wpdb->pmpro_discount_codes} dc ON dc.id = cl.code_id WHERE dc.code = '" . $discount_code . "' AND cl.level_id = '" . (int) $level_id . "' LIMIT 1";
                $pmpro_level = $wpdb->get_row($sqlQuery);
                //if the discount code doesn't adjust the level, let's just get the straight level
                if (empty($pmpro_level)) {
                    $pmpro_level = $all_levels[$level_id];
                }
                //filter adjustments to the level
                $pmpro_level->code_id = $discount_code_id;
                $pmpro_level = apply_filters("pmpro_discount_code_level", $pmpro_level, $discount_code_id);
            }
            //no level yet, use default
            if (empty($pmpro_level)) {
                $pmpro_level = $all_levels[$level_id];
            }
            //no level for some reason
            if (empty($pmpro_level) && empty($pmpro_level->id)) {
                if ($debug) {
                    echo "No level found with ID #" . $level_id . " for user #" . $user_id . ", " . $user->user_email . ".\n";
                }
                continue;
            }
            //filter level
            $pmpro_level = apply_filters("pmpro_checkout_level", $pmpro_level);
            if ($debug) {
                echo "User #" . $user_id . ", " . $user->user_email . ". Fixing.\n";
            }
            //calculate and fix start date
            if (empty($user->membership_level->startdate)) {
                $startdate = $wpdb->get_var("SELECT modified FROM {$wpdb->pmpro_memberships_users} WHERE user_id = {$user_id} AND membership_id = {$level_id} AND status = 'active' LIMIT 1");
                //filter
                $filtered_startdate = apply_filters("pmpro_checkout_start_date", $startdate, $user_id, $pmpro_level);
                //only use filtered value if it's not 0
                if (!empty($filtered_startdate) && $filtered_startdate != '0000-00-00 00:00:00' && $filtered_startdate != "'0000-00-00 00:00:00'") {
                    $startdate = $filtered_startdate;
                }
                if ($debug) {
                    echo "- Adding startdate " . $startdate . ".\n";
                }
                if ($run) {
                    $sqlQuery = "UPDATE {$wpdb->pmpro_memberships_users} SET startdate = '" . esc_sql($startdate) . "' WHERE user_id = {$user_id} AND membership_id = {$level_id} AND status = 'active' LIMIT 1";
                    $wpdb->query($sqlQuery);
                }
            } else {
                $startdate = date_i18n("Y-m-d", $user->membership_level->startdate);
            }
            //calculate and fix the end date
            if (empty($user->membership_level->enddate)) {
                if (!empty($pmpro_level->expiration_number)) {
                    $enddate = date_i18n("Y-m-d", strtotime("+ " . $pmpro_level->expiration_number . " " . $pmpro_level->expiration_period, $last_order->timestamp));
                } else {
                    $enddate = "NULL";
                }
                $enddate = apply_filters("pmpro_checkout_end_date", $enddate, $user_id, $pmpro_level, $startdate);
                if (!empty($enddate) && $enddate != "NULL") {
                    if ($debug) {
                        echo "- Adding enddate " . $enddate . ".\n";
                    }
                    if ($run) {
                        $sqlQuery = "UPDATE {$wpdb->pmpro_memberships_users} SET enddate = '" . esc_sql($enddate) . "' WHERE user_id = {$user_id} AND membership_id = {$level_id} AND status = 'active' LIMIT 1";
                        $wpdb->query($sqlQuery);
                    }
                }
            }
            //clear vars for next pass
            $user_id = NULL;
            $level_id = NULL;
            $discount_code = NULL;
            $discount_code_id = NULL;
            $pmpro_level = NULL;
            $last_order = NULL;
            $startdate = NULL;
            $filtered_startdate = NULL;
            $enddate = NULL;
            echo "\n";
        }
        update_option('pmpro_upgrade_1_8_9_3_last_user_id', $last_user_id, 'no');
    }
}
function pmprodev_checkout_debug_email($level)
{
    global $pmprodev_options, $current_user, $wpdb;
    if (empty($pmprodev_options['checkout_debug_email'])) {
        return $level;
    }
    $email = new PMProEmail();
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
        $http = 'https://';
    } else {
        $http = 'http://';
    }
    $email->subject = sprintf('%s Checkout Page Debug Log', get_bloginfo('name'));
    $email->recipient = $pmprodev_options['checkout_debug_email'];
    $email->template = 'checkout_debug';
    $email->body = file_get_contents(plugin_dir_path(__FILE__) . '/email/checkout_debug.html');
    $email->data = array('sitename' => get_bloginfo('sitename'), 'checkout_url' => $http . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 'submit' => print_r($_REQUEST['submit-checkout'], true), 'level' => print_r($level, true), 'user' => print_r($current_user->data, true), 'request' => print_r($_REQUEST, true));
    $order = new MemberOrder();
    $order->getLastMemberOrder($current_user->user_id);
    if (!empty($order)) {
        $email->data['order'] = print_r($order, true);
    }
    $email->sendEmail();
    return $level;
}
Example #3
0
function pmproet_admin_init_test_order()
{
    global $current_user, $pmproet_test_order_id;
    //make sure PMPro is activated
    if (!class_exists('MemberOrder')) {
        return;
    }
    $pmproet_test_order_id = get_option('pmproet_test_order_id');
    $test_order = new MemberOrder($pmproet_test_order_id);
    if (empty($test_order->id)) {
        $all_levels = pmpro_getAllLevels();
        if (!empty($all_levels)) {
            $first_level = array_shift($all_levels);
            $test_order->membership_id = $first_level->id;
            $test_order->InitialPayment = $first_level->initial_payment;
        } else {
            $test_order->membership_id = 1;
            $test_order->InitialPayment = 1;
        }
        $test_order->user_id = $current_user->ID;
        $test_order->cardtype = "Visa";
        $test_order->accountnumber = "4111111111111111";
        $test_order->expirationmonth = date('m', current_time('timestamp'));
        $test_order->expirationyear = intval(date('Y', current_time('timestamp'))) + 1;
        $test_order->ExpirationDate = $test_order->expirationmonth . $test_order->expirationyear;
        $test_order->CVV2 = '123';
        $test_order->FirstName = 'Jane';
        $test_order->LastName = 'Doe';
        $test_order->Address1 = '123 Street';
        $test_order->billing = new stdClass();
        $test_order->billing->name = 'Jane Doe';
        $test_order->billing->street = '123 Street';
        $test_order->billing->city = 'City';
        $test_order->billing->state = 'ST';
        $test_order->billing->country = 'US';
        $test_order->billing->zip = '12345';
        $test_order->billing->phone = '5558675309';
        $test_order->gateway_environment = 'sandbox';
        $test_order->notes = __('This is a test order used with the PMPro Email Templates addon.', 'pmpro');
        $test_order->saveOrder();
        $pmproet_test_order_id = $test_order->id;
        update_option('pmproet_test_order_id', $pmproet_test_order_id);
    }
}
Example #4
0
 public function mark_referral_complete($order)
 {
     if ('success' !== strtolower($order->status)) {
         return;
     }
     $this->complete_referral($order->id);
     $referral = affiliate_wp()->referrals->get_by('reference', $order->id, $this->context);
     $order = new MemberOrder($order->id);
     // Prevent infinite loop
     remove_action('pmpro_updated_order', array($this, 'mark_referral_complete'), 10);
     $order->affiliate_id = $referral->affiliate_id;
     $amount = html_entity_decode(affwp_currency_filter(affwp_format_amount($referral->amount)), ENT_QUOTES, 'UTF-8');
     $name = affiliate_wp()->affiliates->get_affiliate_name($referral->affiliate_id);
     $note = sprintf(__('Referral #%d for %s recorded for %s', 'affiliate-wp'), $referral->referral_id, $amount, $name);
     if (empty($order->notes)) {
         $order->notes = $note;
     } else {
         $order->notes = $order->notes . "\n\n" . $note;
     }
     $order->saveOrder();
 }
Example #5
0
function pmpro_cron_credit_card_expiring_warnings()
{
    global $wpdb;
    $next_month_date = date("Y-m-01", strtotime("+2 months"));
    $sqlQuery = "SELECT mu.user_id\n\t\t\t\t\t\tFROM  {$wpdb->pmpro_memberships_users} mu\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->usermeta} um1 ON mu.user_id = um1.user_id\n\t\t\t\t\t\t\t\tAND meta_key =  'pmpro_ExpirationMonth'\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->usermeta} um2 ON mu.user_id = um2.user_id\n\t\t\t\t\t\t\t\tAND um2.meta_key =  'pmpro_ExpirationYear'\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->usermeta} um3 ON mu.user_id = um3.user_id\n\t\t\t\t\t\t\t\tAND um3.meta_key = 'pmpro_credit_card_expiring_warning'\n\t\t\t\t\t\tWHERE mu.status =  'active'\n\t\t\t\t\t\t\tAND mu.cycle_number >0\n\t\t\t\t\t\t\tAND CONCAT(um2.meta_value, '-', um1.meta_value, '-01') < '" . $next_month_date . "'\n\t\t\t\t\t\t\tAND (um3.meta_value IS NULL OR CONCAT(um2.meta_value, '-', um1.meta_value, '-01') <> um3.meta_value)\n\t\t\t\t\t";
    $cc_expiring_user_ids = $wpdb->get_col($sqlQuery);
    if (!empty($cc_expiring_user_ids)) {
        require_once ABSPATH . 'wp-includes/pluggable.php';
        foreach ($cc_expiring_user_ids as $user_id) {
            //get user
            $euser = get_userdata($user_id);
            //make sure their level doesn't have a billing limit that's been reached
            $euser->membership_level = pmpro_getMembershipLevelForUser($euser->ID);
            if (!empty($euser->membership_level->billing_limit)) {
                /*
                	There is a billing limit on this level, skip for now. 
                	We should figure out how to tell if the limit has been reached
                	and if not, email the user about the expiring credit card.
                */
                continue;
            }
            //make sure they are using a credit card type billing method for their current membership level (check the last order)
            $last_order = new MemberOrder();
            $last_order->getLastMemberOrder($euser->ID);
            if (empty($last_order->accountnumber)) {
                continue;
            }
            //okay send them an email
            $send_email = apply_filters("pmpro_send_credit_card_expiring_email", true, $e->user_id);
            if ($send_email) {
                //send an email
                $pmproemail = new PMProEmail();
                $pmproemail->sendCreditCardExpiringEmail($euser);
                printf(__("Credit card expiring email sent to %s. ", "pmpro"), $euser->user_email);
            }
            //update user meta so we don't email them again
            update_user_meta($euser->ID, "pmpro_credit_card_expiring_warning", $euser->pmpro_ExpirationYear . "-" . $euser->pmpro_ExpirationMonth . "-01");
        }
    }
}
<?php

global $wpdb, $current_user, $pmpro_msg, $pmpro_msgt;
global $bfirstname, $blastname, $baddress1, $baddress2, $bcity, $bstate, $bzipcode, $bcountry, $bphone, $bemail, $bconfirmemail, $CardType, $AccountNumber, $ExpirationMonth, $ExpirationYear;
$gateway = pmpro_getOption("gateway");
//need to be secure?
global $besecure, $show_paypal_link;
$user_order = new MemberOrder();
$user_order->getLastMemberOrder();
if (empty($user_order->gateway)) {
    //no order
    $besecure = false;
} elseif ($user_order->gateway == "paypalexpress") {
    $besecure = pmpro_getOption("use_ssl");
    //still they might have website payments pro setup
    if ($gateway == "paypal") {
        //$besecure = true;
    } else {
        //$besecure = false;
        $show_paypal_link = true;
    }
} else {
    //$besecure = true;
    $besecure = pmpro_getOption("use_ssl");
}
//code for stripe
if ($gateway == "stripe") {
    //stripe js library
    wp_enqueue_script("stripe", "https://js.stripe.com/v1/", array(), "");
    //stripe js code for checkout
    function pmpro_stripe_javascript()
function pap_pmpro_add_order($morder)
{
    if (!empty($morder->total)) {
        //need to get the last order before this
        $last_order = new MemberOrder();
        $last_order->getLastMemberOrder($morder->user_id);
        if (!empty($last_order->affiliate_id)) {
            $parts = explode(",", $last_order->affiliate_subid);
            $affiliate_code = $last_order->affiliate_id;
            $campaign_id = $parts[0];
            $channel_id = $parts[1];
            $visitor_id = $parts[2];
            //api
            pap_pmpro_track_sale($morder->total, $morder->code, $affiliate_code, $campaign_id, $channel_id, $visitor_id);
            //update the affiliate id for this order
            global $pap_pmpro_affiliate_id, $pap_pmpro_affiliate_subid;
            $pap_pmpro_affiliate_id = $affiliate_code;
            $pap_pmpro_affiliate_subid = $campaign_id . "," . $channel_id . "," . $visitor_id;
        }
    }
}
 function sendToFondy(&$order)
 {
     global $pmpro_currency;
     global $wpdb;
     //taxes on initial amount
     $initial_payment = $order->InitialPayment;
     $initial_payment_tax = $order->getTaxForPrice($initial_payment);
     $initial_payment = round((double) $initial_payment + (double) $initial_payment_tax, 2);
     $fields = array('merchant_data' => 'name=' . $order->billing->name . '=phone=' . $order->billing->phone, 'product_id' => $order->membership_id, 'subscription_callback_url' => admin_url("admin-ajax.php") . "?action=fondy-ins", 'order_id' => $order->code . FondyForm::ORDER_SEPARATOR . time(), 'merchant_id' => pmpro_getOption("fondy_merchantid"), 'order_desc' => substr($order->membership_level->name . " at " . get_bloginfo("name"), 0, 127), 'amount' => round($initial_payment * 100), 'currency' => $pmpro_currency, 'server_callback_url' => admin_url("admin-ajax.php") . "?action=fondy-ins", 'response_url' => admin_url("admin-ajax.php") . "?action=fondy-ins", 'sender_email' => $order->Email, 'required_rectoken' => 'Y', 'subscription' => 'Y');
     $last_subscr_order = new MemberOrder();
     //print_r ($order);
     $last = new MemberOrder($last_subscr_order->getLastMemberOrder($order->user_id, $status = 'success', $membership_id = NULL, $gateway = NULL, $gateway_environment = NULL));
     if (isset($last->user_id) && isset($last->code)) {
         $result = $wpdb->get_row("SELECT fondy_token from `{$wpdb->pmpro_membership_orders}` WHERE user_id='" . $last->user_id . "' AND code='" . $last->code . "'");
         if (isset($result->fondy_token)) {
             $fields['rectoken'] = $result->fondy_token;
         }
     }
     $fields['signature'] = FondyForm::getSignature($fields, pmpro_getOption("fondy_securitykey"));
     //print_r ($last->user_id);die;
     unset($fields['currency']);
     $data = 'currency=' . $pmpro_currency . '&';
     foreach ($fields as $key => $val) {
         $data .= $key . "=" . $val . '&';
     }
     $url = 'https://api.fondy.eu/api/checkout/url/';
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, 'https://api.fondy.eu/api/checkout/url/');
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     $result = curl_exec($ch);
     $str = urldecode($result);
     parse_str($str, $mass);
     $fondy_url = $mass['checkout_url'];
     wp_redirect($fondy_url);
     exit;
 }
function pmpro_changeMembershipLevel($level, $user_id = NULL, $old_level_status = 'inactive')
{
    global $wpdb;
    global $current_user, $pmpro_error;
    if (empty($user_id)) {
        $user_id = $current_user->ID;
    }
    if (empty($user_id)) {
        $pmpro_error = __("User ID not found.", "pmpro");
        return false;
    }
    //make sure user id is int for security
    $user_id = intval($user_id);
    if (empty($level)) {
        $level = 0;
    } else {
        if (is_array($level)) {
            //custom level
        } else {
            $level_obj = pmpro_getLevel($level);
            if (empty($level_obj)) {
                $pmpro_error = __("Invalid level.", "pmpro");
                return false;
            }
            $level = $level_obj->id;
        }
    }
    //if it's a custom level, they're changing
    if (!is_array($level)) {
        //are they even changing?
        if (pmpro_hasMembershipLevel($level, $user_id)) {
            $pmpro_error = __("not changing?", "pmpro");
            return false;
            //not changing
        }
    }
    //get all active membershipships for this user
    $old_levels = pmpro_getMembershipLevelsForUser($user_id);
    //deactivate old memberships based on the old_level_status passed in (updates pmpro_memberships_users table)
    if ($old_levels) {
        foreach ($old_levels as $old_level) {
            $sql = "UPDATE {$wpdb->pmpro_memberships_users} SET `status`='{$old_level_status}', `enddate`='" . current_time('mysql') . "' WHERE `id`=" . $old_level->subscription_id;
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . (mysql_errno() ? mysql_error() : 'unavailable');
                return false;
            }
        }
    }
    //should we cancel their gateway subscriptions?
    $pmpro_cancel_previous_subscriptions = true;
    if (isset($_REQUEST['cancel_membership']) && $_REQUEST['cancel_membership'] == false) {
        $pmpro_cancel_previous_subscriptions = false;
    }
    $pmpro_cancel_previous_subscriptions = apply_filters("pmpro_cancel_previous_subscriptions", $pmpro_cancel_previous_subscriptions);
    //cancel any other subscriptions they have (updates pmpro_membership_orders table)
    if ($pmpro_cancel_previous_subscriptions) {
        $other_order_ids = $wpdb->get_col("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' AND status = 'success' ORDER BY id DESC");
        foreach ($other_order_ids as $order_id) {
            $c_order = new MemberOrder($order_id);
            $c_order->cancel();
            if (!empty($c_order->error)) {
                $pmpro_error = $c_order->error;
            }
        }
    }
    //insert current membership
    if (!empty($level)) {
        if (is_array($level)) {
            //make sure the dates are in good formats
            if ($level['startdate'] != current_time('mysql') && $level['startdate'] != "NULL" && substr($level['startdate'], 0, 1) != "'") {
                $level['startdate'] = "'" . $level['startdate'] . "'";
            }
            if ($level['enddate'] != current_time('mysql') && $level['enddate'] != "NULL" && substr($level['enddate'], 0, 1) != "'") {
                $level['enddate'] = "'" . $level['enddate'] . "'";
            }
            //Better support mySQL Strict Mode by passing  a proper enum value for cycle_period
            if ($level['cycle_period'] == '') {
                $level['cycle_period'] = 0;
            }
            $sql = "INSERT INTO {$wpdb->pmpro_memberships_users} (user_id, membership_id, code_id, initial_payment, billing_amount, cycle_number, cycle_period, billing_limit, trial_amount, trial_limit, startdate, enddate)\n\t\t\t\t\tVALUES('" . $level['user_id'] . "',\n\t\t\t\t\t'" . $level['membership_id'] . "',\n\t\t\t\t\t'" . intval($level['code_id']) . "',\n\t\t\t\t\t'" . $level['initial_payment'] . "',\n\t\t\t\t\t'" . $level['billing_amount'] . "',\n\t\t\t\t\t'" . $level['cycle_number'] . "',\n\t\t\t\t\t'" . $level['cycle_period'] . "',\n\t\t\t\t\t'" . $level['billing_limit'] . "',\n\t\t\t\t\t'" . $level['trial_amount'] . "',\n\t\t\t\t\t'" . $level['trial_limit'] . "',\n\t\t\t\t\t" . $level['startdate'] . ",\n\t\t\t\t\t" . $level['enddate'] . ")";
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . (mysql_errno() ? mysql_error() : 'unavailable');
                return false;
            }
        } else {
            $sql = "INSERT INTO {$wpdb->pmpro_memberships_users} (user_id, membership_id, code_id, initial_payment, billing_amount, cycle_number, cycle_period, billing_limit, trial_amount, trial_limit, startdate, enddate)\n\t\t\t    VALUES (\n\t\t\t    '" . $user_id . "',\n\t\t\t    '" . $level . "',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '0',\n\t\t\t    '" . current_time('mysql') . "',\n                \t    '0000-00-00 00:00:00'\n                \t    )";
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . (mysql_errno() ? mysql_error() : 'unavailable');
                return false;
            }
        }
    }
    //get level id
    if (is_array($level)) {
        $level_id = $level['membership_id'];
    } else {
        $level_id = $level;
    }
    //just id
    //remove cached level
    global $all_membership_levels;
    unset($all_membership_levels[$user_id]);
    //update user data and call action
    pmpro_set_current_user();
    do_action("pmpro_after_change_membership_level", $level_id, $user_id);
    //$level is the $level_id here
    return true;
}
<?php

global $current_user, $pmpro_invoice;
if ($current_user->ID) {
    $current_user->membership_level = pmpro_getMembershipLevelForUser($current_user->ID);
}
/*
	Use the filter to add your gateway here if you want to show them a message on the confirmation page while their checkout is pending.
	For example, when PayPal Standard is used, we need to wait for PayPal to send a message through IPN that the payment was accepted.
	In the meantime, the order is in pending status and the confirmation page shows a message RE waiting.
*/
$gateways_with_pending_status = apply_filters('pmpro_gateways_with_pending_status', array('paypalstandard', 'twocheckout', 'gourl'));
//must be logged in
if (empty($current_user->ID) || empty($current_user->membership_level->ID) && !in_array(pmpro_getGateway(), $gateways_with_pending_status)) {
    wp_redirect(home_url());
}
//if membership is a paying one, get invoice from DB
if (!empty($current_user->membership_level) && !pmpro_isLevelFree($current_user->membership_level)) {
    $pmpro_invoice = new MemberOrder();
    $pmpro_invoice->getLastMemberOrder($current_user->ID, apply_filters("pmpro_confirmation_order_status", array("success", "pending")));
}
 /**
  * Review and Confirmation code.
  *
  * @since 1.8		 
  */
 static function pmpro_checkout_confirmed($pmpro_confirmed)
 {
     global $pmpro_msg, $pmpro_msgt, $pmpro_level, $current_user, $pmpro_review, $pmpro_paypal_token, $discount_code, $bemail;
     //PayPal Express Call Backs
     if (!empty($_REQUEST['review'])) {
         if (!empty($_REQUEST['PayerID'])) {
             $_SESSION['payer_id'] = $_REQUEST['PayerID'];
         }
         if (!empty($_REQUEST['paymentAmount'])) {
             $_SESSION['paymentAmount'] = $_REQUEST['paymentAmount'];
         }
         if (!empty($_REQUEST['currencyCodeType'])) {
             $_SESSION['currCodeType'] = $_REQUEST['currencyCodeType'];
         }
         if (!empty($_REQUEST['paymentType'])) {
             $_SESSION['paymentType'] = $_REQUEST['paymentType'];
         }
         $morder = new MemberOrder();
         $morder->getMemberOrderByPayPalToken($_REQUEST['token']);
         $morder->Token = $morder->paypal_token;
         $pmpro_paypal_token = $morder->paypal_token;
         if ($morder->Token) {
             if ($morder->Gateway->getExpressCheckoutDetails($morder)) {
                 $pmpro_review = true;
             } else {
                 $pmpro_msg = $morder->error;
                 $pmpro_msgt = "pmpro_error";
             }
         } else {
             $pmpro_msg = __("The PayPal Token was lost.", "pmpro");
             $pmpro_msgt = "pmpro_error";
         }
     } elseif (!empty($_REQUEST['confirm'])) {
         $morder = new MemberOrder();
         $morder->getMemberOrderByPayPalToken($_REQUEST['token']);
         $morder->Token = $morder->paypal_token;
         $pmpro_paypal_token = $morder->paypal_token;
         if ($morder->Token) {
             //setup values
             $morder->membership_id = $pmpro_level->id;
             $morder->membership_name = $pmpro_level->name;
             $morder->discount_code = $discount_code;
             $morder->InitialPayment = $pmpro_level->initial_payment;
             $morder->PaymentAmount = $pmpro_level->billing_amount;
             $morder->ProfileStartDate = date("Y-m-d") . "T0:0:0";
             $morder->BillingPeriod = $pmpro_level->cycle_period;
             $morder->BillingFrequency = $pmpro_level->cycle_number;
             $morder->Email = $bemail;
             //setup level var
             $morder->getMembershipLevel();
             $morder->membership_level = apply_filters("pmpro_checkout_level", $morder->membership_level);
             //tax
             $morder->subtotal = $morder->InitialPayment;
             $morder->getTax();
             if ($pmpro_level->billing_limit) {
                 $morder->TotalBillingCycles = $pmpro_level->billing_limit;
             }
             if (pmpro_isLevelTrial($pmpro_level)) {
                 $morder->TrialBillingPeriod = $pmpro_level->cycle_period;
                 $morder->TrialBillingFrequency = $pmpro_level->cycle_number;
                 $morder->TrialBillingCycles = $pmpro_level->trial_limit;
                 $morder->TrialAmount = $pmpro_level->trial_amount;
             }
             if ($morder->confirm()) {
                 $pmpro_confirmed = true;
             } else {
                 $pmpro_msg = $morder->error;
                 $pmpro_msgt = "pmpro_error";
             }
         } else {
             $pmpro_msg = __("The PayPal Token was lost.", "pmpro");
             $pmpro_msgt = "pmpro_error";
         }
     }
     if (!empty($morder)) {
         return array("pmpro_confirmed" => $pmpro_confirmed, "morder" => $morder);
     } else {
         return $pmpro_confirmed;
     }
 }
			<hr>
			<h5>Invoices</h5>
			<div class="row">
				<div class="col-md-4"><h6>Date</h6></div>
				<div class="col-md-4"><h6>Level</h6></div>
				<div class="col-md-4"><h6>Amount</h6></div>
			</div>
			<?php 
        $count = 0;
        foreach ($invoices as $invoice) {
            ?>
					<div class="row">
						<?php 
            //get an member order object
            $invoice_id = $invoice->id;
            $invoice = new MemberOrder();
            $invoice->getMemberOrderByID($invoice_id);
            $invoice->getMembershipLevel();
            ?>
						<div class="col-md-4">
							<a href="<?php 
            echo pmpro_url("invoice", "?invoice=" . $invoice->code);
            ?>
"><?php 
            echo date(get_option("date_format"), $invoice->timestamp);
            ?>
</a>
						</div>
						<div class="col-md-4">
							<?php 
            echo $invoice->membership_level->name;
Example #13
0
//these are the meta_keys for the fields (arrays are object, property. so e.g. $theuser->ID)
$default_columns = array(array("order", "id"), array("user", "ID"), array("user", "user_login"), array("user", "first_name"), array("user", "last_name"), array("user", "user_email"), array("order", "billing", "name"), array("order", "billing", "street"), array("order", "billing", "city"), array("order", "billing", "state"), array("order", "billing", "zip"), array("order", "billing", "country"), array("order", "billing", "phone"), array("order", "membership_id"), array("level", "name"), array("order", "subtotal"), array("order", "tax"), array("order", "couponamount"), array("order", "total"), array("order", "payment_type"), array("order", "cardtype"), array("order", "accountnumber"), array("order", "expirationmonth"), array("order", "expirationyear"), array("order", "status"), array("order", "gateway"), array("order", "gateway_environment"), array("order", "payment_transaction_id"), array("order", "subscription_transactiond_id"), array("discount_code", "id"), array("discount_code", "code"));
//any extra columns
$extra_columns = apply_filters("pmpro_orders_csv_extra_columns", array());
if (!empty($extra_columns)) {
    foreach ($extra_columns as $heading => $callback) {
        $csvoutput .= "," . $heading;
    }
}
$csvoutput .= "\n";
//output
echo $csvoutput;
$csvoutput = "";
if ($order_ids) {
    foreach ($order_ids as $order_id) {
        $order = new MemberOrder();
        $order->nogateway = true;
        $order->getMemberOrderByID($order_id);
        $user = get_userdata($order->user_id);
        $level = $order->getMembershipLevel();
        $sqlQuery = "SELECT c.id, c.code FROM {$wpdb->pmpro_discount_codes_uses} cu LEFT JOIN {$wpdb->pmpro_discount_codes} c ON cu.code_id = c.id WHERE cu.order_id = '" . $order_id . "' LIMIT 1";
        $discount_code = $wpdb->get_row($sqlQuery);
        //default columns
        if (!empty($default_columns)) {
            $count = 0;
            foreach ($default_columns as $col) {
                //add comma after the first item
                $count++;
                if ($count > 1) {
                    $csvoutput .= ",";
                }
$pfData = array();
$pfHost = ($gateway_environment == 'sandbox' ? 'sandbox' : 'www') . '.payfast.co.za';
$pfOrderId = '';
$pfParamString = '';
ipnlog('PayFast ITN call received');
//// Notify PayFast that information has been received
if (!$pfError && !$pfDone) {
    header('HTTP/1.0 200 OK');
    flush();
}
//// Get data sent by PayFast
if (!$pfError && !$pfDone) {
    ipnlog('Get posted data');
    // Posted variables from ITN
    $pfData = pmpro_pfGetData();
    $morder = new MemberOrder($pfData['m_payment_id']);
    $morder->getMembershipLevel();
    $morder->getUser();
    ipnlog('PayFast Data: ' . print_r($pfData, true));
    if ($pfData === false) {
        $pfError = true;
        $pfErrMsg = PF_ERR_BAD_ACCESS;
    }
}
//// Verify security signature
if (!$pfError && !$pfDone) {
    ipnlog('Verify security signature');
    // If signature different, log for debugging
    if (!pmpro_pfValidSignature($pfData, $pfParamString)) {
        $pfError = true;
        $pfErrMsg = PF_ERR_INVALID_SIGNATURE;
 /**
  * Helper method to cancel a subscription at Stripe and also clear up any upaid invoices.
  *
  * @since 1.8
  */
 function cancelSubscriptionAtGateway($subscription)
 {
     //need a valid sub
     if (empty($subscription->id)) {
         return false;
     }
     //make sure we get the customer for this subscription
     $order = new MemberOrder();
     $order->getLastMemberOrderBySubscriptionTransactionID($subscription->id);
     //no order?
     if (empty($order)) {
         //lets cancel anyway, but this is suspicious
         $r = $subscription->cancel();
         return true;
     }
     //okay have an order, so get customer so we can cancel invoices too
     $this->getCustomer($order);
     //get open invoices
     $invoices = $this->customer->invoices();
     $invoices = $invoices->all();
     //found it, cancel it
     try {
         //find any open invoices for this subscription and forgive them
         if (!empty($invoices)) {
             foreach ($invoices->data as $invoice) {
                 if (!$invoice->closed && $invoice->subscription == $subscription->id) {
                     $invoice->closed = true;
                     $invoice->save();
                 }
             }
         }
         //cancel
         $r = $subscription->cancel();
         return true;
     } catch (Exception $e) {
         return false;
     }
 }
/**
 * Create, add, remove or updates the membership level of the given user to the given level.
 *
 * $level may either be the ID or name of the desired membership_level.
 * If $user_id is omitted, the value will be retrieved from $current_user.
 *
 * @param int $level ID of level to set as new level, use 0 to cancel membership
 * @param int $user_id ID of the user to change levels for
 * @param string $old_level_status The status to set for the row in the memberships users table. (e.g. inactive, cancelled, admin_cancelled, expired) Defaults to 'inactive'.
 * $param int $cancel_level If set cancel just this one level instead of all active levels (to support Multiple Memberships per User)
 *
 * Return values:
 *		Success returns boolean true.
 *		Failure returns boolean false.
 */
function pmpro_changeMembershipLevel($level, $user_id = NULL, $old_level_status = 'inactive', $cancel_level = NULL)
{
    global $wpdb;
    global $current_user, $pmpro_error;
    if (empty($user_id)) {
        $user_id = $current_user->ID;
    }
    if (empty($user_id)) {
        $pmpro_error = __("User ID not found.", "pmpro");
        return false;
    }
    //make sure user id is int for security
    $user_id = intval($user_id);
    if (empty($level)) {
        $level = 0;
    } else {
        if (is_array($level)) {
            //custom level
        } else {
            $level_obj = pmpro_getLevel($level);
            if (empty($level_obj)) {
                $pmpro_error = __("Invalid level.", "pmpro");
                return false;
            }
            $level = $level_obj->id;
        }
    }
    //if it's a custom level, they're changing
    if (!is_array($level)) {
        //are they even changing?
        if (pmpro_hasMembershipLevel($level, $user_id)) {
            $pmpro_error = __("not changing?", "pmpro");
            return false;
            //not changing
        }
    }
    //get all active membershipships for this user
    $old_levels = pmpro_getMembershipLevelsForUser($user_id);
    //get level id
    if (is_array($level)) {
        $level_id = $level['membership_id'];
    } else {
        $level_id = $level;
    }
    //just id
    /**
     * Action to run before the membership level changes.
     *
     * @param int $level_id ID of the level changed to.
     * @param int $user_id ID of the user changed.
     * @param array $old_levels array of prior levels the user belonged to.
     * $param int $cancel_level ID of the level being cancelled if specified
     */
    do_action("pmpro_before_change_membership_level", $level_id, $user_id, $old_levels, $cancel_level);
    //deactivate old memberships based on the old_level_status passed in (updates pmpro_memberships_users table)
    $pmpro_deactivate_old_levels = true;
    /**
     * Filter whether old levels should be deactivated or not. This supports the MMPU addon.
     * Typically you'll want to hook into pmpro_before_change_membership_level 
     * or pmpro_after_change_membership_level later to run your own deactivation logic.
     * 
     * @since  1.8.11
     * @var $pmpro_deactivate_old_levels bool True or false if levels should be deactivated. Defaults to true.
     */
    $pmpro_deactivate_old_levels = apply_filters("pmpro_deactivate_old_levels", $pmpro_deactivate_old_levels);
    //make sure we deactivate the specified level if it's passed in
    if (!empty($cancel_level)) {
        $pmpro_deactivate_old_levels = true;
        $new_old_levels = array();
        foreach ($old_levels as $key => $old_level) {
            if ($old_level->id == $cancel_level) {
                $new_old_levels[] = $old_levels[$key];
                break;
            }
        }
        $old_levels = $new_old_levels;
    }
    if ($old_levels && $pmpro_deactivate_old_levels) {
        foreach ($old_levels as $old_level) {
            $sql = "UPDATE {$wpdb->pmpro_memberships_users} SET `status`='{$old_level_status}', `enddate`='" . current_time('mysql') . "' WHERE `id`=" . $old_level->subscription_id;
            if (!$wpdb->query($sql)) {
                $pmpro_error = __("Error interacting with database", "pmpro") . ": " . ($wpdb->last_error ? $wpdb->last_error : 'unavailable');
                return false;
            }
        }
    }
    //should we cancel their gateway subscriptions?
    if (!empty($cancel_level)) {
        $pmpro_cancel_previous_subscriptions = true;
        //don't filter cause we're doing just the one
        $other_order_ids = $wpdb->get_col("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' AND status = 'success' AND membership_id = '" . esc_sql($cancel_level) . "' ORDER BY id DESC");
    } else {
        $pmpro_cancel_previous_subscriptions = true;
        if (isset($_REQUEST['cancel_membership']) && $_REQUEST['cancel_membership'] == false) {
            $pmpro_cancel_previous_subscriptions = false;
        }
        $pmpro_cancel_previous_subscriptions = apply_filters("pmpro_cancel_previous_subscriptions", $pmpro_cancel_previous_subscriptions);
        $other_order_ids = $wpdb->get_col("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' AND status = 'success' ORDER BY id DESC");
    }
    //cancel any other subscriptions they have (updates pmpro_membership_orders table)
    if ($pmpro_cancel_previous_subscriptions && !empty($other_order_ids)) {
        foreach ($other_order_ids as $order_id) {
            $c_order = new MemberOrder($order_id);
            $c_order->cancel();
            if (!empty($c_order->error)) {
                $pmpro_error = $c_order->error;
            }
        }
    }
    //insert current membership
    if (!empty($level)) {
        //make sure the dates are in good formats
        if (is_array($level)) {
            //Better support mySQL Strict Mode by passing  a proper enum value for cycle_period
            if ($level['cycle_period'] == '') {
                $level['cycle_period'] = 0;
            }
            // clean up date formatting (string/not string)
            $level['startdate'] = preg_replace('/\'/', '', $level['startdate']);
            $level['enddate'] = preg_replace('/\'/', '', $level['enddate']);
            $sql = $wpdb->prepare("\r\n\t\t\t\t\tINSERT INTO {$wpdb->pmpro_memberships_users}\r\n\t\t\t\t\t(`user_id`, `membership_id`, `code_id`, `initial_payment`, `billing_amount`, `cycle_number`, `cycle_period`, `billing_limit`, `trial_amount`, `trial_limit`, `startdate`, `enddate`)\r\n\t\t\t\t\tVALUES\r\n\t\t\t\t\t( %d, %d, %d, %s, %s, %d, %s, %d, %s, %d, %s, %s )", $level['user_id'], $level['membership_id'], $level['code_id'], $level['initial_payment'], $level['billing_amount'], $level['cycle_number'], $level['cycle_period'], $level['billing_limit'], $level['trial_amount'], $level['trial_limit'], $level['startdate'], $level['enddate']);
        } else {
            $sql = $wpdb->prepare("\r\n\t\t\t\tINSERT INTO {$wpdb->pmpro_memberships_users}\r\n\t\t\t\t( `user_id`, `membership_id`, `code_id`, `initial_payment`, `billing_amount`, `cycle_number`, `cycle_period`, `billing_limit`, `trial_amount`, `trial_limit`, `startdate`, `enddate`)\r\n\t\t\t\t\tVALUES \r\n\t\t\t\t\t( %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %s, %s )", $user_id, $level_id, '0', '0', '0', '0', '0', '0', '0', '0', current_time('mysql'), '0000-00-00 00:00:00');
        }
        if (false === $wpdb->query($sql)) {
            $pmpro_error = sprintf(__("Error interacting with database: %s", "pmpro"), !empty($wpdb->last_error) ? $wpdb->last_error : 'unavailable');
            return false;
        }
    }
    //remove cached level
    global $all_membership_levels;
    unset($all_membership_levels[$user_id]);
    //update user data and call action
    pmpro_set_current_user();
    /**
     * Action to run after the membership level changes.
     *
     * @param int $level_id ID of the level changed to.
     * @param int $user_id ID of the user changed.
     * $param int $cancel_level ID of the level being cancelled if specified.
     */
    do_action("pmpro_after_change_membership_level", $level_id, $user_id, $cancel_level);
    return true;
}
    $pmproemail = new PMProEmail();
    $pmproemail->sendBillingFailureEmail($user, $morder);
    // Email admin so they are aware of the failure
    $pmproemail = new PMProEmail();
    $pmproemail->sendBillingFailureAdminEmail(get_bloginfo("admin_email"), $morder);
    echo "Sent email to the member and site admin. Thanks.";
    exit;
}
//subscription cancelled (they used one l canceled)
if ($webhookNotification->kind == "subscription_canceled") {
    //need a subscription id
    if (empty($webhookNotification->subscription->id)) {
        die("No subscription ID.");
    }
    //figure out which order to attach to
    $old_order = new MemberOrder();
    $old_order->getLastMemberOrderBySubscriptionTransactionID($webhookNotification->subscription->id);
    if (empty($old_order)) {
        die("Couldn't find old order for failed payment with subscription id=" . $webhookNotification->subscription->id);
    }
    //generate billing failure email
    do_action("pmpro_subscription_cancelled", $old_order);
    $transaction = $webhookNotification->transactions[0];
    //prep this order for the failure emails
    $morder = new MemberOrder();
    $morder->user_id = $user_id;
    $morder->billing->name = trim($transaction->billing_details->first_name . " " . $transaction->billing_details->first_name);
    $morder->billing->street = $transaction->billing_details->street_address;
    $morder->billing->city = $transaction->billing_details->locality;
    $morder->billing->state = $transaction->billing_details->region;
    $morder->billing->zip = $transaction->billing_details->postal_code;
Example #18
0
    ?>
				</a> |
				<a href="<?php 
    echo home_url(JAVO_DEF_LANG . JAVO_MEMBER_SLUG . '/' . wp_get_current_user()->user_login . '/' . JAVO_LOSTPW_SLUG);
    ?>
"><?php 
    _ex("Change Password", "As in 'change password'.", "pmpro");
    ?>
</a>
			</p>
		</div> <!-- end pmpro_account-profile -->
	
		<?php 
    //last invoice for current info
    //$ssorder = $wpdb->get_row("SELECT *, UNIX_TIMESTAMP(timestamp) as timestamp FROM $wpdb->pmpro_membership_orders WHERE user_id = '$current_user->ID' AND membership_id = '" . $current_user->membership_level->ID . "' AND status = 'success' ORDER BY timestamp DESC LIMIT 1");
    $ssorder = new MemberOrder();
    $ssorder->getLastMemberOrder();
    $invoices = $wpdb->get_results("SELECT *, UNIX_TIMESTAMP(timestamp) as timestamp FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '{$current_user->ID}' ORDER BY timestamp DESC LIMIT 6");
    if (!empty($ssorder->id) && $ssorder->gateway != "check" && $ssorder->gateway != "paypalexpress" && $ssorder->gateway != "paypalstandard" && $ssorder->gateway != "twocheckout") {
        //default values from DB (should be last order or last update)
        $bfirstname = get_user_meta($current_user->ID, "pmpro_bfirstname", true);
        $blastname = get_user_meta($current_user->ID, "pmpro_blastname", true);
        $baddress1 = get_user_meta($current_user->ID, "pmpro_baddress1", true);
        $baddress2 = get_user_meta($current_user->ID, "pmpro_baddress2", true);
        $bcity = get_user_meta($current_user->ID, "pmpro_bcity", true);
        $bstate = get_user_meta($current_user->ID, "pmpro_bstate", true);
        $bzipcode = get_user_meta($current_user->ID, "pmpro_bzipcode", true);
        $bcountry = get_user_meta($current_user->ID, "pmpro_bcountry", true);
        $bphone = get_user_meta($current_user->ID, "pmpro_bphone", true);
        $bemail = get_user_meta($current_user->ID, "pmpro_bemail", true);
        $bconfirmemail = get_user_meta($current_user->ID, "pmpro_bconfirmemail", true);
//define('PMPRO_AUTHNET_SILENT_POST_DEBUG', true);
if (defined('PMPRO_AUTHNET_SILENT_POST_DEBUG') && PMPRO_AUTHNET_SILENT_POST_DEBUG) {
    wp_mail(get_option("admin_email"), "Authorize.net Silent Post From " . get_option("blogname"), nl2br(var_export($fields, true)));
}
// If it is an ARB transaction, do something with it
if ($arb == true) {
    // okay, add an invoice. first lookup the user_id from the subscription id passed
    $old_order_id = $wpdb->get_var("SELECT id FROM {$wpdb->pmpro_membership_orders} WHERE subscription_transaction_id = '" . esc_sql($fields['x_subscription_id']) . "' AND gateway = 'authorizenet' ORDER BY timestamp DESC LIMIT 1");
    $old_order = new MemberOrder($old_order_id);
    $user_id = $old_order->user_id;
    $user = get_userdata($user_id);
    if ($fields['x_response_code'] == 1) {
        if ($user_id) {
            //should we check for a dupe x_trans_id?
            //alright. create a new order/invoice
            $morder = new MemberOrder();
            $morder->user_id = $old_order->user_id;
            $morder->membership_id = $old_order->membership_id;
            $morder->InitialPayment = $fields['x_amount'];
            //not the initial payment, but the class is expecting that
            $morder->PaymentAmount = $fields['x_amount'];
            $morder->payment_transaction_id = $fields['x_trans_id'];
            $morder->subscription_transaction_id = $fields['x_subscription_id'];
            $morder->gateway = $old_order->gateway;
            $morder->gateway_environment = $old_order->gateway_environment;
            $morder->FirstName = $fields['x_first_name'];
            $morder->LastName = $fields['x_last_name'];
            $morder->Email = $fields['x_email'];
            $morder->Address1 = $fields['x_address'];
            $morder->City = $fields['x_city'];
            $morder->State = $fields['x_state'];
function pmpro_shortcode_account($atts, $content = null, $code = "")
{
    global $wpdb, $pmpro_msg, $pmpro_msgt, $pmpro_levels, $current_user, $levels;
    // $atts    ::= array of attributes
    // $content ::= text within enclosing form of shortcode element
    // $code    ::= the shortcode found, when == callback name
    // examples: [pmpro_account] [pmpro_account sections="membership,profile"/]
    extract(shortcode_atts(array('section' => '', 'sections' => 'membership,profile,invoices,links'), $atts));
    //did they use 'section' instead of 'sections'?
    if (!empty($section)) {
        $sections = $section;
    }
    //turn into an array
    $sections = explode(',', $sections);
    ob_start();
    //if a member is logged in, show them some info here (1. past invoices. 2. billing information with button to update.)
    if (pmpro_hasMembershipLevel()) {
        $ssorder = new MemberOrder();
        $ssorder->getLastMemberOrder();
        $invoices = $wpdb->get_results("SELECT *, UNIX_TIMESTAMP(timestamp) as timestamp FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '{$current_user->ID}' ORDER BY timestamp DESC LIMIT 6");
        ?>
	
	<div id="pmpro_account">		
		
		<?php 
        if (in_array('membership', $sections) || in_array('memberships', $sections)) {
            ?>
			<div id="pmpro_account-membership" class="pmpro_box">
				
				<h3><?php 
            _e("My Memberships", "pmpro");
            ?>
</h3>
				<table width="100%" cellpadding="0" cellspacing="0" border="0">
					<thead>
						<tr>
							<th><?php 
            _e("Level", "pmpro");
            ?>
</th>
							<th><?php 
            _e("Billing", "pmpro");
            ?>
</th>
							<th><?php 
            _e("Expiration", "pmpro");
            ?>
</th>
						</tr>
					</thead>
					<tbody>
						<?php 
            //TODO: v2.0 will loop through levels here
            $level = $current_user->membership_level;
            ?>
						<tr>
							<td class="pmpro_account-membership-levelname">
								<?php 
            echo $current_user->membership_level->name;
            ?>
								<div class="pmpro_actionlinks">
									<?php 
            do_action("pmpro_member_action_links_before");
            ?>
									
									<?php 
            if (pmpro_isLevelExpiringSoon($current_user->membership_level)) {
                ?>
										<a href="<?php 
                echo pmpro_url("checkout", "?level=" . $current_user->membership_level->id, "https");
                ?>
"><?php 
                _e("Renew", "pmpro");
                ?>
</a>
									<?php 
            }
            ?>

									<?php 
            if (isset($ssorder->status) && $ssorder->status == "success" && (isset($ssorder->gateway) && in_array($ssorder->gateway, array("authorizenet", "paypal", "stripe", "braintree", "payflow", "cybersource")))) {
                ?>
										<a href="<?php 
                echo pmpro_url("billing", "", "https");
                ?>
"><?php 
                _e("Update Billing Info", "pmpro");
                ?>
</a>
									<?php 
            }
            ?>
									
									<?php 
            //To do: Only show CHANGE link if this level is in a group that has upgrade/downgrade rules
            if (count($pmpro_levels) > 1 && !defined("PMPRO_DEFAULT_LEVEL")) {
                ?>
										<a href="<?php 
                echo pmpro_url("levels");
                ?>
"><?php 
                _e("Change", "pmpro");
                ?>
</a>
									<?php 
            }
            ?>
									<a href="<?php 
            echo pmpro_url("cancel", "?level=" . $current_user->membership_level->id);
            ?>
"><?php 
            _e("Cancel", "pmpro");
            ?>
</a>
									<?php 
            do_action("pmpro_member_action_links_after");
            ?>
								</div> <!-- end pmpro_actionlinks -->
							</td>
							<td class="pmpro_account-membership-levelfee">
								<p><?php 
            echo pmpro_getLevelCost($level, true, true);
            ?>
</p>
							</td>
							<td class="pmpro_account-membership-expiration">
							<?php 
            if ($current_user->membership_level->enddate) {
                echo date(get_option('date_format'), $current_user->membership_level->enddate);
            } else {
                echo "---";
            }
            ?>
							</td>
						</tr>
					</tbody>
				</table>
				<?php 
            //Todo: If there are multiple levels defined that aren't all in the same group defined as upgrades/downgrades
            ?>
				<div class="pmpro_actionlinks">
					<a href="<?php 
            echo pmpro_url("levels");
            ?>
"><?php 
            _e("View all Membership Options", "pmpro");
            ?>
</a>
				</div>

			</div> <!-- end pmpro_account-membership -->
		<?php 
        }
        ?>
		
		<?php 
        if (in_array('profile', $sections)) {
            ?>
			<div id="pmpro_account-profile" class="pmpro_box">	
				<?php 
            get_currentuserinfo();
            ?>
 
				<h3><?php 
            _e("My Account", "pmpro");
            ?>
</h3>
				<?php 
            if ($current_user->user_firstname) {
                ?>
					<p><?php 
                echo $current_user->user_firstname;
                ?>
 <?php 
                echo $current_user->user_lastname;
                ?>
</p>
				<?php 
            }
            ?>
				<ul>
					<?php 
            do_action('pmpro_account_bullets_top');
            ?>
					<li><strong><?php 
            _e("Username", "pmpro");
            ?>
:</strong> <?php 
            echo $current_user->user_login;
            ?>
</li>
					<li><strong><?php 
            _e("Email", "pmpro");
            ?>
:</strong> <?php 
            echo $current_user->user_email;
            ?>
</li>
					<?php 
            do_action('pmpro_account_bullets_bottom');
            ?>
				</ul>
				<div class="pmpro_actionlinks">
					<a href="<?php 
            echo admin_url('profile.php');
            ?>
"><?php 
            _e("Edit Profile", "pmpro");
            ?>
</a>
					<a href="<?php 
            echo admin_url('profile.php');
            ?>
"><?php 
            _e('Change Password', 'pmpro');
            ?>
</a>
				</div>
			</div> <!-- end pmpro_account-profile -->
		<?php 
        }
        ?>
	
		<?php 
        if (in_array('invoices', $sections) && !empty($invoices)) {
            ?>
		
		<div id="pmpro_account-invoices" class="pmpro_box">
			<h3><?php 
            _e("Past Invoices", "pmpro");
            ?>
</h3>
			<table width="100%" cellpadding="0" cellspacing="0" border="0">
				<thead>
					<tr>
						<th><?php 
            _e("Date", "pmpro");
            ?>
</th>
						<th><?php 
            _e("Level", "pmpro");
            ?>
</th>
						<th><?php 
            _e("Amount", "pmpro");
            ?>
</th>
					</tr>
				</thead>
				<tbody>
				<?php 
            $count = 0;
            foreach ($invoices as $invoice) {
                if ($count++ > 4) {
                    break;
                }
                //get an member order object
                $invoice_id = $invoice->id;
                $invoice = new MemberOrder();
                $invoice->getMemberOrderByID($invoice_id);
                $invoice->getMembershipLevel();
                ?>
						<tr id="pmpro_account-invoice-<?php 
                echo $invoice->code;
                ?>
">
							<td><a href="<?php 
                echo pmpro_url("invoice", "?invoice=" . $invoice->code);
                ?>
"><?php 
                echo date(get_option("date_format"), $invoice->timestamp);
                ?>
</td>
							<td><?php 
                echo $invoice->membership_level->name;
                ?>
</td>
							<td><?php 
                echo pmpro_formatPrice($invoice->total);
                ?>
</td>
						</tr>
						<?php 
            }
            ?>
				</tbody>
			</table>						
			<?php 
            if ($count == 6) {
                ?>
				<div class="pmpro_actionlinks"><a href="<?php 
                echo pmpro_url("invoice");
                ?>
"><?php 
                _e("View All Invoices", "pmpro");
                ?>
</a></div>
			<?php 
            }
            ?>
		</div> <!-- end pmpro_account-invoices -->
		<?php 
        }
        ?>
		
		<?php 
        if (in_array('links', $sections) && (has_filter('pmpro_member_links_top') || has_filter('pmpro_member_links_bottom'))) {
            ?>
		<div id="pmpro_account-links" class="pmpro_box">
			<h3><?php 
            _e("Member Links", "pmpro");
            ?>
</h3>
			<ul>
				<?php 
            do_action("pmpro_member_links_top");
            ?>
				
				<?php 
            do_action("pmpro_member_links_bottom");
            ?>
			</ul>
		</div> <!-- end pmpro_account-links -->		
		<?php 
        }
        ?>
	</div> <!-- end pmpro_account -->		
	<?php 
    }
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}
function pmpro_ipnSaveOrder($txn_id, $last_order)
{
    global $wpdb;
    //check that txn_id has not been previously processed
    $old_txn = $wpdb->get_var("SELECT payment_transaction_id FROM {$wpdb->pmpro_membership_orders} WHERE payment_transaction_id = '" . $txn_id . "' LIMIT 1");
    if (empty($old_txn)) {
        //hook for successful subscription payments
        do_action("pmpro_subscription_payment_completed");
        //save order
        $morder = new MemberOrder();
        $morder->user_id = $last_order->user_id;
        $morder->membership_id = $last_order->membership_id;
        $morder->payment_transaction_id = $txn_id;
        $morder->subscription_transaction_id = $last_order->subscription_transaction_id;
        $morder->gateway = $last_order->gateway;
        $morder->gateway_environment = $last_order->gateway_environment;
        // Payment Status
        $morder->status = 'success';
        // We have confirmed that and thats the reason we are here.
        // Payment Type.
        $morder->payment_type = $last_order->payment_type;
        //set amount based on which PayPal type
        if ($last_order->gateway == "paypal") {
            $morder->InitialPayment = $_POST['amount'];
            //not the initial payment, but the class is expecting that
            $morder->PaymentAmount = $_POST['amount'];
        } elseif ($last_order->gateway == "paypalexpress") {
            $morder->InitialPayment = $_POST['amount'];
            //not the initial payment, but the class is expecting that
            $morder->PaymentAmount = $_POST['amount'];
        } elseif ($last_order->gateway == "paypalstandard") {
            $morder->InitialPayment = $_POST['mc_gross'];
            //not the initial payment, but the class is expecting that
            $morder->PaymentAmount = $_POST['mc_gross'];
        }
        $morder->FirstName = $_POST['first_name'];
        $morder->LastName = $_POST['last_name'];
        $morder->Email = $_POST['payer_email'];
        //get address info if appropriate
        if ($last_order->gateway == "paypal") {
            $morder->Address1 = get_user_meta($last_order->user_id, "pmpro_baddress1", true);
            $morder->City = get_user_meta($last_order->user_id, "pmpro_bcity", true);
            $morder->State = get_user_meta($last_order->user_id, "pmpro_bstate", true);
            $morder->CountryCode = "US";
            $morder->Zip = get_user_meta($last_order->user_id, "pmpro_bzip", true);
            $morder->PhoneNumber = get_user_meta($last_order->user_id, "pmpro_bphone", true);
            $morder->billing->name = $_POST['first_name'] . " " . $_POST['last_name'];
            $morder->billing->street = get_user_meta($last_order->user_id, "pmpro_baddress1", true);
            $morder->billing->city = get_user_meta($last_order->user_id, "pmpro_bcity", true);
            $morder->billing->state = get_user_meta($last_order->user_id, "pmpro_bstate", true);
            $morder->billing->zip = get_user_meta($last_order->user_id, "pmpro_bzip", true);
            $morder->billing->country = get_user_meta($last_order->user_id, "pmpro_bcountry", true);
            $morder->billing->phone = get_user_meta($last_order->user_id, "pmpro_bphone", true);
            //get CC info that is on file
            $morder->cardtype = get_user_meta($last_order->user_id, "pmpro_CardType", true);
            $morder->accountnumber = hideCardNumber(get_user_meta($last_order->user_id, "pmpro_AccountNumber", true), false);
            $morder->expirationmonth = get_user_meta($last_order->user_id, "pmpro_ExpirationMonth", true);
            $morder->expirationyear = get_user_meta($last_order->user_id, "pmpro_ExpirationYear", true);
            $morder->ExpirationDate = $morder->expirationmonth . $morder->expirationyear;
            $morder->ExpirationDate_YdashM = $morder->expirationyear . "-" . $morder->expirationmonth;
        }
        //save
        $morder->saveOrder();
        $morder->getMemberOrderByID($morder->id);
        //email the user their invoice
        $pmproemail = new PMProEmail();
        $pmproemail->sendInvoiceEmail(get_userdata($last_order->user_id), $morder);
        ipnlog("New order (" . $morder->code . ") created.");
        return true;
    } else {
        ipnlog("Duplicate Transaction ID: " . $txn_id);
        return false;
    }
}
function pmpro_membership_level_profile_fields_update()
{
    //get the user id
    global $wpdb, $current_user, $user_ID;
    get_currentuserinfo();
    if (!empty($_REQUEST['user_id'])) {
        $user_ID = $_REQUEST['user_id'];
    }
    $membership_level_capability = apply_filters("pmpro_edit_member_capability", "manage_options");
    if (!current_user_can($membership_level_capability)) {
        return false;
    }
    //level change
    if (isset($_REQUEST['membership_level'])) {
        //if the level is being set to 0 by the admin, it's a cancellation.
        $changed_or_cancelled = '';
        if ($_REQUEST['membership_level'] === 0 || $_REQUEST['membership_level'] === '0' || $_REQUEST['membership_level'] == '') {
            $changed_or_cancelled = 'admin_cancelled';
        } else {
            $changed_or_cancelled = 'admin_changed';
        }
        //if the cancel at gateway box is not checked, don't cancel
        if (empty($_REQUEST['cancel_subscription'])) {
            add_filter('pmpro_cancel_previous_subscriptions', 'pmpro_cancel_previous_subscriptions_false');
        }
        //do the change
        if (pmpro_changeMembershipLevel($_REQUEST['membership_level'], $user_ID, $changed_or_cancelled)) {
            //it changed. send email
            $level_changed = true;
        } elseif (!empty($_REQUEST['cancel_subscription'])) {
            //the level didn't change, but we were asked to cancel the subscription at the gateway, let's do that
            $order = new MemberOrder();
            $order->getLastMemberOrder($user_ID);
            if (!empty($order) && !empty($order->id)) {
                $r = $order->cancel();
            }
        }
        //remove filter after ward
        if (empty($_REQUEST['cancel_subscription'])) {
            remove_filter('pmpro_cancel_previous_subscriptions', 'pmpro_cancel_previous_subscriptions_false');
        }
    }
    //expiration change
    if (!empty($_REQUEST['expires'])) {
        //update the expiration date
        $expiration_date = intval($_REQUEST['expires_year']) . "-" . str_pad(intval($_REQUEST['expires_month']), 2, "0", STR_PAD_LEFT) . "-" . str_pad(intval($_REQUEST['expires_day']), 2, "0", STR_PAD_LEFT);
        $sqlQuery = "UPDATE {$wpdb->pmpro_memberships_users} SET enddate = '" . $expiration_date . "' WHERE status = 'active' AND membership_id = '" . intval($_REQUEST['membership_level']) . "' AND user_id = '" . $user_ID . "' LIMIT 1";
        if ($wpdb->query($sqlQuery)) {
            $expiration_changed = true;
        }
    } elseif (isset($_REQUEST['expires'])) {
        //already blank? have to check for null or '0000-00-00 00:00:00' or '' here.
        $sqlQuery = "SELECT user_id FROM {$wpdb->pmpro_memberships_users} WHERE (enddate IS NULL OR enddate = '' OR enddate = '0000-00-00 00:00:00') AND status = 'active' AND user_id = '" . $user_ID . "' LIMIT 1";
        $blank = $wpdb->get_var($sqlQuery);
        if (empty($blank)) {
            //null out the expiration
            $sqlQuery = "UPDATE {$wpdb->pmpro_memberships_users} SET enddate = NULL WHERE status = 'active' AND membership_id = '" . intval($_REQUEST['membership_level']) . "' AND user_id = '" . $user_ID . "' LIMIT 1";
            if ($wpdb->query($sqlQuery)) {
                $expiration_changed = true;
            }
        }
    }
    //emails if there was a change
    if (!empty($level_changed) || !empty($expiration_changed)) {
        //email to admin
        $pmproemail = new PMProEmail();
        if (!empty($expiration_changed)) {
            $pmproemail->expiration_changed = true;
        }
        $pmproemail->sendAdminChangeAdminEmail(get_userdata($user_ID));
        //send email
        if (!empty($_REQUEST['send_admin_change_email'])) {
            //email to member
            $pmproemail = new PMProEmail();
            if (!empty($expiration_changed)) {
                $pmproemail->expiration_changed = true;
            }
            $pmproemail->sendAdminChangeEmail(get_userdata($user_ID));
        }
    }
}
 /**
  * Filter pmpro_next_payment to get date via API if possible
  *
  * @since 1.8.6
  */
 static function pmpro_next_payment($timestamp, $user_id, $order_status)
 {
     //find the last order for this user
     if (!empty($user_id)) {
         //get last order
         $order = new MemberOrder();
         $order->getLastMemberOrder($user_id, $order_status);
         //check if this is a paypal express order with a subscription transaction id
         if (!empty($order->id) && !empty($order->subscription_transaction_id) && $order->gateway == "stripe") {
             //get the subscription and return the current_period end or false
             $subscription = $order->Gateway->getSubscription($order);
             if (!empty($subscription->current_period_end)) {
                 return $subscription->current_period_end;
             } else {
                 return false;
             }
         }
     }
     return $timestamp;
 }
     $enddate = "NULL";
 }
 //update membership_user table.
 if (!empty($discount_code) && !empty($use_discount_code)) {
     $discount_code_id = $wpdb->get_var("SELECT id FROM {$wpdb->pmpro_discount_codes} WHERE code = '" . $discount_code . "' LIMIT 1");
 } else {
     $discount_code_id = "";
 }
 //set the start date to NOW() but allow filters
 $startdate = apply_filters("pmpro_checkout_start_date", "'" . current_time("mysql") . "'", $user_id, $pmpro_level);
 $custom_level = array('user_id' => $user_id, 'membership_id' => $pmpro_level->id, 'code_id' => $discount_code_id, 'initial_payment' => $pmpro_level->initial_payment, 'billing_amount' => $pmpro_level->billing_amount, 'cycle_number' => $pmpro_level->cycle_number, 'cycle_period' => $pmpro_level->cycle_period, 'billing_limit' => $pmpro_level->billing_limit, 'trial_amount' => $pmpro_level->trial_amount, 'trial_limit' => $pmpro_level->trial_limit, 'startdate' => $startdate, 'enddate' => $enddate);
 if (pmpro_changeMembershipLevel($custom_level, $user_id, 'changed')) {
     //we're good
     //blank order for free levels
     if (empty($morder)) {
         $morder = new MemberOrder();
         $morder->InitialPayment = 0;
         $morder->Email = $bemail;
         $morder->gateway = "free";
     }
     //add an item to the history table, cancel old subscriptions
     if (!empty($morder)) {
         $morder->user_id = $user_id;
         $morder->membership_id = $pmpro_level->id;
         $morder->saveOrder();
     }
     //update the current user
     global $current_user;
     if (!$current_user->ID && $user->ID) {
         $current_user = $user;
     }
function pmprosm_addDiscountCodeUse($user_id, $level_id, $code_id)
{
    global $wpdb;
    $user = get_userdata($user_id);
    //add blank order
    $morder = new MemberOrder();
    $morder->InitialPayment = 0;
    $morder->Email = $user->user_email;
    $morder->gateway = "free";
    //sponsored
    $morder->user_id = $user_id;
    $morder->membership_id = $level_id;
    $morder->saveOrder();
    if (!empty($morder->id)) {
        $code_order_id = $morder->id;
    } else {
        $code_order_id = "";
    }
    global $wpdb;
    $wpdb->query("INSERT INTO {$wpdb->pmpro_discount_codes_uses} (code_id, user_id, order_id, timestamp) VALUES('" . esc_sql($code_id) . "', '" . esc_sql($user_id) . "', '" . intval($code_order_id) . "', now())");
}
function pmpro_insSaveOrder($txn_id, $last_order)
{
    global $wpdb;
    //check that txn_id has not been previously processed
    $old_txn = $wpdb->get_var("SELECT payment_transaction_id FROM {$wpdb->pmpro_membership_orders} WHERE payment_transaction_id = '" . $txn_id . "' LIMIT 1");
    if (empty($old_txn)) {
        //hook for successful subscription payments
        do_action("pmpro_subscription_payment_completed");
        //save order
        $morder = new MemberOrder();
        $morder->user_id = $last_order->user_id;
        $morder->membership_id = $last_order->membership_id;
        $morder->payment_transaction_id = $txn_id;
        $morder->subscription_transaction_id = $last_order->subscription_transaction_id;
        $morder->InitialPayment = $_POST['item_list_amount_1'];
        //not the initial payment, but the class is expecting that
        $morder->PaymentAmount = $_POST['item_list_amount_1'];
        $morder->FirstName = $_POST['customer_first_name'];
        $morder->LastName = $_POST['customer_last_name'];
        $morder->Email = $_POST['customer_email'];
        //save
        $morder->saveOrder();
        $morder->getMemberOrderByID($morder->id);
        //email the user their invoice
        $pmproemail = new PMProEmail();
        $pmproemail->sendInvoiceEmail(get_userdata($last_order->user_id), $morder);
        inslog("New order (" . $morder->code . ") created.");
        return true;
    } else {
        inslog("Duplicate Transaction ID: " . $txn_id);
        return false;
    }
}
function getOrderFromInvoiceEvent($event)
{
    //pause here to give PMPro a chance to finish checkout
    sleep(PMPRO_STRIPE_WEBHOOK_DELAY);
    $invoice_id = $event->data->object->id;
    $order = new MemberOrder();
    $order->getMemberOrderByPaymentTransactionID($invoice_id);
    if (!empty($order->id)) {
        return $order;
    } else {
        return false;
    }
}
function pmproues_wp_ajax()
{
    //make sure the user is an admin
    if (!current_user_can('manage_options')) {
        exit;
    }
    //get values
    $gateway = $_REQUEST['gateway'];
    $level = $_REQUEST['level'];
    $billing_amount = $_REQUEST['billing_amount'];
    $cycle_number = $_REQUEST['cycle_number'];
    $cycle_period = $_REQUEST['cycle_period'];
    $live = $_REQUEST['live'];
    if (empty($_REQUEST['limit'])) {
        $limit = 5;
    } else {
        $limit = intval($_REQUEST['limit']);
    }
    //continue progress?
    $hash = substr(md5($gateway . $level . $billing_amount . $cycle_number . $cycle_period . $live), 0, 16);
    $last_user = get_transient('pmproues_update_last_row_' . $hash);
    if (empty($last_user)) {
        $last_user = 0;
    }
    //find members
    global $wpdb;
    $sqlQuery = "SELECT user_id FROM {$wpdb->pmpro_memberships_users} WHERE user_id > {$last_user} AND membership_id = '" . intval($level) . "' AND status = 'active' ORDER BY user_id LIMIT {$limit}";
    $member_ids = $wpdb->get_col($sqlQuery);
    if (empty($member_ids)) {
        delete_transient('pmproues_update_last_row_' . $hash);
        echo "done";
        exit;
    } else {
        //update subs
        foreach ($member_ids as $member_id) {
            $last_user = $member_id;
            echo "\n----\nMember ID #" . $member_id . ". ";
            //get user
            $user = get_userdata($member_id);
            //no user?
            if (empty($user) || empty($user->ID)) {
                echo "Could not find user. ";
                continue;
            } else {
                echo "User found. (" . $user->user_email . ") ";
            }
            //get order
            $order = new MemberOrder();
            $order->getLastMemberOrder($user->ID);
            //no order?
            if (empty($order->id)) {
                echo "Could not find order. ";
                continue;
            } else {
                echo "Order found. (" . $order->code . ") ";
            }
            //different gateway?
            if ($order->gateway != $gateway) {
                echo "Different gateway. ";
                continue;
            } else {
                echo "Gateway matches. ";
            }
            //okay find the sub
            if (empty($order->subscription_transaction_id)) {
                echo "No subscription transaction ID. ";
                continue;
            } else {
                echo "Subscription ID found. ";
            }
            if (empty($live)) {
                echo "Would have updated the subscription here, but we're just testing. ";
                continue;
            }
            //let's do it live!
            if ($gateway == "stripe") {
                /*
                	Note: This code is copied and modified from the user_profile_fields_save method.
                */
                //get level for user
                $user_level = pmpro_getMembershipLevelForUser($user->ID);
                //get current plan at Stripe to get payment date
                $order->Gateway->getCustomer($order);
                $subscription = $order->Gateway->getSubscription($order);
                if (!empty($subscription)) {
                    $end_timestamp = $subscription->current_period_end;
                    //cancel the old subscription
                    if (!$order->Gateway->cancelSubscriptionAtGateway($subscription)) {
                        echo "Could not cancel the old subscription. Skipping. ";
                        continue;
                    }
                }
                //if we didn't get an end date, let's set one one cycle out
                if (empty($end_timestamp)) {
                    $end_timestamp = strtotime("+" . $cycle_number . " " . $cycle_period, current_time('timestamp'));
                }
                //build order object
                $update_order = new MemberOrder();
                $update_order->setGateway('stripe');
                $update_order->user_id = $user->ID;
                $update_order->Email = $user->user_email;
                $update_order->membership_id = $user_level->id;
                $update_order->membership_name = $user_level->name;
                $update_order->InitialPayment = 0;
                $update_order->PaymentAmount = $billing_amount;
                $update_order->ProfileStartDate = date("Y-m-d", $end_timestamp);
                $update_order->BillingPeriod = $cycle_period;
                $update_order->BillingFrequency = $cycle_number;
                //need filter to reset ProfileStartDate
                add_filter('pmpro_profile_start_date', create_function('$startdate, $order', 'return "' . $update_order->ProfileStartDate . 'T0:0:0";'), 10, 2);
                //update subscription
                $update_order->Gateway->subscribe($update_order, false);
                //update membership
                $sqlQuery = "UPDATE {$wpdb->pmpro_memberships_users}\r\n\t\t\t\t\t\t\t\tSET billing_amount = '" . esc_sql($billing_amount) . "',\r\n\t\t\t\t\t\t\t\t\tcycle_number = '" . esc_sql($cycle_number) . "',\r\n\t\t\t\t\t\t\t\t\tcycle_period = '" . esc_sql($cycle_period) . "',\r\n\t\t\t\t\t\t\t\t\ttrial_amount = '',\r\n\t\t\t\t\t\t\t\t\ttrial_limit = ''\r\n\t\t\t\t\t\t\t\tWHERE user_id = '" . esc_sql($user->ID) . "'\r\n\t\t\t\t\t\t\t\t\tAND membership_id = '" . esc_sql($order->membership_id) . "'\r\n\t\t\t\t\t\t\t\t\tAND status = 'active'\r\n\t\t\t\t\t\t\t\tLIMIT 1";
                $wpdb->query($sqlQuery);
                //save order so we know which plan to look for at stripe (order code = plan id)
                $update_order->status = "success";
                $update_order->saveOrder();
                echo "ORDER UPDATED!";
            }
        }
    }
    set_transient('pmproues_update_last_row_' . $hash, $last_user, 60 * 60 * 24);
    exit;
}
Example #29
0
    $user = get_user_by('email', $_REQUEST['email']);
    $order = new MemberOrder($_REQUEST['order']);
    if ($email->sendBillableInvoiceEmail($user, $order)) {
        $pmpro_msg = __("Invoice emailed successfully.", "pmpro");
        $pmpro_msgt = "success";
    } else {
        $pmpro_msg = __("Error emailing invoice.", "pmpro");
        $pmpro_msgt = "error";
    }
    //clean up so we stay on the orders list view
    unset($_REQUEST['order']);
    $order = null;
}
//deleting?
if (!empty($_REQUEST['delete'])) {
    $dorder = new MemberOrder(intval($_REQUEST['delete']));
    if ($dorder->deleteMe()) {
        $pmpro_msg = __("Order deleted successfully.", "pmpro");
        $pmpro_msgt = "success";
    } else {
        $pmpro_msg = __("Error deleting order.", "pmpro");
        $pmpro_msgt = "error";
    }
}
$thisyear = date_i18n("Y");
//this array stores fields that should be read only
$read_only_fields = apply_filters("pmpro_orders_read_only_fields", array("code", "payment_transaction_id", "subscription_transaction_id"));
//saving?
if (!empty($_REQUEST['save'])) {
    //start with old order if applicable
    $order_id = intval($_REQUEST['order']);
 /**
  * Filter pmpro_next_payment to get date via API if possible
  *
  * @since 1.8.5
  */
 static function pmpro_next_payment($timestamp, $user_id, $order_status)
 {
     //find the last order for this user
     if (!empty($user_id)) {
         //get last order
         $order = new MemberOrder();
         $order->getLastMemberOrder($user_id, $order_status);
         //check if this is a paypal express order with a subscription transaction id
         if (!empty($order->id) && !empty($order->subscription_transaction_id) && $order->gateway == "paypalexpress") {
             //get the subscription status
             $status = $order->getGatewaySubscriptionStatus();
             d($status);
             if (!empty($status) && !empty($status['NEXTBILLINGDATE'])) {
                 //found the next billing date at PayPal, going to use that
                 $timestamp = strtotime(urldecode($status['NEXTBILLINGDATE']), current_time('timestamp'));
             } elseif (!empty($status) && !empty($status['PROFILESTARTDATE']) && $order_status == "cancelled") {
                 //startdate is in the future and we cancelled so going to use that as the next payment date
                 $startdate_timestamp = strtotime(urldecode($status['PROFILESTARTDATE']), current_time('timestamp'));
                 if ($startdate_timestamp > current_time('timestamp')) {
                     $timestamp = $startdate_timestamp;
                 }
             }
         }
     }
     return $timestamp;
 }