Esempio n. 1
1
 /**
  * @param array $process_data
  * @param $blog_id
  * @param $domain
  *
  * @return bool
  */
 public static function process_checkout_form($process_data = array(), $blog_id, $domain)
 {
     global $psts, $current_user, $current_site;
     $site_name = $current_site->site_name;
     $img_base = $psts->plugin_url . 'images/';
     $session_keys = array('new_blog_details', 'upgraded_blog_details', 'COUPON_CODE', 'activation_key');
     foreach ($session_keys as $key) {
         $process_data[$key] = isset($process_data[$key]) ? $process_data[$key] : ProSites_Helper_Session::session($key);
     }
     if (!empty($domain)) {
         $site_name = !empty($_POST['blogname']) ? $_POST['blogname'] : !empty($_POST['signup_email']) ? $_POST['signup_email'] : '';
     }
     //Process Checkout
     if (isset($_POST['cc_stripe_checkout']) && 1 == (int) $_POST['cc_stripe_checkout']) {
         //check for level, if empty don't go ahead and return
         if (empty($_POST['level']) || empty($_POST['period'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return false;
         } else {
             if (!isset($_POST['stripeToken']) && empty($_POST['wp_password'])) {
                 $psts->errors->add('general', __('There was an error processing your Credit Card with Stripe. Please try again.', 'psts'));
             }
         }
         // TAX Object
         $tax_object = ProSites_Helper_Session::session('tax_object');
         if (empty($tax_object) || empty($tax_object->evidence)) {
             $tax_object = ProSites_Helper_Tax::get_tax_object();
             ProSites_Helper_Session::session('tax_object', $tax_object);
         }
         $evidence_string = ProSites_Helper_Tax::get_evidence_string($tax_object);
         $error = '';
         $success = '';
         $plan = self::get_plan_id($_POST['level'], $_POST['period']);
         $customer_id = '';
         $current_plan_level = 0;
         $activation_key = isset($_POST['activation']) ? $_POST['activation'] : '';
         $email = !empty($_POST['user_email']) ? $_POST['user_email'] : (!empty($_POST['signup_email']) ? $_POST['signup_email'] : (!empty($_POST['blog_email']) ? $_POST['blog_email'] : ''));
         $blog_id = !empty($blog_id) ? $blog_id : isset($_REQUEST['bid']) ? (int) $_REQUEST['bid'] : 0;
         //If there is a blog id, fetch existing customer details (Upgrade)
         if (!empty($blog_id)) {
             $customer_id = self::get_customer_data($blog_id)->customer_id;
             $email = isset($current_user->user_email) ? $current_user->user_email : get_blog_option($blog_id, 'admin_email');
             //Get current plan for the user
             if ($current_plan = self::get_current_plan($blog_id)) {
                 list($current_plan_level, $current_plan_period) = explode('_', $current_plan);
             }
         } else {
             //New Signup
             if (empty($email) && isset($process_data['new_blog_details']) && isset($process_data['new_blog_details']['user_email'])) {
                 $email = $process_data['new_blog_details']['user_email'];
             }
             $customer_id = self::get_customer_data(false, false, $email)->customer_id;
         }
         if (!self::plan_exists($plan)) {
             $psts->errors->add('general', sprintf(__('Stripe plan %1$s does not exist.', 'psts'), $plan));
             return;
         }
         //Create s Stripe profile for the customer with all the available details,
         //If customer already exists, retrieve customer from stripe
         try {
             if (!$customer_id) {
                 try {
                     $customer_args = array('email' => $email, 'description' => sprintf(__('%s user', 'psts'), $site_name), 'card' => $_POST['stripeToken'], 'metadata' => array('domain' => $domain));
                     $user = get_user_by('email', $email);
                     if ($user) {
                         $blog_string = '';
                         $customer_args['metadata']['user'] = $user->user_login;
                         $customer_args['description'] = sprintf(__('%s user - %s ', 'psts'), $site_name, $user->first_name . ' ' . $user->last_name);
                         $user_blogs = get_blogs_of_user($user->ID);
                         foreach ($user_blogs as $user_blog) {
                             $blog_string .= $user_blog->blogname . ', ';
                         }
                         $customer_args['metadata']['blogs'] = $blog_string;
                     }
                     if (!$domain) {
                         unset($customer_args['metadata']['domain']);
                     }
                     $c = Stripe_Customer::create($customer_args);
                 } catch (Exception $e) {
                     $psts->errors->add('general', __('The Stripe customer could not be created. Please try again.', 'psts'));
                     return;
                 }
                 //Update the stripe customer id, this is temporary, will be overridden by subscription or charge id
                 self::set_customer_data($blog_id, $c->id, 'ak_' . $activation_key);
                 $customer_id = $c->id;
                 $new = true;
             } else {
                 // Get a customer if they exist
                 try {
                     $c = Stripe_Customer::retrieve($customer_id);
                 } catch (Exception $e) {
                     $psts->errors->add('general', __('The Stripe customer could not be retrieved. Please try again.', 'psts'));
                     return;
                 }
                 $c->description = sprintf(__('%s user', 'psts'), $site_name);
                 $c->email = $email;
                 $user = get_user_by('email', $email);
                 if ($user) {
                     $blog_string = '';
                     $c->metadata->user = $user->user_login;
                     $c->description = sprintf(__('%s user - %s ', 'psts'), $site_name, $user->first_name . ' ' . $user->last_name);
                     $user_blogs = get_blogs_of_user($user->ID);
                     foreach ($user_blogs as $user_blog) {
                         $blog_string .= $user_blog->blogname . ', ';
                     }
                     $c->metadata->blogs = $blog_string;
                 }
                 $c->save();
                 $new = false;
                 //validate wp password (if applicable)
                 if (!empty($_POST['wp_password']) && !wp_check_password($_POST['wp_password'], $current_user->data->user_pass, $current_user->ID)) {
                     $psts->errors->add('general', __('The password you entered is incorrect.', 'psts'));
                     return;
                 }
             }
             //prepare vars
             $currency = self::currency();
             $amount_off = false;
             $paymentAmount = $initAmount = $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']);
             $trial_days = $psts->get_setting('trial_days', 0);
             $cp_code = false;
             $setup_fee = (double) $psts->get_setting('setup_fee', 0);
             $has_coupon = isset($process_data['COUPON_CODE']) && ProSites_Helper_Coupons::check_coupon($process_data['COUPON_CODE'], $blog_id, $_POST['level'], $_POST['period'], $domain) ? true : false;
             $has_setup_fee = $psts->has_setup_fee($blog_id, $_POST['level']);
             $recurring = $psts->get_setting('recurring_subscriptions', 1);
             if ($has_setup_fee) {
                 $initAmount = $setup_fee + $paymentAmount;
             }
             if ($has_coupon || $has_setup_fee) {
                 $lifetime = 'once';
                 if ($has_coupon) {
                     //apply coupon
                     $adjusted_values = ProSites_Helper_Coupons::get_adjusted_level_amounts($process_data['COUPON_CODE']);
                     $coupon_obj = ProSites_Helper_Coupons::get_coupon($process_data['COUPON_CODE']);
                     $lifetime = isset($coupon_obj['lifetime']) && 'indefinite' == $coupon_obj['lifetime'] ? 'forever' : 'once';
                     //	$coupon_value = $psts->coupon_value( $process_data['COUPON_CODE'], $paymentAmount );
                     $coupon_value = $adjusted_values[$_POST['level']]['price_' . $_POST['period']];
                     // $amount_off   = $paymentAmount - $coupon_value['new_total'];
                     $amount_off = $paymentAmount - $coupon_value;
                     $initAmount -= $amount_off;
                     $initAmount = 0 > $initAmount ? 0 : $initAmount;
                     // avoid negative
                     $cpn = false;
                     //Create a stripe coupon if it doesn't exists already
                     try {
                         $cpn = Stripe_Coupon::create(array('amount_off' => $amount_off * 100, 'duration' => $lifetime, 'currency' => $currency, 'max_redemptions' => 1));
                     } catch (Exception $e) {
                         $psts->errors->add('general', __('Temporary Stripe coupon could not be generated correctly. Please try again.', 'psts'));
                         return;
                     }
                     $cp_code = $cpn->id;
                 }
                 //Check if it's a recurring subscription
                 if ($recurring) {
                     $recurringAmmount = 'forever' == $lifetime && $has_coupon ? $coupon_value : $paymentAmount;
                     if ($_POST['period'] == 1) {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($currency, $initAmount), $psts->format_currency($currency, $recurringAmmount));
                     } else {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first %2$s month period, then %3$s every %4$s months', 'psts'), $psts->format_currency($currency, $initAmount), $_POST['period'], $psts->format_currency($currency, $recurringAmmount), $_POST['period']);
                     }
                 } else {
                     if (!empty($blog_id)) {
                         $initAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $initAmount);
                     }
                     if ($_POST['period'] == 1) {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $initAmount));
                     } else {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $initAmount), $_POST['period']);
                     }
                 }
             } elseif ($recurring) {
                 if ($_POST['period'] == 1) {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency);
                 } else {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every %3$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency, $_POST['period']);
                 }
             } else {
                 //New Signups
                 if (!empty($blog_id)) {
                     $paymentAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $paymentAmount);
                 }
                 if ($_POST['period'] == 1) {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $paymentAmount));
                 } else {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $_POST['period']);
                 }
             }
             // Override the Stripe description
             $desc = apply_filters('psts_stripe_checkout_desc', $desc, $_POST['period'], $_POST['level'], $paymentAmount, $initAmount, $blog_id, $domain);
             // Time to process invoices with Stripe
             if ($recurring) {
                 // Recurring subscription
                 // Assign plan to customer
                 $args = array("plan" => $plan, "prorate" => true);
                 // Apply tax?
                 if ($tax_object->apply_tax) {
                     $args['tax_percent'] = $tax_object->tax_rate * 100;
                 }
                 // If there is a coupon, add its reference
                 if ($cp_code) {
                     $args["coupon"] = $cp_code;
                 }
                 // If this is a trial before the subscription starts
                 if ($psts->is_trial_allowed($blog_id)) {
                     if (isset($process_data['new_blog_details']) || !$psts->is_existing($blog_id)) {
                         //customer is new - add trial days
                         $args['trial_end'] = strtotime('+ ' . $trial_days . ' days');
                     } elseif (is_pro_trial($blog_id) && $psts->get_expire($blog_id) > time()) {
                         //customer's trial is still valid - carry over existing expiration date
                         $args['trial_end'] = $psts->get_expire($blog_id);
                     }
                 }
                 // Meta data for `pay before blog` creation
                 $args['metadata'] = array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level']);
                 if ($tax_object->apply_tax) {
                     $args['metadata']['tax_evidence'] = $evidence_string;
                 }
                 if (!$domain) {
                     unset($args['metadata']['domain']);
                 }
                 // new blog
                 if (isset($_POST['activation'])) {
                     $args['metadata']['activation'] = $_POST['activation'];
                 }
                 // Create Stripe Invoice for the setup fee
                 if ($has_setup_fee) {
                     try {
                         $customer_args = array('customer' => $customer_id, 'amount' => $setup_fee * 100, 'currency' => $currency, 'description' => __('One-time setup fee', 'psts'), 'metadata' => array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level'], 'setup_fee' => 'yes'));
                         if ($tax_object->apply_tax) {
                             $customer_args['metadata']['tax_evidence'] = $evidence_string;
                         }
                         if (!$domain) {
                             unset($customer_args['metadata']['domain']);
                         }
                         // new blog
                         if (isset($_POST['activation'])) {
                             $customer_args['metadata']['activation'] = $_POST['activation'];
                         }
                         Stripe_InvoiceItem::create($customer_args);
                     } catch (Exception $e) {
                         wp_mail(get_blog_option($blog_id, 'admin_email'), __('Error charging setup fee. Attention required!', 'psts'), sprintf(__('An error occurred while charging a setup fee of %1$s to Stripe customer %2$s. You will need to manually process this amount.', 'psts'), $psts->format_currency($currency, $setup_fee), $customer_id));
                     }
                 }
                 // Create/update subscription
                 try {
                     $result = false;
                     $sub = false;
                     // Brand new blog...
                     if (empty($blog_id)) {
                         $result = $c->subscriptions->create($args);
                     } else {
                         $customer_data = self::get_customer_data($blog_id);
                         try {
                             $sub = $c->subscriptions->retrieve($customer_data->subscription_id);
                             $sub_id = $sub->id;
                             $prev_plan = $sub->plan->id;
                             $sub->plan = isset($args['plan']) ? $args['plan'] : $sub->plan;
                             $changed_plan = $sub->plan;
                             $sub->prorate = isset($args['prorate']) ? $args['prorate'] : $sub->prorate;
                             if (isset($args['coupon'])) {
                                 $sub->coupon = $args['coupon'];
                             }
                             if (isset($args['trial_end'])) {
                                 $sub->trial_end = $args['trial_end'];
                             }
                             $sub->metadata->period = $args['metadata']['period'];
                             $sub->metadata->level = $args['metadata']['level'];
                             if (isset($args['metadata']['activation'])) {
                                 $sub->metadata->activation = $args['metadata']['activation'];
                             } else {
                                 $activation_key = ProSites_Helper_ProSite::get_activation_key($blog_id);
                                 if (!empty($activation_key)) {
                                     $sub->metadata->activation = $activation_key;
                                 }
                             }
                             $sub->metadata->blog_id = $blog_id;
                             if (isset($args['metadata']['domain'])) {
                                 $sub->metadata->domain = $args['metadata']['domain'];
                             }
                             // Apply tax?
                             if ($tax_object->apply_tax) {
                                 $sub->tax_percent = $tax_object->tax_rate * 100;
                                 $sub->metadata->tax_evidence = $evidence_string;
                             }
                             $sub->save();
                             // As per Stripe API, to charge immediately, apply an invoice now
                             if ($prev_plan != $changed_plan) {
                                 $customer_args = array('customer' => $customer_id, 'subscription' => $sub_id, 'metadata' => array('plan_change' => 'yes'));
                                 $invoice = Stripe_Invoice::create($customer_args);
                                 $invoice = $invoice->pay();
                                 $plan_parts = explode('_', $changed_plan);
                                 $new_period = array_pop($plan_parts);
                                 $new_level = array_pop($plan_parts);
                                 $plan_parts = explode('_', $prev_plan);
                                 $prev_period = array_pop($plan_parts);
                                 $prev_level = array_pop($plan_parts);
                                 $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $new_level, 'period' => $new_period, 'prev_level' => $prev_level, 'prev_period' => $prev_period);
                                 ProSites_Helper_Session::session('plan_updated', $updated);
                             }
                         } catch (Exception $e) {
                             // Fall through...
                         }
                         // Additional blog
                         if (empty($sub)) {
                             $args['metadata']['blog_id'] = $blog_id;
                             if (!isset($args['metadata']['activation'])) {
                                 $activation_key = ProSites_Helper_ProSite::get_activation_key($blog_id);
                                 if (!empty($activation_key)) {
                                     $args['metadata']['activation'] = $activation_key;
                                 }
                             }
                             $result = $c->subscriptions->create($args);
                         }
                         // This one is now deprecated
                         // $result = $c->updateSubscription( $args );
                     }
                     // Capture success as soon as we can!
                     if (!empty($result)) {
                         $sub_id = $result->id;
                         $plan = $result->plan;
                         $plan_parts = explode('_', $plan->id);
                         $period = array_pop($plan_parts);
                         $level = array_pop($plan_parts);
                         $trial = isset($plan->status) && 'trialing' == $plan->status ? true : false;
                         $expire = $trial ? $plan->trial_end : $result->current_period_end;
                         $result = ProSites_Helper_Registration::activate_blog($activation_key, $trial, $period, $level, $expire);
                         $blog_id = $result['blog_id'];
                         if (isset($process_data['new_blog_details'])) {
                             ProSites_Helper_Session::session(array('new_blog_details', 'blog_id'), $blog_id);
                             ProSites_Helper_Session::session(array('new_blog_details', 'payment_success'), true);
                         } else {
                             ProSites_Helper_Session::session('upgrade_blog_details', array());
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'blog_id'), $blog_id);
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'level'), $level);
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'period'), $period);
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'payment_success'), true);
                         }
                         self::set_customer_data($blog_id, $customer_id, $sub_id);
                     }
                     if ($current_plan = self::get_current_plan($blog_id)) {
                         list($current_plan_level, $current_plan_period) = explode('_', $current_plan);
                     }
                     //Extend the Blog Subscription
                     $old_expire = $psts->get_expire($blog_id);
                     $new_expire = $old_expire && $old_expire > time() ? $old_expire : false;
                     $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $initAmount, $new_expire, false);
                     //$psts->email_notification( $blog_id, 'receipt' );
                     if (isset($current_plan_level)) {
                         if ($current_plan_level > $_POST['level']) {
                             $psts->record_stat($blog_id, 'upgrade');
                         } else {
                             $psts->record_stat($blog_id, 'modify');
                         }
                     } else {
                         $psts->record_stat($blog_id, 'signup');
                     }
                     // Update the sub with the new blog id (old subscriptions will update later).
                     if (!empty($blog_id)) {
                         $sub = $c->subscriptions->retrieve($sub_id);
                         $sub->metadata->blog_id = $blog_id;
                         $sub->save();
                     }
                 } catch (Exception $e) {
                     $body = $e->getJsonBody();
                     $error = $body['error'];
                     $psts->errors->add('general', $error['message']);
                     return;
                 }
             } else {
                 // Not a subscription, this is a one of payment, charged for 1 term
                 try {
                     if (!empty($blog_id)) {
                         $initAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $initAmount);
                         //If activation key is empty
                         $activation_key = !empty($activation_key) ? $activation_key : ProSites_Helper_ProSite::get_activation_key($blog_id);
                     }
                     if ($tax_object->apply_tax) {
                         $amount = $initAmount + $initAmount * $tax_object->tax_rate;
                         $desc += sprintf(__('(includes tax of %s%% [%s])', 'psts'), $tax_object->tax_rate * 100, $tax_object->country);
                     } else {
                         $amount = $initAmount;
                     }
                     $customer_args = array('customer' => $customer_id, 'amount' => $amount * 100, 'currency' => $currency, 'description' => $desc, 'metadata' => array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level']));
                     if ($tax_object->apply_tax) {
                         $customer_args['metadata']['tax_evidence'] = $evidence_string;
                     }
                     if (!$domain) {
                         unset($customer_args['metadata']['domain']);
                     }
                     // new blog
                     if (isset($_POST['activation'])) {
                         $customer_args['metadata']['activation'] = $_POST['activation'];
                     }
                     /**
                      * 1 off charge of not trialing, but if trialing, just send a zero-dollar invoice
                      */
                     if (empty($trial_days) || 0 == $customer_args['amount']) {
                         $result = Stripe_Charge::create($customer_args);
                     } else {
                         $result = Stripe_InvoiceItem::create($customer_args);
                     }
                     // Capture success as soon as we can!
                     if ($result) {
                         $period = (int) $_POST['period'];
                         $level = (int) $_POST['level'];
                         $signup_details = ProSites_Helper_Registration::activate_blog($activation_key, false, $period, $level);
                         $blog_id = $signup_details['blog_id'];
                         if (isset($process_data['new_blog_details'])) {
                             ProSites_Helper_Session::session(array('new_blog_details', 'blog_id'), $blog_id);
                             ProSites_Helper_Session::session(array('new_blog_details', 'payment_success'), true);
                         }
                         self::set_customer_data($blog_id, $customer_id, $result->id);
                     }
                     if ($current_plan = self::get_current_plan($blog_id)) {
                         list($current_plan_level, $current_plan_period) = explode('_', $current_plan);
                     }
                     $old_expire = $psts->get_expire($blog_id);
                     $new_expire = $old_expire && $old_expire > time() ? $old_expire : false;
                     $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $initAmount, $new_expire, false);
                     //$psts->email_notification( $blog_id, 'receipt' );
                     if (isset($current_plan_level)) {
                         if ($current_plan_level > $_POST['level']) {
                             $psts->record_stat($blog_id, 'upgrade');
                         } else {
                             $psts->record_stat($blog_id, 'modify');
                         }
                     } else {
                         $psts->record_stat($blog_id, 'signup');
                     }
                 } catch (Stripe_CardError $e) {
                     $body = $e->getJsonBody();
                     $err = $body['error'];
                     $psts->errors->add('general', $e['message']);
                 } catch (Exception $e) {
                     $psts->errors->add('general', __('An unknown error occurred while processing your payment. Please try again.', 'psts'));
                 }
             }
             //delete the temporary coupon code
             if ($cp_code) {
                 try {
                     $cpn = Stripe_Coupon::retrieve($cp_code);
                     $cpn->delete();
                 } catch (Exception $e) {
                     wp_mail(get_blog_option($blog_id, 'admin_email'), __('Error deleting temporary Stripe coupon code. Attention required!.', 'psts'), sprintf(__('An error occurred when attempting to delete temporary Stripe coupon code %1$s. You will need to manually delete this coupon via your Stripe account.', 'psts'), $cp_code));
                 }
                 $psts->use_coupon($process_data['COUPON_CODE'], $blog_id, $domain);
             }
             if ($new || $psts->is_blog_canceled($blog_id)) {
                 // Added for affiliate system link
                 if ($recurring) {
                     $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Customer ID: %2$s', 'psts'), $desc, $customer_id), $domain);
                 } else {
                     $psts->log_action($blog_id, sprintf(__('User completed new payment via CC: Site created/extended (%1$s) - Customer ID: %2$s', 'psts'), $desc, $customer_id), $domain);
                 }
                 do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']);
             } else {
                 $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: Plan changed to (%1$s) - %2$s', 'psts'), $desc, $customer_id), $domain);
             }
             //display GA ecommerce in footer
             $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $site_name, $domain);
             if (!empty($blog_id)) {
                 update_blog_option($blog_id, 'psts_stripe_canceled', 0);
                 /* 	some times there is a lag receiving webhooks from Stripe. we want to be able to check for that
                 				and display an appropriate message to the customer (e.g. there are changes pending to your account) */
                 update_blog_option($blog_id, 'psts_stripe_waiting', 1);
             } else {
                 if (isset($process_data['activation_key'])) {
                     //Update signup meta
                     $key = $process_data['activation_key'];
                     $signup_meta = '';
                     $signup_meta = $psts->get_signup_meta($key);
                     $signup_meta['psts_stripe_canceled'] = 0;
                     $signup_meta['psts_stripe_waiting'] = 1;
                     $psts->update_signup_meta($signup_meta, $key);
                 }
             }
             update_blog_option($blog_id, 'psts_stripe_waiting', 1);
             if (empty(self::$complete_message)) {
                 // Message is redundant now, but still used as a flag.
                 self::$complete_message = __('Your payment was successfully recorded! You should be receiving an email receipt shortly.', 'psts');
             }
         } catch (Exception $e) {
             $psts->errors->add('general', $e->getMessage());
         }
     }
 }
 /**
  * Handles the form processing for Paypal button and express payments
  */
 public static function process_checkout_form()
 {
     global $current_site, $current_user, $psts, $wpdb;
     $domain = $path = '';
     $discountAmt = $has_coupon = false;
     $new_blog = true;
     $tax_amt_payment = $tax_amt_init = 0;
     //Blog id, Level Period
     $blog_id = !empty($_REQUEST['bid']) ? $_REQUEST['bid'] : 0;
     $level = !empty($_POST['level']) ? $_POST['level'] : '';
     $period = !empty($_POST['period']) ? $_POST['period'] : '';
     // TAX Object
     $tax_object = ProSites_Helper_Session::session('tax_object');
     if (empty($tax_object) || empty($tax_object->evidence)) {
         $tax_object = ProSites_Helper_Tax::get_tax_object();
         ProSites_Helper_Session::session('tax_object', $tax_object);
     }
     $evidence_string = ProSites_Helper_Tax::get_evidence_string($tax_object);
     // Try going stateless, or check the session
     $process_data = array();
     $session_keys = array('new_blog_details', 'upgraded_blog_details', 'COUPON_CODE', 'activation_key');
     foreach ($session_keys as $key) {
         $process_data[$key] = !empty($process_data[$key]) ? $process_data[$key] : ProSites_Helper_Session::session($key);
     }
     // Get blog_id from the session
     if (isset($process_data['new_blog_details']) && isset($process_data['new_blog_details']['blog_id'])) {
         $blog_id = $process_data['new_blog_details']['blog_id'];
     }
     $blog_id = !empty($blog_id) ? $blog_id : (!empty($_GET['bid']) ? (int) $_GET['bid'] : 0);
     $activation_key = '';
     //Get domain details, if activation is set, runs when user submits the form for blog signup
     if (!empty($_POST['activation']) || !empty($process_data['activation_key'])) {
         $activation_key = !empty($_POST['activation']) ? $_POST['activation'] : $process_data['activation_key'];
         //For New Signup
         $signup_details = $wpdb->get_row($wpdb->prepare("SELECT `domain`, `path` FROM {$wpdb->signups} WHERE activation_key = %s", $activation_key));
         if ($signup_details) {
             $domain = $signup_details->domain;
             $path = $signup_details->path;
             //Store values in session or custom variable, to be used after user returns from Paypal Payment
             $process_data['new_blog_details']['domain'] = $domain;
             $process_data['new_blog_details']['path'] = $path;
         }
         $process_data['activation_key'] = $activation_key;
     }
     //Set Level and period in upgraded blog details, if blog id is set, for upgrades
     if (!empty($blog_id)) {
         $new_blog = false;
         if (!empty($level) && !empty($period)) {
             $process_data['upgraded_blog_details']['level'] = $level;
             $process_data['upgraded_blog_details']['period'] = $period;
         }
         $current = $wpdb->get_row("SELECT * FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '{$blog_id}'");
     }
     $signup_type = $new_blog ? 'new_blog_details' : 'upgraded_blog_details';
     // Update the session data with the changed process data.
     ProSites_Helper_Session::session('new_blog_details', $process_data['new_blog_details']);
     ProSites_Helper_Session::session('upgraded_blog_details', $process_data['upgraded_blog_details']);
     ProSites_Helper_Session::session('activation_key', $process_data['activation_key']);
     //After user is redirected back from Paypal
     if (isset($_GET['token'])) {
         //Check if blog id is set, If yes -> Upgrade, else  -> New Setup
         $_POST['level'] = !empty($process_data[$signup_type]) ? $process_data[$signup_type]['level'] : '';
         $_POST['period'] = !empty($process_data[$signup_type]) ? $process_data[$signup_type]['period'] : '';
     }
     //Process The submitted form and redirect user to Paypal for payment or process when the user comes back
     if (isset($_POST['paypal_checkout']) || isset($_POST['paypal_checkout_x']) || isset($_POST['cc_paypal_checkout']) || isset($_GET['token'])) {
         //Check for level, if there is no level and period, return back
         if (empty($_POST['level']) || empty($_POST['period'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return false;
         }
         //prepare vars
         $currency = self::currency();
         $trial_days = $psts->get_setting('trial_days', 0);
         $is_trial = $psts->is_trial_allowed($blog_id);
         $setup_fee = (double) $psts->get_setting('setup_fee', 0);
         $trial_desc = $is_trial ? ProSites_Gateway_PayPalExpressPro::get_free_trial_desc($trial_days) : '';
         $recurring = $psts->get_setting('recurring_subscriptions', true);
         //If free level is selected, activate a trial
         if (isset($_POST['level']) && isset($_POST['period'])) {
             if (!empty($domain) && !$psts->prevent_dismiss() && '0' === $_POST['level'] && '0' === $_POST['period']) {
                 $esc_domain = esc_url($domain);
                 ProSites_Helper_Registration::activate_blog($process_data['activation_key'], $is_trial, $process_data[$signup_type]['period'], $process_data[$signup_type]['level']);
                 //Set complete message
                 self::$complete_message = __('Your trial blog has been setup at <a href="' . $esc_domain . '">' . $esc_domain . '</a>', 'psts');
                 return;
             }
         }
         //Current site name as per the payment procedure
         $site_name = !empty($domain) ? $domain : (!empty($process_data[$signup_type]['domain']) ? $process_data[$signup_type]['domain'] : $current_site->site_name);
         $initAmount = 0;
         $paymentAmountInitial = $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']);
         $has_setup_fee = $psts->has_setup_fee($blog_id, $_POST['level']);
         $has_coupon = isset($process_data['COUPON_CODE']) && ProSites_Helper_Coupons::check_coupon($process_data['COUPON_CODE'], $blog_id, $_POST['level'], $_POST['period'], $domain) ? true : false;
         //Add setup fee to init amount
         if ($has_setup_fee) {
             $initAmount += $setup_fee;
         }
         if ($has_coupon || $has_setup_fee) {
             $lifetime = 'once';
             if ($has_coupon) {
                 //apply coupon
                 $adjusted_values = ProSites_Helper_Coupons::get_adjusted_level_amounts($process_data['COUPON_CODE']);
                 $coupon_obj = ProSites_Helper_Coupons::get_coupon($process_data['COUPON_CODE']);
                 $lifetime = isset($coupon_obj['lifetime']) && 'indefinite' == $coupon_obj['lifetime'] ? 'forever' : 'once';
                 //	$coupon_value = $psts->coupon_value( $process_data['COUPON_CODE'], $paymentAmount );
                 $coupon_value = $adjusted_values[$_POST['level']]['price_' . $_POST['period']];
                 // $amount_off   = $paymentAmount - $coupon_value['new_total'];
                 $amount_off = $paymentAmount - $coupon_value;
                 $initAmount -= $amount_off;
                 $initAmount = 0 > $initAmount ? 0 : $initAmount;
                 // avoid negative
             }
             //Update Tax
             $tax_amt_init = self::calculate_tax($tax_object, $initAmount, true);
             $initAmount += $tax_amt_init;
             $tax_amt_payment = self::calculate_tax($tax_object, $paymentAmount, true);
             $paymentAmount += $tax_amt_payment;
             //Check if it's a recurring subscription
             if ($recurring) {
                 $recurringAmmount = 'forever' == $lifetime && $has_coupon ? $coupon_value : $paymentAmount;
                 if ($_POST['period'] == 1) {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($currency, $initAmount + $paymentAmount), $psts->format_currency($currency, $recurringAmmount));
                 } else {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first %2$s month period, then %3$s every %4$s months', 'psts'), $psts->format_currency($currency, $initAmount + $paymentAmount), $_POST['period'], $psts->format_currency($currency, $recurringAmmount), $_POST['period']);
                 }
             } else {
                 if (!empty($blog_id)) {
                     //Calculate Upgrade or downgrade cost
                     $paymentAmountInitial = $paymentAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $paymentAmount - $tax_amt_payment);
                     //Calculate tax
                     $tax_amt_payment = self::calculate_tax($tax_object, $paymentAmount, true);
                     $paymentAmount += $tax_amt_payment;
                 }
                 if ($_POST['period'] == 1) {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $paymentAmount + $initAmount));
                 } else {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $paymentAmount + $initAmount), $_POST['period']);
                 }
             }
         } elseif ($recurring) {
             //Calculate Tax
             $tax_amt_init = self::calculate_tax($tax_object, $initAmount, true);
             $initAmount += $tax_amt_init;
             $tax_amt_payment = self::calculate_tax($tax_object, $paymentAmount, true);
             $paymentAmount += $tax_amt_payment;
             if ($_POST['period'] == 1) {
                 $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency);
             } else {
                 $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every %3$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency, $_POST['period']);
             }
         } else {
             //New Signups
             if (!empty($blog_id)) {
                 $paymentAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $paymentAmount - $tax_amt_payment);
             }
             //Calculate Tax
             $tax_amt_init = self::calculate_tax($tax_object, $initAmount, true);
             $initAmount += $tax_amt_init;
             $tax_amt_payment = self::calculate_tax($tax_object, $paymentAmount, true);
             $paymentAmount += $tax_amt_payment;
             if ($_POST['period'] == 1) {
                 $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $paymentAmount));
             } else {
                 $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $_POST['period']);
             }
         }
         //Update Description for Tax
         if ($tax_object->apply_tax) {
             $desc .= sprintf(__('(includes tax of %s%% [%s])', 'psts'), $tax_object->tax_rate * 100, $tax_object->country);
         }
         $desc = apply_filters('psts_pypl_checkout_desc', $desc, $_POST['period'], $_POST['level'], $paymentAmount, $initAmount, $blog_id, $domain);
         $modify = self::is_modifying($blog_id, $_POST, $initAmount - $tax_amt_init);
     }
     //Runs just after the paypal button click, process paypal express checkout
     if (isset($_POST['paypal_checkout']) || isset($_POST['paypal_checkout_x'])) {
         //check for level
         if (!isset($_POST['period']) || !isset($_POST['level'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return;
         }
         //If not recurring and there is a trial, Force recurring subscription with 1 Billing cycle
         if (!$recurring && $is_trial) {
             $force_recurring = true;
         } else {
             $force_recurring = false;
         }
         if (!$is_trial && !$recurring) {
             $resArray = PaypalApiHelper::SetExpressCheckout($initAmount + $paymentAmount, $desc, $blog_id, $domain, $force_recurring);
         } else {
             $resArray = PaypalApiHelper::SetExpressCheckout($paymentAmount, $desc, $blog_id, $domain, $force_recurring);
         }
         if (isset($resArray['ACK']) && ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning')) {
             $token = $resArray["TOKEN"];
             PaypalApiHelper::RedirectToPayPal($token);
         } else {
             $psts->errors->add('general', sprintf(__('There was a problem setting up the paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), self::parse_error_string($resArray)));
         }
     }
     /* ------------------- PayPal Checkout ----------------- */
     //!check for return from Express Checkout
     if (isset($_GET['token']) && isset($_POST['period']) && isset($_POST['level'])) {
         if (!empty($_GET['action']) && $_GET['action'] == 'canceled') {
             return false;
         }
         //Set payerID if missing
         if (!isset($_GET['PayerID'])) {
             $details = PaypalApiHelper::GetExpressCheckoutDetails($_GET['token']);
             if (isset($details['PAYERID'])) {
                 $_GET['PayerID'] = $details['PAYERID'];
             }
         }
         $domain = !empty($domain) ? $domain : (!empty($process_data[$signup_type]['domain']) ? $process_data[$signup_type]['domain'] : '');
         $path = !empty($path) ? $path : (!empty($process_data[$signup_type]['path']) ? $process_data[$signup_type]['path'] : '');
         $activation_key = !empty($process_data['activation_key']) ? $process_data['activation_key'] : '';
         //Non Recurring - Handle One time payment for new signups and upgrades, Paypal doesn't supports trial for one time payments, so we create a subscription
         // with 1 billing cycle
         if (!$recurring) {
             //Non recurring Upgrades, Non Recurring signup without trial
             if ($modify || !$is_trial) {
                 $resArray = PaypalApiHelper::DoExpressCheckoutPayment($_GET['token'], $_GET['PayerID'], $initAmount + $paymentAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $activation_key, $tax_amt_init + $tax_amt_payment);
                 if ($resArray['PAYMENTINFO_0_ACK'] == 'Success' || $resArray['PAYMENTINFO_0_ACK'] == 'SuccessWithWarning') {
                     $payment_status = $resArray['PAYMENTINFO_0_PAYMENTSTATUS'];
                     $paymentAmount = $resArray['PAYMENTINFO_0_AMT'];
                     $init_transaction = $resArray['PAYMENTINFO_0_TRANSACTIONID'];
                     if ($modify) {
                         //Plan Update
                         $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Initial payment successful (%1$s) - Transaction ID: %2$s', 'psts'), $desc, $init_transaction));
                         $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $_POST['level'], 'period' => $_POST['period'], 'prev_level' => !empty($current->level) ? $current->level : '', 'prev_period' => !empty($current->term) ? $current->term : '');
                         ProSites_Helper_Session::session('plan_updated', $updated);
                     } else {
                         //New Signup, Activate blog
                         $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                         $blog_id = !empty($site_details) ? $site_details['blog_id'] : $blog_id;
                         $psts->log_action($blog_id, sprintf(__('User creating modifying subscription via PayPal Express: Payment successful (%1$s) - Transaction ID: %2$s', 'psts'), $desc, $init_transaction));
                     }
                     //just in case, try to cancel any old subscription
                     if (!empty($blog_id) && ($profile_id = self::get_profile_id($blog_id))) {
                         PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                     }
                     //now get the details of the transaction to see if initial payment went through already
                     if ($payment_status == 'Completed' || $payment_status == 'Processed') {
                         $old_expire = $psts->get_expire($blog_id);
                         $new_expire = $old_expire > time() ? $old_expire : false;
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']), $new_expire, false);
                         $psts->email_notification($blog_id, 'success');
                         $psts->record_transaction($blog_id, $init_transaction, $paymentAmount);
                         if ($modify) {
                             if ($process_data[$signup_type]['level'] > ($old_level = $psts->get_level($blog_id))) {
                                 $psts->record_stat($blog_id, 'upgrade');
                             } else {
                                 $psts->record_stat($blog_id, 'modify');
                             }
                             $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $_POST['level'], 'period' => $_POST['period'], 'prev_level' => !empty($current->level) ? $current->level : '', 'prev_period' => !empty($current->term) ? $current->term : '');
                             ProSites_Helper_Session::session('plan_updated', $updated);
                         } else {
                             $psts->record_stat($blog_id, 'signup');
                         }
                         do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']);
                         if (empty(self::$complete_message)) {
                             self::$complete_message = __('Your PayPal subscription was successful! You should be receiving an email receipt shortly.', 'psts');
                         }
                     } else {
                         //If payment is pending for some reason, store the details, to display it on Checkout screen later
                         if ($payment_status == 'Pending') {
                             self::update_pending_reason($blog_id, $payment_status, $resArray['PAYMENTINFO_0_PENDINGREASON'], $_GET['PayerID']);
                         }
                         if (!empty($blog_id)) {
                             //Set expiry for 4 hours from now, and set waiting step as 1, until payment is confirmed from Paypal
                             $expiry = strtotime('+ 4 Hours');
                             //Extend the Blog expiry as per Trial or not
                             $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $expiry);
                         }
                         update_blog_option($blog_id, 'psts_waiting_step', 1);
                     }
                     self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                     if (!empty($init_transaction)) {
                         //Update Evidence string in table
                         self::update_evidence($blog_id, $init_transaction, $evidence_string);
                     }
                 }
                 //End of Check if transaction was successful, for non recurring signup and upgrade
                 //End of if no trial, or non recurring upgrade
             } else {
                 //If there is a trial, create a subscription with total 1 billing cycle
                 //create the recurring profile, with 1 total billing cycle
                 $resArray = PaypalApiHelper::CreateRecurringPaymentsProfileExpress($_GET['token'], $paymentAmountInitial, $initAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], '', $activation_key, 1, $tax_amt_payment);
                 $profile_status = !empty($resArray['PROFILESTATUS']) ? $resArray['PROFILESTATUS'] : '';
                 //If Profile is created
                 if (isset($resArray['ACK']) && ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning')) {
                     //Blog might be already active
                     $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                     $blog_id = !empty($site_details) ? $site_details['blog_id'] : $blog_id;
                     if (!empty($blog_id)) {
                         //save new profile_id
                         self::set_profile_id($blog_id, $resArray["PROFILEID"]);
                         //update the blog id in paypal custom so that future payments are applied to the proper blog id
                         $custom = PSTS_PYPL_PREFIX . '_' . $blog_id . "_" . $_POST['level'] . '_' . $_POST['period'] . '_' . $initAmount . '_' . self::currency() . '_' . time() . '_' . $activation_key;
                         PaypalApiHelper::UpdateRecurringPaymentsProfile($resArray["PROFILEID"], $custom);
                         $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]));
                         //Store Payment , for rendering the confirmation on checkout page
                         self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                     } else {
                         //Store in signup meta for domain
                         self::set_profile_id('', $resArray["PROFILEID"], $domain);
                         $psts->log_action('', sprintf(__('User creating new subscription via PayPal Express: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]), $domain);
                     }
                 } elseif (!empty($resArray['ACK'])) {
                     //If payment was declined, or user returned
                     $psts->errors->add('general', sprintf(__('There was a problem processing the Paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), self::parse_error_string($resArray)));
                     //Log action
                     $psts->log_action($blog_id, sprintf(__('User creating subscription via PayPal Express: PayPal returned an error: %s', 'psts'), self::parse_error_string($resArray)), $domain);
                 } else {
                     self::$complete_message = __('Your initial PayPal transaction was successful, but there was a problem creating the subscription so you may need to renew when the first period is up. Your site should be upgraded shortly.', 'psts') . '<br />"<strong>' . self::parse_error_string($resArray) . '</strong>"';
                     $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Problem creating the subscription after successful initial payment. User may need to renew when the first period is up: %s', 'psts'), self::parse_error_string($resArray)), $domain);
                 }
                 //now get the details of the transaction to see if initial payment went through already
                 if ($is_trial || $profile_status == 'ActiveProfile') {
                     //If we have domain details, activate the blog, It will be extended later in the same code block
                     $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                     if (empty($blog_id) && !empty($site_details)) {
                         $blog_id = !empty($site_details['blog_id']) ? $site_details['blog_id'] : $blog_id;
                     }
                     //If we have blog id, Extend the blog expiry
                     if (!empty($blog_id)) {
                         //Trial is allowed, set expiry date to n number of days from today, where n is number of days for trial
                         $paymentAmount = '';
                         $trial = strtotime('+ ' . $trial_days . ' days');
                         //Extend the Blog expiry as per Trial or not
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $trial);
                     }
                     $psts->record_stat($blog_id, 'signup');
                     $psts->email_notification($blog_id, 'success');
                     // Added for affiliate system link
                     do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']);
                     if (empty(self::$complete_message)) {
                         self::$complete_message = __('Your PayPal subscription was successful! You should be receiving an email receipt shortly.', 'psts');
                     }
                 } else {
                     //If we have blog id
                     if (!empty($blog_id)) {
                         self::update_pending_reason($blog_id, $profile_status, '', $_GET['PayerID'], __("Initial amount not confirmed for subscription, Please check your associated Paypal account."));
                         //Set expiry for 4 hours from now, and set waiting step as 1, until payment is confirmed from Paypal
                         $expiry = strtotime('+ 4 Hours');
                         update_blog_option($blog_id, 'psts_waiting_step', 1);
                         //Extend the Blog expiry as per Trial or not
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $expiry);
                     } else {
                         //Update Domain meta
                         $signup_meta = '';
                         $signup = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->signups} WHERE domain = %s", $domain));
                         if (!empty($signup)) {
                             $signup_meta = maybe_unserialize($signup->meta);
                         }
                         $signup_meta['psts_waiting_step'] = 1;
                         $wpdb->update($wpdb->signups, array('meta' => serialize($signup_meta)), array('domain' => $domain));
                     }
                 }
                 //End of else, if its trial or payment completed
                 if (!empty($blog_id)) {
                     self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                     //@Todo: check this, as there ain't going to be a transaction id, so better use the profile id
                     //Store Evidence string for the transaction ID
                     $txn_id = !empty($resArray['TRANSACTIONID']) ? $resArray['TRANSACTIONID'] : (!empty($resArray['PROFILEID']) ? $resArray['PROFILEID'] : '');
                     if (!empty($txn_id)) {
                         //Update Evidence string in table
                         self::update_evidence($blog_id, $txn_id, $evidence_string);
                     }
                 }
             }
             //End of Non Recurring subscriptions
         } else {
             //Recurring Subscription
             //Upgrade
             if ($modify) {
                 //! create the recurring profile
                 $resArray = PaypalApiHelper::CreateRecurringPaymentsProfileExpress($_GET['token'], $paymentAmountInitial, $initAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $modify, $activation_key, '', $tax_amt_payment);
                 if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                     $new_profile_id = $resArray["PROFILEID"];
                     $end_date = date_i18n(get_blog_option($blog_id, 'date_format'), $modify);
                     $psts->log_action($blog_id, sprintf(__('User modifying subscription via PayPal Express: New subscription created (%1$s), first payment will be made on %2$s - %3$s', 'psts'), $desc, $end_date, $new_profile_id));
                     //cancel old subscription
                     $old_gateway = $wpdb->get_var("SELECT gateway FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '{$blog_id}'");
                     if ($profile_id = self::get_profile_id($blog_id)) {
                         $resArray = PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %1$s subscription has been modified. This previous subscription has been canceled, and your new subscription (%2$s) will begin on %3$s.', 'psts'), $psts->get_setting('rebrand'), $desc, $end_date));
                         if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                             $psts->log_action($blog_id, sprintf(__('User modifying subscription via PayPal Express: Old subscription canceled - %s', 'psts'), $profile_id));
                         }
                     } else {
                         self::manual_cancel_email($blog_id, $old_gateway);
                         //send email for old paypal system
                     }
                     if ($process_data['upgraded_blog_details']['level'] > ($old_level = $psts->get_level($blog_id))) {
                         $psts->record_stat($blog_id, 'upgrade');
                     } else {
                         $psts->record_stat($blog_id, 'modify');
                     }
                     $psts->extend($blog_id, $process_data['upgraded_blog_details']['period'], self::get_slug(), $process_data['upgraded_blog_details']['level'], $paymentAmount, false, true);
                     $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $_POST['level'], 'period' => $_POST['period'], 'prev_level' => !empty($current->level) ? $current->level : '', 'prev_period' => !empty($current->term) ? $current->term : '');
                     ProSites_Helper_Session::session('plan_updated', $updated);
                     //use coupon
                     if ($has_coupon) {
                         $psts->use_coupon($process_data['COUPON_CODE'], $blog_id);
                     }
                     //save new profile_id
                     self::set_profile_id($blog_id, $new_profile_id);
                     //save new period/term
                     $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}pro_sites SET term = %d WHERE blog_ID = %d", $process_data['upgraded_blog_details']['period'], $blog_id));
                     //show confirmation page
                     self::$complete_message = sprintf(__('Your PayPal subscription modification was successful for %s.', 'psts'), $desc);
                     //display GA ecommerce in footer
                     if (!$is_trial) {
                         $psts->create_ga_ecommerce($blog_id, $process_data['upgraded_blog_details']['period'], $initAmount, $process_data['upgraded_blog_details']['level']);
                     }
                     //show instructions for old gateways
                     if ($old_gateway == 'PayPal') {
                         self::$complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your PayPal account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                         self::$complete_message .= '<p><a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_subscr-find&alias=' . urlencode(get_site_option("supporter_paypal_email")) . '"><img src="' . $psts->plugin_url . 'images/cancel_subscribe_gen.gif" /></a><br /><small>' . __('You can also cancel following <a href="https://www.paypal.com/webapps/helpcenter/article/?articleID=94044#canceling_recurring_paymemt_subscription_automatic_billing">these steps</a>.', 'psts') . '</small></p>';
                     } else {
                         if ($old_gateway == 'Amazon') {
                             self::$complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your Amazon Payments account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                             self::$complete_message .= '<p>' . __('To view your subscriptions, simply go to <a target="_blank" href="https://payments.amazon.com/">https://payments.amazon.com/</a>, click Your Account at the top of the page, log in to your Amazon Payments account (if asked), and then click the Your Subscriptions link. This page displays your subscriptions, showing the most recent, active subscription at the top. To view the details of a specific subscription, click Details. Then cancel your subscription by clicking the Cancel Subscription button on the Subscription Details page.', 'psts') . '</p>';
                         }
                     }
                     //@Todo: check this, as there ain't going to be a transaction id, so better use the profile id
                     //Store Evidence string for the transaction ID
                     $txn_id = !empty($resArray['TRANSACTIONID']) ? $resArray['TRANSACTIONID'] : (!empty($resArray['PROFILEID']) ? $resArray['PROFILEID'] : '');
                     if (!empty($txn_id)) {
                         //Update Evidence string in table
                         self::update_evidence($blog_id, $txn_id, $evidence_string);
                     }
                 } else {
                     $psts->errors->add('general', sprintf(__('There was a problem setting up the Paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), self::parse_error_string($resArray)));
                     $psts->log_action($blog_id, sprintf(__('User modifying subscription via PayPal Express: PayPal returned an error: %s', 'psts'), self::parse_error_string($resArray)));
                 }
             } else {
                 //Handle the new signups
                 //use coupon
                 if ($has_coupon) {
                     $psts->use_coupon($process_data['COUPON_CODE'], $blog_id);
                 }
                 //just in case, try to cancel any old subscription
                 if (!empty($blog_id) && ($profile_id = self::get_profile_id($blog_id))) {
                     PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                 }
                 //create the recurring profile
                 $resArray = PaypalApiHelper::CreateRecurringPaymentsProfileExpress($_GET['token'], $paymentAmountInitial, $initAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], '', $activation_key, '', $tax_amt_payment);
                 $profile_status = !empty($resArray['PROFILESTATUS']) ? $resArray['PROFILESTATUS'] : '';
                 //If Profile is created
                 if (isset($resArray['ACK']) && ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning')) {
                     //Blog might be already active
                     $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                     $blog_id = !empty($site_details) ? $site_details['blog_id'] : $blog_id;
                     if (!empty($blog_id)) {
                         //save new profile_id
                         self::set_profile_id($blog_id, $resArray["PROFILEID"]);
                         //update the blog id in paypal custom so that future payments are applied to the proper blog id
                         $custom = PSTS_PYPL_PREFIX . '_' . $blog_id . "_" . $_POST['level'] . '_' . $_POST['period'] . '_' . $initAmount . '_' . self::currency() . '_' . time() . '_' . $activation_key;
                         PaypalApiHelper::UpdateRecurringPaymentsProfile($resArray["PROFILEID"], $custom);
                         $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]));
                         //Store Payment , for rendering the confirmation on checkout page
                         self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                     } else {
                         //Store in signup meta for domain
                         self::set_profile_id('', $resArray["PROFILEID"], $domain);
                         $psts->log_action('', sprintf(__('User creating new subscription via PayPal Express: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]), $domain);
                     }
                 } elseif (!empty($resArray['ACK'])) {
                     //If payment was declined, or user returned
                     $psts->errors->add('general', sprintf(__('There was a problem processing the Paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), self::parse_error_string($resArray)));
                     $psts->log_action($blog_id, sprintf(__('User creating subscription via PayPal Express: PayPal returned an error: %s', 'psts'), self::parse_error_string($resArray)), $domain);
                 } else {
                     self::$complete_message = __('Your initial PayPal transaction was successful, but there was a problem creating the subscription so you may need to renew when the first period is up. Your site should be upgraded shortly.', 'psts') . '<br />"<strong>' . self::parse_error_string($resArray) . '</strong>"';
                     $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Problem creating the subscription after successful initial payment. User may need to renew when the first period is up: %s', 'psts'), self::parse_error_string($resArray)), $domain);
                 }
                 //now get the details of the transaction to see if initial payment went through already
                 if ($is_trial || $profile_status == 'ActiveProfile') {
                     //If there is no blog id
                     if (empty($blog_id)) {
                         $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                         $blog_id = !empty($site_details['blog_id']) ? $site_details['blog_id'] : '';
                     }
                     //If we have blog id, Extend the blog expiry
                     if (!empty($blog_id)) {
                         //If trial is allowed, set expiry date to n number of days from today, where n is number of days for trial
                         if ($is_trial) {
                             $paymentAmount = '';
                             $trial = strtotime('+ ' . $trial_days . ' days');
                         } else {
                             $trial = '';
                         }
                         //Extend the Blog expiry as per Trial or not
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $trial);
                     }
                     $psts->record_stat($blog_id, 'signup');
                     $psts->email_notification($blog_id, 'success');
                     // Added for affiliate system link
                     do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']);
                     if (empty(self::$complete_message)) {
                         self::$complete_message = __('Your PayPal subscription was successful! You should be receiving an email receipt shortly.', 'psts');
                     }
                 } else {
                     //If we have blog id
                     if (!empty($blog_id)) {
                         self::update_pending_reason($blog_id, $profile_status, '', $_GET['PayerID'], __("Initial Amount not confirmed for subscription, Please check your associated Paypal account."));
                         //Set expiry for 4 hours from now, and set waiting step as 1, until payment is confirmed from Paypal
                         $expiry = strtotime('+ 4 Hours');
                         update_blog_option($blog_id, 'psts_waiting_step', 1);
                         //Extend the Blog expiry as per Trial or not
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $expiry);
                     } else {
                         //Update Domain meta
                         $signup_meta = '';
                         $signup = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->signups} WHERE domain = %s", $domain));
                         if (!empty($signup)) {
                             $signup_meta = maybe_unserialize($signup->meta);
                         }
                         $signup_meta['psts_waiting_step'] = 1;
                         $wpdb->update($wpdb->signups, array('meta' => serialize($signup_meta)), array('domain' => $domain));
                     }
                 }
                 if (!empty($blog_id)) {
                     //Store activation key in Pro sites table
                     self::set_blog_identifier($activation_key, $blog_id);
                     //@todo: Use Profile ID instead
                     //Store Evidence string for the transaction ID, for create recurring profile
                     $txn_id = !empty($resArray['TRANSACTIONID']) ? $resArray['TRANSACTIONID'] : (!empty($resArray['PROFILEID']) ? $resArray['PROFILEID'] : '');
                     if (!empty($txn_id)) {
                         //Update Evidence string in table
                         self::update_evidence($blog_id, $txn_id, $evidence_string);
                     }
                 }
                 //display GA ecommerce in footer
                 if (!$is_trial) {
                     $psts->create_ga_ecommerce($blog_id, $_POST['period'], $paymentAmount, $_POST['period']);
                 }
             }
         }
         //End of recurring payments, modify or upgrade
     }
     /*! ------------ CC Checkout ----------------- */
     if (isset($_POST['cc_paypal_checkout'])) {
         //check for level
         if (!isset($_POST['period']) || !isset($_POST['level'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return;
         }
         //process form
         if (isset($_POST['cc_form'])) {
             $error_message = array('general' => __('Whoops, looks like you may have tried to submit    your payment twice so we prevented it. Check your subscription info below to see if it was created. If not, please try again.', 'psts'), 'card-type' => __('Please choose a Card Type.', 'psts'), 'number' => __('Please enter a valid Credit Card Number.', 'psts'), 'expiration' => __('Please choose an expiration date.', 'psts'), 'cvv2' => __('Please enter a valid card security code. This is the 3  digits on the signature panel, or 4 digits on the front of Amex cards.', 'psts'), 'firstname' => __('Please enter your First Name.', 'psts'), 'lastname' => __('Please enter your Last Name.', 'psts'), 'address' => __('Please enter your billing Street Address.', 'psts'), 'city' => __('Please enter your billing City.', 'psts'), 'state' => __('Please enter your billing State/Province.', 'psts'), 'zip' => __('Please enter your billing Zip/Postal Code.', 'psts'), 'country' => __('Please enter your billing Country.', 'psts'));
             //clean up $_POST
             $cc_cardtype = isset($_POST['cc_card-type']) ? $_POST['cc_card-type'] : '';
             $cc_number = isset($_POST['cc_number']) ? stripslashes($_POST['cc_number']) : '';
             $cc_month = isset($_POST['cc_month']) ? $_POST['cc_month'] : '';
             $cc_year = isset($_POST['cc_year']) ? $_POST['cc_year'] : '';
             $cc_firstname = isset($_POST['cc_firstname']) ? stripslashes($_POST['cc_firstname']) : '';
             $cc_lastname = isset($_POST['cc_lastname']) ? stripslashes($_POST['cc_lastname']) : '';
             $cc_address = isset($_POST['cc_address']) ? stripslashes($_POST['cc_address']) : '';
             $cc_address2 = isset($_POST['cc_address2']) ? stripslashes($_POST['cc_address2']) : '';
             $cc_city = isset($_POST['cc_city']) ? stripslashes($_POST['cc_city']) : '';
             $cc_state = isset($_POST['cc_state']) ? stripslashes($_POST['cc_state']) : '';
             $cc_zip = isset($_POST['cc_zip']) ? stripslashes($_POST['cc_zip']) : '';
             $cc_country = isset($_POST['cc_country']) ? stripslashes($_POST['cc_country']) : '';
             $cc_number = preg_replace('/[^0-9]/', '', $cc_number);
             //strip any slashes
             $_POST['cc_cvv2'] = preg_replace('/[^0-9]/', '', $_POST['cc_cvv2']);
             //check nonce
             if (!self::check_nonce()) {
                 $psts->errors->add('general', $error_message['general']);
             }
             if (empty($cc_cardtype)) {
                 $psts->errors->add('card-type', $error_message['card-type']);
             }
             if (empty($cc_number)) {
                 $psts->errors->add('number', $error_message['number']);
             }
             if (empty($cc_month) || empty($cc_year)) {
                 $psts->errors->add('expiration', $error_message['expiration']);
             }
             if (strlen($_POST['cc_cvv2']) < 3 || strlen($_POST['cc_cvv2']) > 4) {
                 $psts->errors->add('cvv2', $error_message['cvv2']);
             }
             if (empty($cc_firstname)) {
                 $psts->errors->add('firstname', $error_message['firstname']);
             }
             if (empty($cc_lastname)) {
                 $psts->errors->add('lastname', $error_message['lastname']);
             }
             if (empty($cc_address)) {
                 $psts->errors->add('address', $error_message['address']);
             }
             if (empty($_POST['cc_city'])) {
                 $psts->errors->add('city', $error_message['city']);
             }
             if (($cc_country == 'US' || $cc_country == 'CA') && empty($cc_state)) {
                 $psts->errors->add('state', $error_message['state']);
             }
             if (empty($cc_zip)) {
                 $psts->errors->add('zip', $error_message['zip']);
             }
             if (empty($cc_country) || strlen($cc_country) != 2) {
                 $psts->errors->add('country', $error_message['country']);
             }
             //All fields are Proper, process Card
             if (!$psts->errors->get_error_code()) {
                 if (!$recurring) {
                     //Only Upgrades or signup without trial
                     if ($modify || !$is_trial) {
                         $resArray = PaypalApiHelper::DoDirectPayment($initAmount + $paymentAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email, $activation_key, $tax_amt_init + $tax_amt_payment);
                         if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                             $init_transaction = $resArray["TRANSACTIONID"];
                             $paymentAmount = $resArray['AMT'];
                             if ($modify) {
                                 $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Direct Payment: Initial payment successful (%1$s) - Transaction ID: %2$s', 'psts'), $desc, $init_transaction));
                                 $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $_POST['level'], 'period' => $_POST['period'], 'prev_level' => !empty($current->level) ? $current->level : '', 'prev_period' => !empty($current->term) ? $current->term : '');
                                 ProSites_Helper_Session::session('plan_updated', $updated);
                             } else {
                                 //New Signup, Activate blog
                                 $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                                 $blog_id = !empty($site_details) ? $site_details['blog_id'] : $blog_id;
                                 $psts->log_action($blog_id, sprintf(__('User creating modifying subscription via PayPal Direct Payment: Payment successful (%1$s) - Transaction ID: %2$s', 'psts'), $desc, $init_transaction));
                             }
                             //just in case, try to cancel any old subscription
                             if ($profile_id = self::get_profile_id($blog_id)) {
                                 PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                             }
                             //Calculate the new expiry and extend the blog expiry
                             $old_expire = $psts->get_expire($blog_id);
                             $new_expire = $old_expire && $old_expire > time() ? $old_expire : false;
                             $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']), $new_expire, false);
                             //Notify blog user
                             $psts->email_notification($blog_id, 'success');
                             //Update Log
                             $psts->record_transaction($blog_id, $init_transaction, $paymentAmount);
                             if ($modify) {
                                 if ($_POST['level'] > ($old_level = $psts->get_level($blog_id))) {
                                     $psts->record_stat($blog_id, 'upgrade');
                                     $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $_POST['level'], 'period' => $_POST['period'], 'prev_level' => !empty($current->level) ? $current->level : '', 'prev_period' => !empty($current->term) ? $current->term : '');
                                     ProSites_Helper_Session::session('plan_updated', $updated);
                                 } else {
                                     $psts->record_stat($blog_id, 'modify');
                                 }
                             } else {
                                 //New Signup
                                 $psts->record_stat($blog_id, 'signup');
                                 //Update Activation Key
                                 self::set_blog_identifier($activation_key, $blog_id);
                             }
                             //Store Payment , for rendering the confirmation on checkout page
                             self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                             do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']);
                             if (empty(self::$complete_message)) {
                                 self::$complete_message = __('Your PayPal subscription was successful! You should be receiving an email receipt shortly.', 'psts');
                             }
                             //Store Evidence string for the transaction ID
                             if (!empty($init_transaction)) {
                                 //Update Evidence string in table
                                 self::update_evidence($blog_id, $init_transaction, $evidence_string);
                             }
                         } elseif ($resArray['ACK'] == 'Failure' && !empty($resArray['L_SHORTMESSAGE0'])) {
                             $psts->errors->add('general', $resArray['L_SHORTMESSAGE0']);
                         } else {
                             update_blog_option($blog_id, 'psts_waiting_step', 1);
                         }
                         //End of if upgrade or not trial
                     } else {
                         //Non Recurring signup with trial - Direct Payment, Create a subscription with total 1 billing cycle
                         //just in case, try to cancel any old subscription
                         if (!empty($blog_id) && ($profile_id = self::get_profile_id($blog_id))) {
                             PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                         }
                         //use coupon
                         if ($has_coupon) {
                             $psts->use_coupon($process_data['COUPON_CODE'], $blog_id, $domain);
                         }
                         //now attempt to create the subscription
                         $resArray = PaypalApiHelper::CreateRecurringPaymentsProfileDirect($paymentAmountInitial, $initAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email, '', $activation_key, 1, $tax_amt_payment);
                         $profile_status = !empty($resArray['PROFILESTATUS']) ? $resArray['PROFILESTATUS'] : '';
                         //If recurring profile was created successfully
                         if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                             if (empty($blog_id)) {
                                 $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                                 $blog_id = !empty($site_details['blog_id']) ? $site_details['blog_id'] : '';
                             }
                             if (!empty($blog_id)) {
                                 //save new profile_id
                                 self::set_profile_id($blog_id, $resArray["PROFILEID"]);
                                 //update the profile id in paypal so that future payments are applied to the proper blog id
                                 $custom = PSTS_PYPL_PREFIX . '_' . $blog_id . "_" . $_POST['level'] . '_' . $_POST['period'] . '_' . $initAmount . '_' . self::currency() . '_' . time() . '_' . $activation_key;
                                 PaypalApiHelper::UpdateRecurringPaymentsProfile($resArray["PROFILEID"], $custom);
                                 $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]), $domain);
                                 //Store Payment , for rendering the confirmation on checkout page
                                 self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                                 //Store activation key in Pro Sites table
                                 self::set_blog_identifier($activation_key, $blog_id);
                             } else {
                                 //Store in signup meta for domain
                                 self::set_profile_id('', $resArray["PROFILEID"], $domain);
                                 $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]));
                             }
                         } else {
                             self::$complete_message = __('Your initial payment was successful, but there was a problem creating the subscription with your credit card so you may need to renew when the first period is up. Your site should be upgraded shortly.', 'psts') . '<br />"<strong>' . self::parse_error_string($resArray) . '</strong>"';
                             $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Problem creating the subscription after successful initial payment. User may need to renew when the first period is up: %s', 'psts'), self::parse_error_string($resArray)), $domain);
                         }
                         if (!empty($blog_id)) {
                             $psts->email_notification($blog_id, 'success');
                             $psts->record_stat($blog_id, 'signup');
                         }
                         //now get the details of the transaction to see if initial payment went through
                         if ($profile_status == 'ActiveProfile') {
                             $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount);
                             if (empty(self::$complete_message)) {
                                 self::$complete_message = sprintf(__('Your Credit Card subscription was successful! You should be receiving an email receipt at %s shortly.', 'psts'), get_blog_option($blog_id, 'admin_email'));
                             }
                         } else {
                             self::update_pending_reason($blog_id, $profile_status, '', $_GET['PAYERID'], __("Initial Amount not confirmed for subscription, Please check your associated Paypal account."));
                             //Set expiry for 4 hours from now, and set waiting step as 1, until payment is confirmed from Paypal
                             $expiry = strtotime('+ 4 Hours');
                             //Extend the Blog expiry as per Trial or not
                             $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $expiry);
                             update_blog_option($blog_id, 'psts_waiting_step', 1);
                         }
                         $txn_id = !empty($resArray['TRANSACTIONID']) ? $resArray['TRANSACTIONID'] : (!empty($resArray['PROFILEID']) ? $resArray['PROFILEID'] : '');
                         if (!empty($txn_id)) {
                             //Update Evidence string in table
                             self::update_evidence($blog_id, $init_transaction, $evidence_string);
                         }
                     }
                     //End of Non Recurring subscription with trial - Direct Payment
                 } elseif ($modify) {
                     $old_profile = false;
                     if ($profile_id = self::get_profile_id($blog_id)) {
                         $old_profile = PaypalApiHelper::GetRecurringPaymentsProfileDetails($profile_id);
                         if (strtotime($old_profile['PROFILESTARTDATE']) > gmdate('U') && (int) $old_profile['TRIALAMTPAID'] == 0) {
                             $is_trial = true;
                         }
                     }
                     //create the recurring profile
                     $resArray = PaypalApiHelper::CreateRecurringPaymentsProfileDirect($paymentAmountInitial, $initAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email, $modify, $activation_key, '', $tax_amt_payment);
                     if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                         $new_profile_id = $resArray["PROFILEID"];
                         $end_date = date_i18n(get_blog_option($blog_id, 'date_format'), $modify);
                         $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: New subscription created (%1$s), first payment will be made on %2$s - %3$s', 'psts'), $desc, $end_date, $new_profile_id));
                         //cancel old subscription
                         $old_gateway = $wpdb->get_var("SELECT gateway FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '{$blog_id}'");
                         if ($old_profile) {
                             $resArray = PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %1$s subscription has been modified. This previous subscription has been canceled, and your new subscription (%2$s) will begin on %3$s.', 'psts'), $psts->get_setting('rebrand'), $desc, $end_date));
                             if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                                 $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: Old subscription canceled - %s', 'psts'), $profile_id));
                             }
                         } else {
                             self::manual_cancel_email($blog_id, $old_gateway);
                             //send email for old paypal system
                         }
                         //extend
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $is_trial ? '' : $paymentAmount, $is_trial ? $psts->get_expire($blog_id) : false);
                         $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $_POST['level'], 'period' => $_POST['period'], 'prev_level' => !empty($current->level) ? $current->level : '', 'prev_period' => !empty($current->term) ? $current->term : '');
                         ProSites_Helper_Session::session('plan_updated', $updated);
                         //Store Payment , for rendering the confirmation on checkout page
                         self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                         //use coupon
                         if ($has_coupon) {
                             $psts->use_coupon($process_data['COUPON_CODE'], $blog_id);
                         }
                         //save new profile_id
                         self::set_profile_id($blog_id, $new_profile_id);
                         //show confirmation page
                         self::$complete_message = sprintf(__('Your Credit Card subscription modification was successful for %s.', 'psts'), $desc);
                         //display GA ecommerce in footer
                         $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $cc_city, $cc_state, $cc_country);
                         //show instructions for old gateways
                         if ($old_gateway == 'PayPal') {
                             self::$complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your PayPal account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                             self::$complete_message .= '<p><a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_subscr-find&alias=' . urlencode(get_site_option("supporter_paypal_email")) . '"><img src="' . $psts->plugin_url . 'images/cancel_subscribe_gen.gif" /></a><br /><small>' . __('You can also cancel following <a href="https://www.paypal.com/helpcenter/main.jsp;jsessionid=SCPbTbhRxL6QvdDMvshNZ4wT2DH25d01xJHj6cBvNJPGFVkcl6vV!795521328?t=solutionTab&ft=homeTab&ps=&solutionId=27715&locale=en_US&_dyncharset=UTF-8&countrycode=US&cmd=_help-ext">these steps</a>.', 'psts') . '</small></p>';
                         } else {
                             if ($old_gateway == 'Amazon') {
                                 self::$complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your Amazon Payments account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                                 self::$complete_message .= '<p>' . __('To view your subscriptions, simply go to <a target="_blank" href="https://payments.amazon.com/">https://payments.amazon.com/</a>, click Your Account at the top of the page, log in to your Amazon Payments account (if asked), and then click the Your Subscriptions link. This page displays your subscriptions, showing the most recent, active subscription at the top. To view the details of a specific subscription, click Details. Then cancel your subscription by clicking the Cancel Subscription button on the Subscription Details page.', 'psts') . '</p>';
                             }
                         }
                         //Store Evidence string for the transaction ID
                         $txn_id = !empty($resArray['TRANSACTIONID']) ? $resArray['TRANSACTIONID'] : (!empty($resArray['PROFILEID']) ? $resArray['PROFILEID'] : '');
                         if (!empty($txn_id)) {
                             //Update Evidence string in table
                             self::update_evidence($blog_id, $txn_id, $evidence_string);
                         }
                     } else {
                         $psts->errors->add('general', sprintf(__('There was a problem with your Credit Card information:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), self::parse_error_string($resArray)));
                         $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: PayPal returned a problem with Credit Card info: %s', 'psts'), self::parse_error_string($resArray)));
                     }
                 } else {
                     //new or expired signup
                     //attempt initial direct payment
                     $success = $init_transaction = false;
                     $domain = !empty($domain) ? $domain : (!empty($process_data[$signup_type]['domain']) ? $process_data[$signup_type]['domain'] : '');
                     //use coupon
                     if ($has_coupon) {
                         $psts->use_coupon($process_data['COUPON_CODE'], $blog_id, $domain);
                     }
                     //now attempt to create the subscription
                     $resArray = PaypalApiHelper::CreateRecurringPaymentsProfileDirect($paymentAmountInitial, $initAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email, '', $activation_key, '', $tax_amt_payment);
                     $profile_status = !empty($resArray['PROFILESTATUS']) ? $resArray['PROFILESTATUS'] : '';
                     //If recurring profile was created successfully
                     if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                         $site_details = ProSites_Helper_Registration::activate_blog($activation_key, $is_trial, $_POST['period'], $_POST['level']);
                         $blog_id = !empty($site_details['blog_id']) ? $site_details['blog_id'] : $blog_id;
                         if (!empty($blog_id)) {
                             //just in case, try to cancel any old subscription
                             if (!empty($blog_id) && ($profile_id = self::get_profile_id($blog_id))) {
                                 PaypalApiHelper::ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                             }
                             //save new profile_id
                             self::set_profile_id($blog_id, $resArray["PROFILEID"]);
                             //update the profile id in paypal so that future payments are applied to the proper blog id
                             $custom = PSTS_PYPL_PREFIX . '_' . $blog_id . "_" . $_POST['level'] . '_' . $_POST['period'] . '_' . $initAmount . '_' . self::currency() . '_' . time() . '_' . $activation_key;
                             PaypalApiHelper::UpdateRecurringPaymentsProfile($resArray["PROFILEID"], $custom);
                             $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]), $domain);
                             //Store Payment , for rendering the confirmation on checkout page
                             self::update_session_vars($process_data, array('blog_id' => $blog_id, 'level' => $level, 'period' => $period));
                             //Store activation key in Pro Sites table
                             self::set_blog_identifier($activation_key, $blog_id);
                         } else {
                             //Store in signup meta for domain
                             self::set_profile_id('', $resArray["PROFILEID"], $domain);
                             $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]));
                         }
                     } else {
                         self::$complete_message = __('Your initial payment was successful, but there was a problem creating the subscription with your credit card so you may need to renew when the first period is up. Your site should be upgraded shortly.', 'psts') . '<br />"<strong>' . self::parse_error_string($resArray) . '</strong>"';
                         $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Problem creating the subscription after successful initial payment. User may need to renew when the first period is up: %s', 'psts'), self::parse_error_string($resArray)), $domain);
                     }
                     if (!empty($blog_id)) {
                         $psts->email_notification($blog_id, 'success');
                         $psts->record_stat($blog_id, 'signup');
                     }
                     //now get the details of the transaction to see if initial payment went through
                     if ($profile_status == 'ActiveProfile') {
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount);
                         if (empty(self::$complete_message)) {
                             self::$complete_message = sprintf(__('Your Credit Card subscription was successful! You should be receiving an email receipt at %s shortly.', 'psts'), get_blog_option($blog_id, 'admin_email'));
                         }
                     } else {
                         update_blog_option($blog_id, 'psts_waiting_step', 1);
                         $expiry = strtotime('+ 4 Hours');
                         //Extend the Blog expiry as per Trial or not
                         $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $paymentAmount, $expiry);
                     }
                     //Store Evidence string for the transaction ID
                     $txn_id = !empty($resArray['TRANSACTIONID']) ? $resArray['TRANSACTIONID'] : (!empty($resArray['PROFILEID']) ? $resArray['PROFILEID'] : '');
                     if (!empty($txn_id)) {
                         //Update Evidence string in table
                         self::update_evidence($blog_id, $txn_id, $evidence_string);
                     }
                     //display GA ecommerce in footer
                     if (!$is_trial) {
                         $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $cc_city, $cc_state, $cc_country);
                     }
                 }
             } else {
                 $psts->errors->add('general', __('There was a problem with your credit card information. Please check all fields and try again.', 'psts'));
             }
         }
     }
     //If there are any errors, store them in $_POST
     $error_codes = $psts->errors->get_error_codes();
     if (is_wp_error($psts->errors) && !empty($error_codes)) {
         $_POST['errors'] = $psts->errors;
     }
 }
