Example #1
0
function pmpro_cron_expire_memberships()
{
    global $wpdb;
    //make sure we only run once a day
    $today = date("Y-m-d", current_time("timestamp"));
    //look for memberships that expired before today
    $sqlQuery = "SELECT mu.user_id, mu.membership_id, mu.startdate, mu.enddate FROM {$wpdb->pmpro_memberships_users} mu WHERE mu.status = 'active' AND mu.enddate IS NOT NULL AND mu.enddate <> '' AND mu.enddate <> '0000-00-00 00:00:00' AND DATE(mu.enddate) <= '" . $today . "' ORDER BY mu.enddate";
    if (defined('PMPRO_CRON_LIMIT')) {
        $sqlQuery .= " LIMIT " . PMPRO_CRON_LIMIT;
    }
    $expired = $wpdb->get_results($sqlQuery);
    foreach ($expired as $e) {
        do_action("pmpro_membership_pre_membership_expiry", $e->user_id, $e->membership_id);
        //remove their membership
        pmpro_changeMembershipLevel(false, $e->user_id, 'expired');
        do_action("pmpro_membership_post_membership_expiry", $e->user_id, $e->membership_id);
        $send_email = apply_filters("pmpro_send_expiration_email", true, $e->user_id);
        if ($send_email) {
            //send an email
            $pmproemail = new PMProEmail();
            $euser = get_userdata($e->user_id);
            $pmproemail->sendMembershipExpiredEmail($euser);
            if (current_user_can('manage_options')) {
                printf(__("Membership expired email sent to %s. ", "pmpro"), $euser->user_email);
            } else {
                echo ". ";
            }
        }
    }
}
Example #2
0
	function pmpro_cron_expire_memberships()
	{
		global $wpdb;
				
		//make sure we only run once a day
		$today = date("Y-m-d");
		
		//look for memberships that expired before today
		$sqlQuery = "SELECT mu.user_id, mu.membership_id, mu.startdate, mu.enddate FROM $wpdb->pmpro_memberships_users mu WHERE mu.status = 'active' AND mu.enddate IS NOT NULL AND mu.enddate <> '' AND mu.enddate <> '0000-00-00 00:00:00' AND DATE(mu.enddate) <= '" . $today . "' ORDER BY mu.enddate";
						
		$expired = $wpdb->get_results($sqlQuery);
				
		foreach($expired as $e)
		{						
			//remove their membership
			pmpro_changeMembershipLevel(false, $e->user_id);
			
			$send_email = apply_filters("pmpro_send_expiration_email", true, $e->user_id);
			if($send_email)
			{
				//send an email
				$pmproemail = new PMProEmail();
				$euser = get_userdata($e->user_id);		
				$pmproemail->sendMembershipExpiredEmail($euser);
				
				echo "Membership expired email sent to " . $euser->user_email . ". ";
			}
		}
	}
function pmpro_delete_user($user_id = NULL)
{
    global $wpdb;
    //changing their membership level to 0 will cancel any subscription and remove their membership level entry
    //we don't remove the orders because it would affect reporting
    if (pmpro_changeMembershipLevel(0, $user_id)) {
        //okay
    } else {
        //okay, guessing they didn't have a level
    }
}
function pmprosl_pmpro_default_registration_level($user_id)
{
    global $pmpro_level;
    //if default is set and we're not otherwise checking out
    $default_level = get_option('pmpro_social_login_default_level');
    if (!empty($default_level) && empty($pmpro_level) && empty($_REQUEST['level'])) {
        pmpro_changeMembershipLevel($default_level, $user_id);
        $user = get_userdata($user_id);
        $user->membership_level = pmpro_getMembershipLevelForUser($user->ID);
        //send email to member
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutEmail($user, false);
        //send email to admin
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutAdminEmail($user, false);
    }
}
function pmpro_delete_user($user_id = NULL)
{
    global $wpdb;
    //changing their membership level to 0 will cancel any subscription and remove their membership level entry
    //we don't remove the orders because it would affect reporting
    if (pmpro_changeMembershipLevel(0, $user_id)) {
        //okay
    } else {
        //couldn't delete the subscription
        //we should probably notify the admin
        global $pmpro_error;
        if (!empty($pmpro_error)) {
            $pmproemail = new PMProEmail();
            $pmproemail->data = array("body" => "<p>" . sprintf(__("There was an error canceling the subscription for user with ID=%s. You will want to check your payment gateway to see if their subscription is still active.", "pmpro"), strval($user_id)) . "</p><p>Error: " . $pmpro_error . "</p>");
            $last_order = $wpdb->get_row("SELECT * FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' ORDER BY timestamp DESC LIMIT 1");
            if (!empty($last_order)) {
                $pmproemail->data["body"] .= "<p>Last Invoice:<br />" . nl2br(var_export($last_order, true)) . "</p>";
            }
            $pmproemail->sendEmail(get_bloginfo("admin_email"));
        }
    }
}
Example #6
0
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;
        }
        //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));
        }
    }
}
Example #7
0
function check_benefactor_status($email)
{
    if (!$email) {
        $user = wp_get_current_user();
    } else {
        $user = get_user_by_email($email);
    }
    $membership = pmpro_getMembershipLevelForUser($user->ID);
    if (!$membership->ID) {
        return;
    }
    $invoices = getInvoicesRecurring($user);
    if (!empty($invoices)) {
        $gateway = new PMProGateway_paypalexpress();
        $lastOrderInfo = $gateway->getSubscriptionStatus($invoices[0]);
        if ($lastOrderInfo['STATUS'] == 'Cancelled') {
            // neu cancel tu paypal => cancel benefactor
            pmpro_changeMembershipLevel(0, $user->ID, $current_user->membership_level->ID, false);
        }
    } else {
        pmpro_changeMembershipLevel(0, $user->ID, $current_user->membership_level->ID, false);
    }
    return;
}
function pmprowoo_cancelled_subscription($user_id, $subscription_key)
{
    global $pmprowoo_product_levels;
    //don't bother if array is empty
    if (empty($pmprowoo_product_levels)) {
        return;
    }
    /*
        does this order contain a membership product?
    */
    $subscription = WC_Subscriptions_Manager::get_users_subscription($user_id, $subscription_key);
    if (isset($subscription['product_id']) && isset($subscription['order_id'])) {
        $product_id = $subscription['product_id'];
        $order_id = $subscription['order_id'];
        //membership product ids
        $product_ids = array_keys($pmprowoo_product_levels);
        //get order
        $order = new WC_Order($order_id);
        //does the order have a user id and some products?
        if (!empty($order->customer_user) && !empty($product_id)) {
            //is there a membership level for this product?
            if (in_array($product_id, $product_ids)) {
                //add the user to the level
                pmpro_changeMembershipLevel(0, $order->customer_user);
            }
        }
    }
}
Example #9
0
function pmpro_insChangeMembershipLevel($txn_id, &$morder)
{
    $recurring = pmpro_getParam('rectoken', 'POST');
    //filter for level
    $morder->membership_level = apply_filters("pmpro_inshandler_level", $morder->membership_level, $morder->user_id);
    //set the start date to current_time('mysql') but allow filters (documented in preheaders/checkout.php)
    $startdate = apply_filters("pmpro_checkout_start_date", "'" . current_time('mysql') . "'", $morder->user_id, $morder->membership_level);
    //fix expiration date
    if (!empty($morder->membership_level->expiration_number)) {
        $enddate = "'" . date("Y-m-d", strtotime("+ " . $morder->membership_level->expiration_number . " " . $morder->membership_level->expiration_period, current_time("timestamp"))) . "'";
    } else {
        $enddate = "NULL";
    }
    //filter the enddate (documented in preheaders/checkout.php)
    $enddate = apply_filters("pmpro_checkout_end_date", $enddate, $morder->user_id, $morder->membership_level, $startdate);
    //get discount code
    $morder->getDiscountCode();
    if (!empty($morder->discount_code)) {
        //update membership level
        $morder->getMembershipLevel(true);
        $discount_code_id = $morder->discount_code->id;
    } else {
        $discount_code_id = "";
    }
    //custom level to change user to
    $custom_level = array('user_id' => $morder->user_id, 'membership_id' => $morder->membership_level->id, 'code_id' => $discount_code_id, 'initial_payment' => $morder->membership_level->initial_payment, 'billing_amount' => $morder->membership_level->billing_amount, 'cycle_number' => $morder->membership_level->cycle_number, 'cycle_period' => $morder->membership_level->cycle_period, 'billing_limit' => $morder->membership_level->billing_limit, 'trial_amount' => $morder->membership_level->trial_amount, 'trial_limit' => $morder->membership_level->trial_limit, 'startdate' => $startdate, 'enddate' => $enddate);
    global $pmpro_error;
    if (!empty($pmpro_error)) {
        //echo $pmpro_error;
        fnlog($pmpro_error);
    }
    if (pmpro_changeMembershipLevel($custom_level, $morder->user_id) !== false) {
        //update order status and transaction ids
        $morder->status = "success";
        $morder->payment_transaction_id = $txn_id;
        if (!$recurring) {
            $morder->subscription_transaction_id = $txn_id;
        } else {
            $morder->subscription_transaction_id = '';
        }
        $morder->saveOrder();
        //add discount code use
        if (!empty($discount_code) && !empty($use_discount_code)) {
            $wpdb->query("INSERT INTO {$wpdb->pmpro_discount_codes_uses} (code_id, user_id, order_id, timestamp) VALUES('" . $discount_code_id . "', '" . $morder->user_id . "', '" . $morder->id . "', '" . current_time('mysql') . "')");
        }
        //hook
        do_action("pmpro_after_checkout", $morder->user_id);
        //print_r ($morder); die;
        //setup some values for the emails
        if (!empty($morder)) {
            $invoice = new MemberOrder($morder->id);
        } else {
            $invoice = NULL;
        }
        fnlog("CHANGEMEMBERSHIPLEVEL: ORDER: " . var_export($morder, true) . "\n---\n");
        $user = get_userdata($morder->user_id);
        if (empty($user)) {
            return false;
        }
        $user->membership_level = $morder->membership_level;
        //make sure they have the right level info
        //send email to member
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutEmail($user, $invoice);
        //send email to admin
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutAdminEmail($user, $invoice);
        return true;
    } else {
        return false;
    }
}
    }
    do_action("pmpro_save_membership_level", $saveid);
} elseif ($action == "delete_membership_level") {
    global $wpdb;
    $ml_id = $_REQUEST['deleteid'];
    if ($ml_id > 0) {
        do_action("pmpro_delete_membership_level", $ml_id);
        //remove any categories from the ml
        $sqlQuery = "DELETE FROM {$wpdb->pmpro_memberships_categories} WHERE membership_id = '{$ml_id}'";
        $r1 = $wpdb->query($sqlQuery);
        //cancel any subscriptions to the ml
        $r2 = true;
        $user_ids = $wpdb->get_col("SELECT user_id FROM {$wpdb->pmpro_memberships_users} WHERE membership_id = '{$ml_id}' AND status = 'active'");
        foreach ($user_ids as $user_id) {
            //change there membership level to none. that will handle the cancel
            if (pmpro_changeMembershipLevel(0, $user_id)) {
                //okay
            } else {
                //couldn't delete the subscription
                //we should probably notify the admin
                $pmproemail = new PMProEmail();
                $pmproemail->data = array("body" => "<p>" . sprintf(__("There was an error canceling the subscription for user with ID=%d. You will want to check your payment gateway to see if their subscription is still active.", "pmpro"), $user_id) . "</p>");
                $last_order = $wpdb->get_row("SELECT * FROM {$wpdb->pmpro_membership_orders} WHERE user_id = '" . $user_id . "' ORDER BY timestamp DESC LIMIT 1");
                if ($last_order) {
                    $pmproemail->data["body"] .= "<p>" . __("Last Invoice", "pmpro") . ":<br />" . nl2br(var_export($last_order, true)) . "</p>";
                }
                $pmproemail->sendEmail(get_bloginfo("admin_email"));
                $r2 = false;
            }
        }
        //delete the ml
 } else {
     //other user meta
     update_user_meta($user_id, "user_notes", $user_notes);
     //figure out start date
     $now = current_time('timestamp');
     $startdate = date("Y-m-d", $now);
     //figure out end date
     if (!empty($_REQUEST['expires'])) {
         //update the expiration date
         $enddate = 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);
     } else {
         $enddate = '';
     }
     //add membership level
     $custom_level = array('user_id' => $user_id, 'membership_id' => $membership_level, 'code_id' => '', 'initial_payment' => $total, 'billing_amount' => '', 'cycle_number' => '', 'cycle_period' => '', 'billing_limit' => '', 'trial_amount' => '', 'trial_limit' => '', 'startdate' => $startdate, 'enddate' => $enddate);
     pmpro_changeMembershipLevel($custom_level, $user_id);
     //add order
     //blank order for free levels
     if (empty($morder)) {
         $morder = new MemberOrder();
         $morder->InitialPayment = $total;
         $morder->Email = $user_email;
         $morder->gateway = $gateway;
         $morder->status = "success";
     }
     //add an item to the history table, cancel old subscriptions
     if (!empty($morder)) {
         $morder->user_id = $user_id;
         $morder->membership_id = $membership_level;
         $morder->notes = $order_notes;
         $morder->saveOrder();
function pmpro_insRecurringRestarted($morder)
{
    global $pmpro_error;
    //hook to do other stuff when payments restart
    do_action("pmpro_subscription_recuring_restarted", $last_order);
    $worked = pmpro_changeMembershipLevel($morder->membership_level->id, $morder->user->ID);
    if ($worked === true) {
        //$pmpro_msg = __("Your membership has been cancelled.", 'pmpro');
        //$pmpro_msgt = "pmpro_success";
        //send an email to the member
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutEmail($morder->user, $morder);
        //send email to admin
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutAdminEmail($morder->user, $morder);
        inslog("Subscription restarted due to 'recurring restarted' INS notification.");
        return true;
    } else {
        return false;
    }
}
function pmpro_payflow_recurring_orders()
{
    //is PMPro even active?
    if (!function_exists('pmpro_hasMembershipLevel')) {
        return;
    }
    global $wpdb;
    $now = current_time('timestamp');
    //between what hours should the cron run?
    $cron_start = 1;
    //1 AM
    $cron_end = 6;
    //6 AM
    $current_hour = date('G', $now);
    if ($current_hour > $cron_end || $current_hour < $cron_start) {
        return;
    }
    //where did we leave off?
    if (isset($_REQUEST['start'])) {
        $start = intval($_REQUEST['start']);
        delete_option('pmpro_pfro_paused');
    } else {
        $start = get_option('payflow_recurring_orders_cron_count', 0);
    }
    //are we paused? value is timestamp. if set wait until then
    $paused = get_option('pmpro_pfro_paused', false);
    if (!empty($paused) && $paused > $now) {
        return;
    }
    //how many subscriptions to run at one time. based on your server speed and timeout limits/etc.
    $nper = 50;
    //next one
    $end = intval($start) + intval($nper);
    //get subs
    $sqlQuery = "\n\t\tSELECT SQL_CALC_FOUND_ROWS user_id FROM\n\t\t(\n\t\t\tSELECT mu.user_id,\n\t\t\t\tCASE mu.cycle_period\n\t\t\t\t\tWHEN 'Day' THEN date_add(mo.timestamp, INTERVAL mu.cycle_number DAY)\n\t\t\t\t\tWHEN 'Month' THEN date_add(mo.timestamp, INTERVAL mu.cycle_number MONTH)\n\t\t\t\t\tWHEN 'Week' THEN date_add(mo.timestamp, INTERVAL mu.cycle_number WEEK)\n\t\t\t\t\tWHEN 'Year' THEN date_add(mo.timestamp, INTERVAL mu.cycle_number YEAR)\n\t\t\t\tEND as next_payment_date\n\t\t\tFROM {$wpdb->pmpro_memberships_users} mu\n\t\t\t\tLEFT JOIN {$wpdb->pmpro_membership_orders} mo\n\t\t\t\t\tON mo.id = (\n\t\t\t\t\t\tSELECT id FROM {$wpdb->pmpro_membership_orders} WHERE gateway = 'payflowpro' AND status NOT IN('review', 'token', 'pending') AND user_id = mu.user_id ORDER BY id DESC LIMIT 1\n\t\t\t\t\t)\n\t\t\tWHERE mu.status = 'active'\n\t\t\t\tAND mo.subscription_transaction_id <> ''\n\t\t) members\n\t\tWHERE DATEDIFF('" . current_time('mysql') . "', next_payment_date) >= 0\n\t\tLIMIT {$start}, {$nper}\n\t";
    $sub_user_ids = $wpdb->get_col($sqlQuery);
    $count = $wpdb->get_var('SELECT FOUND_ROWS()');
    echo "Processing " . intval($start) . " to " . (intval($start) + intval($nper)) . " of " . $count . " subscriptions.<hr />";
    //if no more subs, pause until tomorrow
    if (empty($sub_user_ids)) {
        echo "All done. Pausing until tomorrow.<br />";
        $tomorrow = strtotime(date("Y-m-d 00:00:00", $now + 3600 * 24));
        update_option('pmpro_pfro_paused', $tomorrow);
        update_option('payflow_recurring_orders_cron_count', 0);
        return;
    }
    $failed_payment_emails = array();
    //loop through subs
    foreach ($sub_user_ids as $user_id) {
        $user = get_userdata($user_id);
        if (empty($user->ID)) {
            echo "Coundn't find user #" . $user_id . "...<br /><hr />";
            continue;
        }
        echo "Checking for recurring orders for user #" . $user->ID . " " . $user->user_login . " (" . $user->user_email . ")...<br />";
        $last_order = new MemberOrder();
        $last_order->getLastMemberOrder($user_id);
        if (!empty($last_order->id)) {
            echo "- Last order found. #" . $last_order->id . ", Code: " . $last_order->code . ", SubID: " . $last_order->subscription_transaction_id . ".<br />";
        } else {
            echo "- No last order. Skipping.";
            echo "<hr />";
            continue;
        }
        //is it even Payflow?
        if ($last_order->gateway != "payflowpro") {
            echo "- Order is for '" . $last_order->gateway . "' gateway.<br />";
            echo "<hr />";
            continue;
        }
        //check subscription
        if (!empty($last_order->subscription_transaction_id)) {
            echo "- Checking subscription #" . $last_order->subscription_transaction_id . ".<br />";
            $status = pmpropfro_getSubscriptionPayments($last_order);
            //find orders
            $payments = pmpropfro_processPaymentHistory($status);
            if (!empty($payments)) {
                foreach ($payments as $payment) {
                    if ($payment['P_TRANSTATE'] == 1 || $payment['P_TRANSTATE'] == 11) {
                        echo "- Failed payment #" . $payment['P_PNREF'] . ".";
                        //check if we have this one already
                        $old_order = new MemberOrder();
                        $old_order->getMemberOrderByPaymentTransactionID($payment['P_PNREF']);
                        if (empty($old_order->id)) {
                            $failed_payment_emails[] = $user->user_email;
                            //not there yet, add it
                            $morder = new MemberOrder();
                            $morder->user_id = $last_order->user_id;
                            $morder->membership_id = $last_order->membership_id;
                            $morder->payment_transaction_id = $payment['P_PNREF'];
                            $morder->subscription_transaction_id = $last_order->subscription_transaction_id;
                            $morder->InitialPayment = $payment['P_AMT'];
                            //not the initial payment, but the class is expecting that
                            $morder->PaymentAmount = $payment['P_AMT'];
                            $morder->status = "error";
                            //save
                            $morder->saveOrder();
                            $morder->getMemberOrderByID($morder->id);
                            echo " Saving order.";
                            //this will affect the main query, so need to roll back the "end" 1 space
                            $end--;
                            //unless there is another non-failed payment more recent, cancel their membership
                            if (!pmpropfro_paymentAfter($payments, strtotime($payment['P_TRANSTIME']))) {
                                //cancel membership
                                pmpro_changeMembershipLevel(0, $user_id);
                                echo " Membership cancelled. Member emailed.";
                                //notify them
                                $myemail = new PMProEmail();
                                $myemail->sendCancelEmail($user);
                            } else {
                                echo " More recent successful order. So not cancelling membership.";
                            }
                        } else {
                            echo " Already logged.";
                        }
                        echo "<br />";
                    } elseif ($payment['P_TRANSTATE'] == 8) {
                        //check if we have this one already
                        $old_order = new MemberOrder();
                        $old_order->getMemberOrderByPaymentTransactionID($payment['P_PNREF']);
                        if (empty($old_order->id)) {
                            //not there yet, add it
                            $morder = new MemberOrder();
                            $morder->user_id = $last_order->user_id;
                            $morder->membership_id = $last_order->membership_id;
                            $morder->payment_transaction_id = $payment['P_PNREF'];
                            $morder->subscription_transaction_id = $last_order->subscription_transaction_id;
                            $morder->InitialPayment = $payment['P_AMT'];
                            //not the initial payment, but the class is expecting that
                            $morder->PaymentAmount = $payment['P_AMT'];
                            $morder->status = "success";
                            //save
                            $morder->saveOrder();
                            $morder->getMemberOrderByID($morder->id);
                            //this will affect the main query, so need to roll back the "end" 1 space
                            $end--;
                            if (!empty($morder->id)) {
                                //update the timestamp
                                $timestamp = date("Y-m-d H:i:s", strtotime($payment['P_TRANSTIME']));
                                $wpdb->query("UPDATE {$wpdb->pmpro_membership_orders} SET timestamp = '" . $timestamp . "' WHERE id = '" . $morder->id . "' LIMIT 1");
                                echo "<strong>- Order added. #" . $morder->id . ".</strong><br />";
                                //email the user their invoice
                                $pmproemail = new PMProEmail();
                                $pmproemail->sendInvoiceEmail($user, $morder);
                                echo "- Invoice email sent to " . $user->user_email . ".";
                            } else {
                                echo "- Error adding order.";
                            }
                        } else {
                            echo "- Order already saved for #" . $payment['P_TRANSTATE'] . ".<br />";
                        }
                    } else {
                        echo "<strong>- Payment " . $payment['P_PNREF'] . " has status #" . $payment['P_TRANSTATE'] . " so not saving.</strong><br />";
                    }
                }
            } else {
                echo "- No payments found.<br />";
            }
        }
        echo "<hr />";
        echo "Going to start with #" . $end . " next time.";
        update_option('payflow_recurring_orders_cron_count', $end);
    }
    echo "<hr />";
    foreach ($failed_payment_emails as $email) {
        echo $email . "<br />";
    }
}
function pmpro_ipnChangeMembershipLevel($txn_id, &$morder)
{
    //filter for level
    $morder->membership_level = apply_filters("pmpro_ipnhandler_level", $morder->membership_level, $morder->user_id);
    //fix expiration date
    if (!empty($morder->membership_level->expiration_number)) {
        $enddate = "'" . date("Y-m-d", strtotime("+ " . $morder->membership_level->expiration_number . " " . $morder->membership_level->expiration_period, current_time("timestamp"))) . "'";
    } else {
        $enddate = "NULL";
    }
    //get discount code
    $morder->getDiscountCode();
    if (!empty($morder->discount_code)) {
        //update membership level
        $morder->getMembershipLevel(true);
        $discount_code_id = $morder->discount_code->id;
    } else {
        $discount_code_id = "";
    }
    //set the start date to current_time('timestamp') but allow filters
    $startdate = apply_filters("pmpro_checkout_start_date", "'" . current_time('mysql') . "'", $morder->user_id, $morder->membership_level);
    //custom level to change user to
    $custom_level = array('user_id' => $morder->user_id, 'membership_id' => $morder->membership_level->id, 'code_id' => $discount_code_id, 'initial_payment' => $morder->membership_level->initial_payment, 'billing_amount' => $morder->membership_level->billing_amount, 'cycle_number' => $morder->membership_level->cycle_number, 'cycle_period' => $morder->membership_level->cycle_period, 'billing_limit' => $morder->membership_level->billing_limit, 'trial_amount' => $morder->membership_level->trial_amount, 'trial_limit' => $morder->membership_level->trial_limit, 'startdate' => $startdate, 'enddate' => $enddate);
    global $pmpro_error;
    if (!empty($pmpro_error)) {
        echo $pmpro_error;
        ipnlog($pmpro_error);
    }
    //change level and continue "checkout"
    if (pmpro_changeMembershipLevel($custom_level, $morder->user_id) !== false) {
        //update order status and transaction ids
        $morder->status = "success";
        $morder->payment_transaction_id = $txn_id;
        if (!empty($_POST['subscr_id'])) {
            $morder->subscription_transaction_id = $_POST['subscr_id'];
        } else {
            $morder->subscription_transaction_id = "";
        }
        $morder->saveOrder();
        //add discount code use
        if (!empty($discount_code) && !empty($use_discount_code)) {
            $wpdb->query("INSERT INTO {$wpdb->pmpro_discount_codes_uses} (code_id, user_id, order_id, timestamp) VALUES('" . $discount_code_id . "', '" . $morder->user_id . "', '" . $morder->id . "', '" . current_time('mysql') . "");
        }
        //save first and last name fields
        if (!empty($_POST['first_name'])) {
            $old_firstname = get_user_meta($morder->user_id, "first_name", true);
            if (empty($old_firstname)) {
                update_user_meta($morder->user_id, "first_name", $_POST['first_name']);
            }
        }
        if (!empty($_POST['last_name'])) {
            $old_lastname = get_user_meta($morder->user_id, "last_name", true);
            if (empty($old_lastname)) {
                update_user_meta($morder->user_id, "last_name", $_POST['last_name']);
            }
        }
        //hook
        do_action("pmpro_after_checkout", $morder->user_id);
        //setup some values for the emails
        if (!empty($morder)) {
            $invoice = new MemberOrder($morder->id);
        } else {
            $invoice = NULL;
        }
        $user = get_userdata($morder->user_id);
        $user->membership_level = $morder->membership_level;
        //make sure they have the right level info
        //send email to member
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutEmail($user, $invoice);
        //send email to admin
        $pmproemail = new PMProEmail();
        $pmproemail->sendCheckoutAdminEmail($user, $invoice);
        return true;
    } else {
        return false;
    }
}
Example #15
0
	function pmpro_ipnChangeMembershipLevel($txn_id, &$morder)
	{
		//filter for level
		$morder->membership_level = apply_filters("pmpro_ipnhandler_level", $morder->membership_level, $morder->user_id);
					
		//fix expiration date		
		if(!empty($morder->membership_level->expiration_number))
		{
			$enddate = "'" . date("Y-m-d", strtotime("+ " . $morder->membership_level->expiration_number . " " . $morder->membership_level->expiration_period)) . "'";
		}
		else
		{
			$enddate = "NULL";
		}
		
		//get discount code		(NOTE: but discount_code isn't set here. How to handle discount codes for PayPal Standard?)
		$use_discount_code = true;		//assume yes
		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", "NOW()", $morder->user_id, $morder->membership_level);
		
		//custom level to change user to
		$custom_level = array(
			'user_id' => $morder->user_id,
			'membership_id' => $morder->membership_level->id,
			'code_id' => $discount_code_id,
			'initial_payment' => $morder->membership_level->initial_payment,
			'billing_amount' => $morder->membership_level->billing_amount,
			'cycle_number' => $morder->membership_level->cycle_number,
			'cycle_period' => $morder->membership_level->cycle_period,
			'billing_limit' => $morder->membership_level->billing_limit,
			'trial_amount' => $morder->membership_level->trial_amount,
			'trial_limit' => $morder->membership_level->trial_limit,
			'startdate' => $startdate,
			'enddate' => $enddate);

		global $pmpro_error;
		if(!empty($pmpro_error))
		{
			echo $pmpro_error;
			ipnlog($pmpro_error);				
		}
		
		if(pmpro_changeMembershipLevel($custom_level, $morder->user_id) !== false)
		{
			//update order status and transaction ids					
			$morder->status = "success";
			$morder->payment_transaction_id = $txn_id;
			if(!empty($_POST['subscr_id']))
				$morder->subscription_transaction_id = $_POST['subscr_id'];
			else
				$morder->subscription_transaction_id = "";
			$morder->saveOrder();
			
			//add discount code use
			if(!empty($discount_code) && !empty($use_discount_code))
			{
				$wpdb->query("INSERT INTO $wpdb->pmpro_discount_codes_uses (code_id, user_id, order_id, timestamp) VALUES('" . $discount_code_id . "', '" . $current_user->ID . "', '" . $morder->id . "', now())");					
			}									
		
			//save first and last name fields
			if(!empty($_POST['first_name']))
			{
				$old_firstname = get_user_meta($morder->user_id, "first_name", true);
				if(!empty($old_firstname))
					update_user_meta($morder->user_id, "first_name", $_POST['first_name']);
			}
			if(!empty($_POST['last_name']))
			{
				$old_lastname = get_user_meta($morder->user_id, "last_name", true);
				if(!empty($old_lastname))
					update_user_meta($morder->user_id, "last_name", $_POST['last_name']);
			}
												
			//hook
			do_action("pmpro_after_checkout", $morder->user_id);						
		
			//setup some values for the emails
			if(!empty($morder))
				$invoice = new MemberOrder($morder->id);						
			else
				$invoice = NULL;
		
			$user = get_userdata($morder->user_id);
			$user->membership_level = $morder->membership_level;		//make sure they have the right level info
		
			//send email to member
			$pmproemail = new PMProEmail();				
			$pmproemail->sendCheckoutEmail($user, $invoice);
										
			//send email to admin
			$pmproemail = new PMProEmail();
			$pmproemail->sendCheckoutAdminEmail($user, $invoice);
			
			return true;
		}
		else
			return false;
	}
function pmprosm_changeMembershipLevelWithCode($level_id, $user_id, $code_id)
{
    $child_level = pmpro_getLevel($level_id);
    //set the start date to NOW() but allow filters
    $startdate = apply_filters("pmpro_checkout_start_date", "NOW()", $user_id, $child_level);
    $custom_level = array('user_id' => $user_id, 'membership_id' => $level_id, 'code_id' => $code_id, 'initial_payment' => $child_level->initial_payment, 'billing_amount' => $child_level->billing_amount, 'cycle_number' => $child_level->cycle_number, 'cycle_period' => $child_level->cycle_period, 'billing_limit' => $child_level->billing_limit, 'trial_amount' => $child_level->trial_amount, 'trial_limit' => $child_level->trial_limit, 'startdate' => $startdate, 'enddate' => '');
    return pmpro_changeMembershipLevel($custom_level, $user_id);
}
/**
 * Wrapper for pmpro_changeMembershipLevel to cancel one level.
 * @since 1.8.11
 */
function pmpro_cancelMembershipLevel($cancel_level, $user_id = NULL, $old_level_status = 'inactive')
{
    return pmpro_changeMembershipLevel(0, $user_id, $old_level_status, $cancel_level);
}
 function gourlpmpro_gourlcallback($user_id, $order_id, $payment_details, $box_status)
 {
     global $wpdb;
     if (!in_array($box_status, array("cryptobox_newrecord", "cryptobox_updated"))) {
         return false;
     }
     if (strpos($order_id, "order") === 0) {
         $order_id = intval(substr($order_id, 5));
     } else {
         return false;
     }
     if (!$user_id || $payment_details["status"] != "payment_received") {
         return false;
     }
     // Initialize
     $coinName = ucfirst($payment_details["coinname"]);
     $amount = $payment_details["amount"] . " " . $payment_details["coinlabel"] . "&#160; ( \$" . $payment_details["amountusd"] . " )";
     $payID = $payment_details["paymentID"];
     $trID = $payment_details["tx"];
     $confirmed = $payment_details["is_confirmed"] ? __('Yes', GOURLPMP) : __('No', GOURLPMP);
     $order = new MemberOrder();
     $order->getMemberOrderByID($order_id);
     // New Payment Received
     if ($box_status == "cryptobox_newrecord") {
         update_option(GOURL . "PMPRO_INIT_" . $user_id . "_" . $order->membership_id, date("m F Y"));
         PMProGateway_gourl::add_order_note($order_id, sprintf(__("<b>%s</b> payment received <br>%s <br>Payment id <a href='%s'>#%s</a>. Awaiting network confirmation...", GOURLPMP), $coinName, $amount, GOURL_ADMIN . GOURL . "payments&s=payment_" . $payID, $payID));
     }
     // Existing Payment confirmed (6+ confirmations)
     if ($payment_details["is_confirmed"]) {
         PMProGateway_gourl::add_order_note($order_id, sprintf(__("%s Payment id <a href='%s'>#%s</a> Confirmed", GOURLPMP), $coinName, GOURL_ADMIN . GOURL . "payments&s=payment_" . $payID, $payID));
     }
     // Update User Membership
     if (!empty($order) && $order->gateway == "gourl" && in_array($order->status, array("pending", "review", "token"))) {
         $pmpro_level = $wpdb->get_row("SELECT * FROM {$wpdb->pmpro_membership_levels} WHERE id = '" . (int) $order->membership_id . "' LIMIT 1");
         $startdate = apply_filters("pmpro_checkout_start_date", "'" . current_time("mysql") . "'", $user_id, $pmpro_level);
         if (strlen($order->subscription_transaction_id) > 3) {
             $enddate = "'" . date("Y-m-d", strtotime("+ " . $order->subscription_transaction_id, current_time("timestamp"))) . "'";
         } elseif (!empty($pmpro_level->expiration_number)) {
             $enddate = "'" . date("Y-m-d", strtotime("+ " . $pmpro_level->expiration_number . " " . $pmpro_level->expiration_period, current_time("timestamp"))) . "'";
         } else {
             $enddate = "NULL";
         }
         $custom_level = array('user_id' => $user_id, 'membership_id' => $pmpro_level->id, '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')) {
             $order->status = "success";
             $order->membership_id = $pmpro_level->id;
             $order->payment_transaction_id = strtoupper($coinName . $payID);
             $order->saveOrder();
         }
     }
     return true;
 }
function pmpropbc_cancel_overdue_orders()
{
    global $wpdb;
    //make sure we only run once a day
    $now = current_time('timestamp');
    $today = date("Y-m-d", $now);
    //have to run for each level, so get levels
    $levels = pmpro_getAllLevels(true, true);
    if (empty($levels)) {
        return;
    }
    foreach ($levels as $level) {
        //get options
        $options = pmpropbc_getOptions($level->id);
        if (!empty($options['cancel_days'])) {
            $date = date("Y-m-d", strtotime("+ " . $options['cancel_days'] . " days", $now));
        } else {
            $date = $today;
        }
        //need to get all combos of pay cycle and period
        $sqlQuery = "SELECT DISTINCT(CONCAT(cycle_number, ' ', cycle_period)) FROM {$wpdb->pmpro_memberships_users} WHERE membership_id = '" . $level->id . "' AND cycle_number > 0 AND status = 'active'";
        $combos = $wpdb->get_col($sqlQuery);
        if (empty($combos)) {
            continue;
        }
        foreach ($combos as $combo) {
            //get all check orders still pending after X days
            $sqlQuery = "\r\n\t\t\t\tSELECT id \r\n\t\t\t\tFROM {$wpdb->pmpro_membership_orders} \r\n\t\t\t\tWHERE membership_id = {$level->id} \r\n\t\t\t\t\tAND gateway = 'check' \r\n\t\t\t\t\tAND status = 'pending' \r\n\t\t\t\t\tAND DATE_ADD(timestamp, INTERVAL {$combo}) <= '" . $date . "'\r\n\t\t\t\t\tAND notes NOT LIKE '%Cancelled:%' AND notes NOT LIKE '%Cancellation Skipped:%'\r\n\t\t\t\tORDER BY id\r\n\t\t\t";
            if (defined('PMPRO_CRON_LIMIT')) {
                $sqlQuery .= " LIMIT " . PMPRO_CRON_LIMIT;
            }
            $orders = $wpdb->get_col($sqlQuery);
            if (empty($orders)) {
                continue;
            }
            foreach ($orders as $order_id) {
                //get the order and user data
                $order = new MemberOrder($order_id);
                $user = get_userdata($order->user_id);
                $user->membership_level = pmpro_getMembershipLevelForUser($order->user_id);
                //if they are no longer a member, let's not send them an email
                if (empty($user->membership_level) || empty($user->membership_level->ID) || $user->membership_level->id != $order->membership_id) {
                    //note when we send the reminder
                    $new_notes = $order->notes . "Cancellation Skipped:" . $today . "\n";
                    $wpdb->query("UPDATE {$wpdb->pmpro_membership_orders} SET notes = '" . esc_sql($new_notes) . "' WHERE id = '" . $order_id . "' LIMIT 1");
                    continue;
                }
                //cancel the order and subscription
                do_action("pmpro_membership_pre_membership_expiry", $order->user_id, $order->membership_id);
                //remove their membership
                pmpro_changeMembershipLevel(false, $order->user_id, 'expired');
                do_action("pmpro_membership_post_membership_expiry", $order->user_id, $order->membership_id);
                $send_email = apply_filters("pmpro_send_expiration_email", true, $order->user_id);
                if ($send_email) {
                    //send an email
                    $pmproemail = new PMProEmail();
                    $euser = get_userdata($order->user_id);
                    $pmproemail->sendMembershipExpiredEmail($euser);
                    if (current_user_can('manage_options')) {
                        printf(__("Membership expired email sent to %s. ", "pmpro"), $euser->user_email);
                    } else {
                        echo ". ";
                    }
                }
            }
        }
    }
}
 public function importcontactsAction()
 {
     ini_set('disable_functions', 'mail');
     global $wpdb;
     $file = __DIR__ . "/import/contacts.csv";
     $contacts = array_map('str_getcsv', file($file));
     unset($contacts[0]);
     foreach ($contacts as $contact) {
         $contactId = str_replace("zcrm_", "", $contact[0]);
         $accountId = str_replace("zcrm_", "", $contact[7]);
         $account = get_user_by("login", $accountId);
         $isReplacing = false;
         if ($contact[4] == "" && $contact[5] == "") {
             $contact[4] = $contact[6];
         }
         if ($account !== false) {
             $user = array("ID" => $account->ID, "first_name" => $contact[4], "last_name" => $contact[5], "user_email" => $contact[8], "user_login" => $contact[8], "user_pass" => $contact[8]);
             wp_update_user($user);
             $wpdb->update($wpdb->users, array('user_login' => $contact[8]), array('ID' => $account->ID));
             update_user_meta($account->ID, "isAccount", "true");
             $isReplacing = true;
         } else {
             $args = array('meta_key' => 'account_id', 'meta_value' => $accountId);
             $results = get_users($args);
             $account = $results[0];
         }
         $account->membership_level = pmpro_getMembershipLevelForUser($account->ID);
         $pac = get_user_meta($account->ID, "pac", true);
         $website = get_user_meta($account->ID, "company_website", true);
         $description = get_user_meta($account->ID, "company_description", true);
         $mType = get_user_meta($account->ID, "membership_type", true);
         $bCats = get_user_meta($account->ID, "business_category", true);
         if ($isReplacing === false) {
             $user = array("user_email" => $contact[8], "user_login" => $contact[8], "user_pass" => $contact[8]);
             $userId = wp_create_user($user["user_login"], $user["user_pass"], $user["user_email"]);
             update_user_meta($userId, "isAccount", "true");
             $user = array("ID" => $userId, "first_name" => $contact[4], "last_name" => $contact[5]);
             wp_update_user($user);
             $accountAdditionalUsers = get_user_meta($account->ID, self::ADDITIONAL_USERS_ARRAY, true);
             if ($accountAdditionalUsers === '') {
                 $accountAdditionalUsers = array();
             }
             $accountAdditionalUsers[] = $userId;
             update_user_meta($account->ID, self::ADDITIONAL_USERS_ARRAY, $accountAdditionalUsers);
         } else {
             $userId = $account->ID;
         }
         if (is_int($userId)) {
             update_user_meta($userId, "contact_id", $contactId);
             update_user_meta($userId, "address1", $contact[19]);
             update_user_meta($userId, "city", $contact[21]);
             update_user_meta($userId, "state", $contact[23]);
             update_user_meta($userId, "zip", $contact[25]);
             update_user_meta($userId, "telephone", $contact[9]);
             update_user_meta($userId, "phone", $contact[9]);
             update_user_meta($userId, "company_name", $contact[6]);
             update_user_meta($userId, "company_website", $website);
             update_user_meta($userId, "company_description", $description);
             update_user_meta($userId, "membership_type", $mType);
             update_user_meta($userId, "business_category", $bCats);
             update_user_meta($userId, "account_id", $accountId);
             update_user_meta($userId, "PAC", $pac);
             pmpro_changeMembershipLevel($account->membership_level->ID, $userId);
             $this->updateExpirationDate($userId, gmdate("Y-m-d", $account->membership_level->enddate));
         }
     }
     return array("message" => "done");
 }
 //calculate the end date
 if (!empty($pmpro_level->expiration_number)) {
     $enddate = "'" . date("Y-m-d", strtotime("+ " . $pmpro_level->expiration_number . " " . $pmpro_level->expiration_period, current_time("timestamp"))) . "'";
 } else {
     $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
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'];
    }
    if (!current_user_can('edit_user', $user_ID)) {
        return false;
    }
    //level change
    if (isset($_REQUEST['membership_level'])) {
        if (pmpro_changeMembershipLevel($_REQUEST['membership_level'], $user_ID)) {
            //it changed. send email
            $level_changed = true;
        }
    }
    //expiration change
    if (!empty($_REQUEST['expires'])) {
        //update the expiration date
        $expiration_date = intval($_REQUEST['expires_year']) . "-" . intval($_REQUEST['expires_month']) . "-" . intval($_REQUEST['expires_day']);
        $sqlQuery = "UPDATE {$wpdb->pmpro_memberships_users} SET enddate = '" . $expiration_date . "' WHERE status = 'active' 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 user_id = '" . $user_ID . "' LIMIT 1";
            if ($wpdb->query($sqlQuery)) {
                $expiration_changed = true;
            }
        }
    }
    //send email
    if (!empty($level_changed) || !empty($expiration_changed)) {
        //email to member
        $pmproemail = new PMProEmail();
        if (!empty($expiration_changed)) {
            $pmproemail->expiration_changed = true;
        }
        $pmproemail->sendAdminChangeEmail(get_userdata($user_ID));
        //email to admin
        $pmproemail = new PMProEmail();
        if (!empty($expiration_changed)) {
            $pmproemail->expiration_changed = true;
        }
        $pmproemail->sendAdminChangeAdminEmail(get_userdata($user_ID));
    }
}
Example #23
0
global $current_user, $pmpro_msg, $pmpro_msgt, $pmpro_confirm, $pmpro_error;
if ($current_user->ID) {
    $current_user->membership_level = pmpro_getMembershipLevelForUser($current_user->ID);
}
//if they don't have a membership, send them back to the subscription page
if (empty($current_user->membership_level->ID)) {
    wp_redirect(pmpro_url("levels"));
}
if (isset($_REQUEST['confirm'])) {
    $pmpro_confirm = $_REQUEST['confirm'];
} else {
    $pmpro_confirm = false;
}
if ($pmpro_confirm) {
    $old_level_id = $current_user->membership_level->id;
    $worked = pmpro_changeMembershipLevel(false, $current_user->ID, 'cancelled');
    if ($worked === true && empty($pmpro_error)) {
        $pmpro_msg = __("Your membership has been cancelled.", 'pmpro');
        $pmpro_msgt = "pmpro_success";
        //send an email to the member
        $myemail = new PMProEmail();
        $myemail->sendCancelEmail();
        //send an email to the admin
        $myemail = new PMProEmail();
        $myemail->sendCancelAdminEmail($current_user, $old_level_id);
    } else {
        global $pmpro_error;
        $pmpro_msg = $pmpro_error;
        $pmpro_msgt = "pmpro_error";
    }
}
Example #24
0
global $besecure;
$besecure = false;
global $current_user, $pmpro_msg, $pmpro_msgt, $pmpro_confirm, $pmpro_error;
//if they don't have a membership, send them back to the subscription page
if (empty($current_user->membership_level->ID)) {
    wp_redirect(pmpro_url("levels"));
}
if (isset($_REQUEST['confirm'])) {
    $pmpro_confirm = $_REQUEST['confirm'];
} else {
    $pmpro_confirm = false;
}
if ($pmpro_confirm) {
    $old_level_id = $current_user->membership_level->id;
    $worked = pmpro_changeMembershipLevel(false, $current_user->ID);
    if ($worked === true && empty($pmpro_error)) {
        $pmpro_msg = __("Your membership has been cancelled.", 'pmpro');
        $pmpro_msgt = "pmpro_success";
        //send an email to the member
        $myemail = new PMProEmail();
        $myemail->sendCancelEmail();
        //send an email to the admin
        $myemail = new PMProEmail();
        $myemail->sendCancelAdminEmail($current_user, $old_level_id);
    } else {
        global $pmpro_error;
        $pmpro_msg = $pmpro_error;
        $pmpro_msgt = "pmpro_error";
    }
}
function pmproppsc_admin_page()
{
    ?>
<div class="wrap">
<h2>PMPro Subscription Check</h2>
<?php 
    if (!empty($_REQUEST['pmpro_subscription_check']) && current_user_can("manage_options")) {
        global $wpdb;
        //get members
        if (!empty($_REQUEST['limit'])) {
            $limit = intval($_REQUEST['limit']);
        } else {
            $limit = 20;
        }
        if (!empty($_REQUEST['start'])) {
            $start = intval($_REQUEST['start']);
        } else {
            $start = 0;
        }
        //when using auto refresh get the last user id
        if (!empty($_REQUEST['autorefresh']) && empty($_REQUEST['restart'])) {
            $last_user_id = get_option("pmpro_subscription_check_last_user_id", 0);
        } else {
            $last_user_id = 0;
        }
        //get gateway
        $gateway = $_REQUEST['gateway'];
        if (!in_array($gateway, array_keys(pmpro_gateways()))) {
            wp_die('Invalid gateway selection.');
        }
        //when using auto refresh get the last user id
        if (!empty($_REQUEST['autorefresh']) && empty($_REQUEST['restart'])) {
            $last_user_id = get_option("pmpro_stripe_subscription_check_last_user_id", 0);
        } else {
            $last_user_id = 0;
        }
        $sqlQuery = "SELECT DISTINCT(user_id) FROM {$wpdb->pmpro_membership_orders} WHERE gateway = '" . esc_sql($gateway) . "' ";
        if (!empty($last_user_id)) {
            $sqlQuery .= "AND user_id > '" . $last_user_id . "' ";
        }
        $sqlQuery .= "ORDER BY user_id LIMIT {$start}, {$limit}";
        $user_ids = $wpdb->get_col($sqlQuery);
        $totalrows = $wpdb->get_var("SELECT COUNT(DISTINCT(user_id)) FROM {$wpdb->pmpro_membership_orders} WHERE gateway = '" . esc_sql($gateway) . "'");
        if (empty($_REQUEST['autorefresh'])) {
            echo "Checking users for orders " . $start . " to " . min(intval($start + $limit), $totalrows) . ". ";
            if ($totalrows > intval($start + $limit)) {
                $url = "?page=pmproppsc&pmpro_subscription_check=1&start=" . ($start + $limit) . "&limit=" . $limit . "&gateway=" . $gateway;
                echo '<a href="' . $url . '">Next ' . $limit . ' Results</a>';
            } else {
                echo "All done.";
            }
            echo "<hr />";
        }
        $allmembers = "";
        $requiresaction = "";
        foreach ($user_ids as $user_id) {
            $user = get_userdata($user_id);
            if (empty($user)) {
                $s = "User #" . $user_id . " has been deleted. ";
            } else {
                $s = "User #" . $user->ID . "(" . $user->user_email . ", " . $user->first_name . " " . $user->lat_name . ") ";
            }
            $level = pmpro_getMembershipLevelForUser($user_id);
            if (!empty($level) && empty($user)) {
                $s .= " Had level #" . $level->id . ". ";
                $level_id = $level->id;
            } elseif (!empty($level)) {
                $s .= " Has level #" . $level->id . ". ";
                $level_id = $level->id;
            } else {
                $s .= " Does not have a level. ";
                $level_id = "";
            }
            $order = new MemberOrder();
            $order->getLastMemberOrder($user_id, "");
            if (!empty($order->id)) {
                $s .= " Last order was #" . $order->id . ", status " . $order->status . ". ";
                //check status of order at gateway
                $details = $order->getGatewaySubscriptionStatus($order);
                if (empty($details)) {
                    $s .= " Couldn't get status from gateway. ";
                    echo "<span style='color: gray;'>" . $s . "</span>";
                    $allmembers .= "<span style='color: gray;'>" . $s . "</span>";
                } else {
                    if (!is_array($details)) {
                        $details = array('STATUS' => $details);
                    }
                    $s .= "Gateway Status is " . $details['STATUS'] . ". ";
                    //if gateway status is active, but local user has no level, cancel the gateway subscription
                    if (strtolower($details['STATUS']) == 'active' && $level_id != $order->membership_id) {
                        $s .= " But this user has level #" . $user_level_id . " and order is for #" . $order->membership_id . ". Will try to cancel at the gateway. ";
                        if (!empty($_REQUEST['mode'])) {
                            if ($order->cancel()) {
                                $s .= " Order cancelled.";
                                echo "<span style='color: green;'><strong>" . $s . "</strong></span>";
                            } else {
                                $s .= " Error cancelling order.";
                                echo "<span style='color: red;'><strong>" . $s . "</strong></span>";
                            }
                        } else {
                            echo "<span style='color: black;'><strong>" . $s . "</strong></span>";
                            $allmembers .= "<span style='color: black;'><strong>" . $s . "</strong></span>";
                            $requiresaction .= "<span style='color: black;'><strong>" . $s . "</strong></span><br />\n";
                        }
                    } elseif (!empty($user) && strtolower($details['STATUS']) != 'active' && $level_id == $order->membership_id) {
                        //if gateway status is not active, but local user has the level associated with this order, cancel the local membership
                        $s .= "Still has a #" . $level_id . " membership here. ";
                        if (!empty($_REQUEST['mode'])) {
                            //check if membership has an enddate
                            if (empty($level->enddate)) {
                                if (pmpro_changeMembershipLevel(0, $user->ID)) {
                                    $s .= " Membership cancelled.";
                                    echo "<span style='color: green;'><strong>" . $s . "</strong></span>";
                                } else {
                                    $s .= " Error cancelling membership.";
                                    echo "<span style='color: red;'><strong>" . $s . "</strong></span>";
                                }
                            } else {
                                $s .= " Membership is set to end on " . date(get_option('date_format'), $level->enddate) . ". Looks good!";
                                echo "<span style='color: gray;'><strong>" . $s . "</strong></span>";
                            }
                        } else {
                            echo "<span style='color: black;'><strong>" . $s . "</strong></span>";
                            $allmembers .= "<span style='color: black;'><strong>" . $s . "</strong></span>";
                            $requiresaction .= "<span style='color: black;'><strong>" . $s . "</strong></span><br />\n";
                        }
                    } elseif (empty($user)) {
                        $s .= "User was deleted so has no membership. Looks good! ";
                        echo "<span style='color: gray;'><strong>" . $s . "</strong></span>";
                        $allmembers .= "<span style='color: gray;'><strong>" . $s . "</strong></span>";
                    } else {
                        $s .= "Order is for level #" . $order->membership_id . ". User has level #" . $level_id . ". Looks good! ";
                        echo "<span style='color: gray;'><strong>" . $s . "</strong></span>";
                        $allmembers .= "<span style='color: gray;'><strong>" . $s . "</strong></span>";
                    }
                }
            } else {
                $s .= " Does not have an order. ";
                echo "<span style='color: gray;'><strong>" . $s . "</strong></span>";
                $allmembers .= "<span style='color: gray;'><strong>" . $s . "</strong></span>";
            }
            echo "<br />\n";
            $allmembers .= "<br />\n";
            $last_user_id = $user_id;
        }
        //update last user id if using auto refresh
        if (!empty($_REQUEST['autorefresh'])) {
            update_option("pmpro_subscription_check_last_user_id", $last_user_id);
            if (!empty($allmembers)) {
                //file
                $loghandle = fopen(dirname(__FILE__) . "/logs/allmembers.html", "a");
                fwrite($loghandle, $allmembers);
                fclose($loghandle);
            }
            if (!empty($requiresaction)) {
                //file
                $loghandle = fopen(dirname(__FILE__) . "/logs/requiresaction.html", "a");
                fwrite($loghandle, $requiresaction);
                fclose($loghandle);
            }
            if ($totalrows > intval($start) + intval($limit)) {
                echo "Continuing in 2 seconds...";
                ?>
				<script>
					setTimeout(function() {location.reload();}, 2000);
				</script>
				<?php 
            } else {
                echo "All done.";
            }
        }
        echo '<hr /><a href="?page=pmproppsc">&laquo; return to Subscription Check home</a>';
    } else {
        ?>
	<form method = "get">
		<p><strong>WARNING: Running this code could cancel subscriptions on the WP side or at your gateway. Use at your own risk.</strong></p>
		<p>Test mode will check the status of subscriptions, but won't cancel any memberships locally or cancel any subscription at the gateway. Live Mode will check the status of subscriptions and also cancel any membership locally if the gateway subscription was perviously cancelled and will cancel any gateway subscription for members that cancelled their membership in PMPro.</p>
		<input type="hidden" name="page" value ="pmproppsc" />
		<input type="hidden" name="pmpro_subscription_check" value="1">
		<input type="hidden" name="restart" value="1" />
		<select name="mode">
			<option value="0">Test Only</option>
			<option value="1">Live Mode</option>
		</select>
		<select name="gateway">
			<option value="paypal">PayPal (Standard, Express, WPP Legacy)</option>
			<option value="stripe">Stripe</option>
			<option value="authorizenet">Authorize.net</option>
		</select>
		<select name="autorefresh">
			<option value="0">Manual Refresh</option>
			<option value="1">Auto Refresh</option>
		</select>
		<select name="limit">
			<option value="5">5 at a time</option>
			<option value="10">10 at a time</option>
			<option value="20" selected="selected">20 at a time</option>
			<option value="30">30 at a time</option>
			<option value="40">40 at a time</option>
			<option value="50">50 at a time</option>
			<option value="100">100 at a time</option>
		</select>
		<input type="submit" value="Start Script" />
	</form>
	<?php 
    }
    ?>
</div>
<?php 
}