Esempio n. 3
0
	function __construct() {

		// Creates the class autoloader.
		spl_autoload_register( array( $this, 'class_loader' ) );

		//setup our variables
		$this->init_vars();

		//install plugin
		register_activation_hook( __FILE__, array( $this, 'install' ) );

		//load dashboard notice
		global $wpmudev_notices;
		$wpmudev_notices[] = array(
			'id'      => 49,
			'name'    => 'Pro Sites',
			'screens' => array(
				'toplevel_page_psts-network',
				'pro-sites_page_psts-stats-network',
				'pro-sites_page_psts-coupons-network',
				'pro-sites_page_psts-levels-network',
				'pro-sites_page_psts-modules-network',
				'pro-sites_page_psts-plugins-network',
				'pro-sites_page_psts-themes-network',
				'pro-sites_page_psts-settings-network',
				'pro-sites_page_psts-gateways-network',
				'pro-sites_page_psts-pricing-settings-network',
			)
		);
		include_once( $this->plugin_dir . 'dash-notice/wpmudev-dash-notification.php' );

		// Force sessions to activate
		add_action( 'init', array( 'ProSites_Helper_Session', 'attempt_force_sessions' ) );

		//load plugins
		require_once( $this->plugin_dir . 'plugins-loader.php' );

		// TAX integration
		ProSites_Helper_Tax::init_tax();

		// Other integrations
		ProSites_Helper_Integration::init();

		/**
		 * Temporary loading for modules
		 *
		 * @todo Improve this
		 */
		//add important filters
		$modules = get_site_option( 'psts_settings' );
		$modules = isset( $modules['modules_enabled'] ) ? $modules['modules_enabled'] : array();

		foreach ( $modules as $module ) {
			ProSites_PluginLoader::require_module( $module );
			// Making sure that important filters are in place rather than loading too late
			if( method_exists( $module, 'run_critical_tasks' ) ) {
				call_user_func( array(  $module, 'run_critical_tasks' ) );
			}
		}

		/**
		 * @todo make Taxamo load as module above (above needs changing first)
		 */
		ProSites_Module_Taxamo::init();


		//localize
		add_action( 'plugins_loaded', array( &$this, 'localization' ) );

		//admin page stuff
		add_action( 'network_admin_menu', array( &$this, 'plug_network_pages' ) );
		add_action( 'admin_menu', array( &$this, 'plug_pages' ) );
		add_action( 'admin_bar_menu', array( &$this, 'add_menu_admin_bar' ), 100 );
		add_action( 'wp_head', array( &$this, 'add_menu_admin_bar_css' ) );
		add_action( 'admin_head', array( &$this, 'add_menu_admin_bar_css' ) );
		add_filter( 'wpmu_blogs_columns', array( &$this, 'add_column' ) );
		add_action( 'manage_sites_custom_column', array( &$this, 'add_column_field' ), 1, 3 );

		add_action( 'init', array( &$this, 'check' ) );
		add_action( 'load-toplevel_page_psts-checkout', array( &$this, 'redirect_checkout' ) );
		add_action( 'admin_init', array(
			&$this,
			'signup_redirect'
		), 100 ); //delay to make sure it is last hook to admin_init

		//trials
		add_action( 'wpmu_new_blog', array( &$this, 'trial_extend' ) );
		add_action( 'admin_notices', array( &$this, 'trial_notice' ), 2 );

		add_action( 'pre_get_posts', array( &$this, 'checkout_page_load' ) );

		// Change signup...
		add_filter( 'register', array( &$this, 'prosites_signup_url' ) );

		add_filter( 'psts_primary_checkout_table', array( 'ProSites_View_Front_Checkout', 'render_checkout_page' ), 10, 3 );
		// Add Registration AJAX handler
		ProSites_Model_Registration::add_ajax_hook();
		add_filter( 'prosite_register_blog_pre_validation', array( 'ProSites_Model_Registration', 'cleanup_unused_user' ), 10, 3 );

//		add_action( 'signup_finished', array( 'ProSites_View_Front_Registration', 'render_signup_finished' ) );
		add_action( 'wp_enqueue_scripts', array( &$this, 'registration_page_styles' ) );
		add_filter( 'update_welcome_email', array( 'ProSites_Helper_Registration', 'alter_welcome_for_existing_users' ), 10, 6 );

		//handle signup pages
		add_action('init','ProSites_Helper_ProSite::redirect_signup_page' );
		add_filter( 'prosites_render_checkout_page_period', 'ProSites_View_Front_Gateway::select_current_period', 10, 2 );
		add_filter( 'prosites_render_checkout_page_level', 'ProSites_View_Front_Gateway::select_current_level', 10, 2 );
		// Dismissed signup prompt
		if ( isset( $_GET['psts_dismiss'] ) ) {
			update_option( 'psts_signed_up', 0 );
		}

//		add_action( 'signup_blogform', array( &$this, 'signup_output' ) );
//		add_action( 'bp_after_blog_details_fields', array( &$this, 'signup_output' ) );
//		add_action( 'signup_extra_fields', array( &$this, 'signup_override' ) );
//		add_filter( 'add_signup_meta', array( &$this, 'signup_save' ) );
//		add_filter( 'bp_signup_usermeta', array( &$this, 'signup_save' ) );

		//Force Used Space Check in network if quota is enabled
		add_action( 'psts_modules_save', array( $this, 'enable_network_used_space_check' ) );

		add_action( 'psts_process_stats', array( &$this, 'process_stats' ) ); //cronjob hook
		add_filter( 'blog_template_exclude_settings', array(
			&$this,
			'blog_template_settings'
		) ); // exclude pro site setting from blog template copies

		//Disable activation emails
		add_filter( 'wpmu_signup_user_notification', array( $this, 'disable_user_activation_mail' ), 10 );

		//Disable Blog Activation Email, as of Pay before blog creation
		add_filter( 'wpmu_signup_blog_notification', array( $this, 'disable_user_activation_mail' ), 10 );



		//Redirect to checkout page after signup
//		add_action( 'signup_finished', array( $this, 'signup_redirect_checkout' ) );
//		add_action( 'bp_complete_signup', array( $this, 'signup_redirect_checkout' ) );

		//Register styles
		add_action( 'admin_enqueue_scripts', array( $this, 'register_psts_style' ) );

		//Display the asterisk detail in sites screen
		add_action( 'in_admin_footer', array( $this, 'psts_note' ) );

		//update install script if necessary
		if ( ( ! defined( 'PSTS_DISABLE_UPGRADE' ) || ( defined( 'PSTS_DISABLE_UPGRADE' ) && ! PSTS_DISABLE_UPGRADE ) ) && $this->get_setting( 'version' ) != $this->version ) {
			$this->install();
		}

		// Hooking here until the models get reworked.
		add_action( 'psts_extend', array( $this, 'send_extension_email' ), 10, 4 );

		// New receipt
		add_action( 'prosites_transaction_record', array( get_class(), 'send_receipt' ) );

		$this->setup_ajax_hooks();

		$this->errors = new WP_Error();

	}