/** * @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; } }
function admin_modify() { global $wpdb, $current_user; if ( ! is_super_admin() ) { echo "<p>" . __( 'Nice Try...', 'psts' ) . "</p>"; //If accessed properly, this message doesn't appear. return; } //add manual log entries if ( isset( $_POST['log_entry'] ) ) { $this->log_action( (int) $_GET['bid'], $current_user->display_name . ': "' . strip_tags( stripslashes( $_POST['log_entry'] ) ) . '"' ); echo '<div id="message" class="updated fade"><p>' . __( 'Log entry added.', 'psts' ) . '</p></div>'; } //extend blog if ( isset( $_POST['psts_extend'] ) ) { check_admin_referer( 'psts_extend' ); //check nonce if ( isset( $_POST['extend_permanent'] ) ) { $extend = 9999999999; } else { $months = $_POST['extend_months']; $days = $_POST['extend_days']; $extend = strtotime( "+$months Months $days Days" ) - time(); } $this->extend( (int) $_POST['bid'], $extend, __( 'Manual', 'psts' ), $_POST['extend_level'], false, false, true, true ); echo '<div id="message" class="updated fade"><p>' . __( 'Site Extended.', 'psts' ) . '</p></div>'; } if ( isset( $_POST['psts_transfer_pro'] ) ) { $new_bid = (int) $_POST['new_bid']; $current_bid = (int) $_GET['bid']; if ( ! $new_bid ) { echo '<div id="message" class="error"><p>' . __( 'Please enter the Blog ID of a site to transfer to.', 'psts' ) . '</p></div>'; } else if ( is_pro_site( $new_bid ) ) { echo '<div id="message" class="error"><p>' . __( 'Could not transfer Pro Status: The chosen site already is a Pro Site. You must remove Pro status and cancel any existing subscriptions tied to that site.', 'psts' ) . '</p></div>'; } else { $current_level = $wpdb->get_row( "SELECT * FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '$current_bid'" ); $new_expire = $current_level->expire - time(); $this->extend( $new_bid, $new_expire, $current_level->gateway, $current_level->level, $current_level->amount ); $wpdb->query( "UPDATE {$wpdb->base_prefix}pro_sites SET term = '{$current_level->term}' WHERE blog_ID = '$new_bid'" ); $this->withdraw( $current_bid ); $this->log_action( $current_bid, sprintf( __( 'Pro Status transferred by %s to BlogID: %d', 'psts' ), $current_user->display_name, $new_bid ) ); $this->log_action( $new_bid, sprintf( __( 'Pro Status transferred by %s from BlogID: %d', 'psts' ), $current_user->display_name, $current_bid ) ); do_action( 'psts_transfer_pro', $current_bid, $new_bid ); //for gateways to hook into for api calls, etc. echo '<div id="message" class="updated fade"><p>' . sprintf( __( 'Pro Status transferred to BlogID: %d', 'psts' ), (int) $_POST['new_bid'] ) . '</p></div>'; } } //remove blog if ( isset( $_POST['psts_modify'] ) ) { check_admin_referer( 'psts_modify' ); //check nonce do_action( 'psts_modify_process', (int) $_POST['bid'] ); if ( isset( $_POST['psts_remove'] ) ) { $this->withdraw( (int) $_POST['bid'] ); echo '<div id="message" class="updated fade"><p>' . __( 'Pro Site Status Removed.', 'psts' ) . '</p></div>'; } if ( isset( $_POST['psts_receipt'] ) ) { $this->email_notification( (int) $_POST['bid'], 'receipt', $_POST['receipt_email'] ); echo '<div id="message" class="updated fade"><p>' . __( 'Email receipt sent.', 'psts' ) . '</p></div>'; } } //check blog_id if ( isset( $_GET['bid'] ) ) { $blog_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->base_prefix}blogs WHERE blog_ID = %d", (int) $_GET['bid'] ) ); if ( ! $blog_count ) { echo '<div id="message" class="updated fade"><p>' . __( 'Invalid blog ID. Please try again.', 'psts' ) . '</p></div>'; $blog_id = false; } else { $blog_id = (int) $_GET['bid']; } } else { $blog_id = false; } $activation_key = false; if ( isset( $_GET['activation_key'] ) ) { $activation_key = $_GET['activation_key']; } ?> <div class="wrap"> <script type="text/javascript"> jQuery(document).ready(function () { jQuery('input.psts_confirm').click(function () { var answer = confirm("<?php _e('Are you sure you really want to do this?', 'psts'); ?>") if (answer) { return true; } else { return false; } ; }); }); </script> <div class="icon32"><img src="<?php echo $this->plugin_url . 'images/modify.png'; ?>"/></div> <h2><?php _e( 'Pro Sites Management', 'psts' ); ?></h2> <?php if( $activation_key ) { $result = ProSites_Helper_Registration::activate_blog( $activation_key ); $blog_id = $result; } if ( $blog_id ) { ?> <h3><?php _e( 'Manage Site', 'psts' ) ?> <?php if ( $name = get_blog_option( $blog_id, 'blogname' ) ) { echo ': ' . $name . ' (Blog ID: ' . $blog_id . ')'; } echo '</h3>'; $levels = (array) get_site_option( 'psts_levels' ); $current_level = $this->get_level( $blog_id ); $expire = $this->get_expire( $blog_id ); $result = $wpdb->get_row( "SELECT * FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '$blog_id'" ); if ( $result ) { if ( $result->term == 1 || $result->term == 3 || $result->term == 12 ) { $term = sprintf( _n( '%s Month','%s Months', $result->term, 'psts' ), $result->term ); } else { $term = $result->term; } } else { $term = 0; } if ( $expire && $expire > time() ) { echo '<p><strong>' . __( 'Current Pro Site', 'psts' ) . '</strong></p>'; echo '<ul>'; if ( $expire > 2147483647 ) { echo '<li>' . __( 'Pro Site privileges will expire: <strong>Never</strong>', 'psts' ) . '</li>'; } else { $trialing = ProSites_Helper_Registration::is_trial( $blog_id ); $active_trial = $trialing ? __( '(Active trial)', 'psts') : ''; echo '<li>' . sprintf( __( 'Pro Site privileges will expire on: <strong>%s</strong>', 'psts' ), date_i18n( get_option( 'date_format' ), $expire ) ) . ' ' . $active_trial . '</li>'; } echo '<li>' . sprintf( __( 'Level: <strong>%s</strong>', 'psts' ), $current_level . ' - ' . @$levels[ $current_level ]['name'] ) . '</li>'; if ( $result->gateway ) { $nicename = ProSites_Helper_Gateway::get_nice_name( $result->gateway ); echo '<li>' . sprintf( __( 'Payment Gateway: <strong>%s</strong>', 'psts' ), $nicename ) . '</li>'; } if ( $term ) { echo '<li>' . sprintf( __( 'Payment Term: <strong>%s</strong>', 'psts' ), $term ) . '</li>'; } echo '</ul>'; } else if ( $expire && $expire <= time() ) { echo '<p><strong>' . __( 'Expired Pro Site', 'psts' ) . '</strong></p>'; echo '<ul>'; echo '<li>' . sprintf( __( 'Pro Site privileges expired on: <strong>%s</strong>', 'psts' ), date_i18n( get_option( 'date_format' ), $expire ) ) . '</li>'; echo '<li>' . sprintf( __( 'Previous Level: <strong>%s</strong>', 'psts' ), $current_level . ' - ' . @$levels[ $current_level ]['name'] ) . '</li>'; if ( $result->gateway ) { $nicename = ProSites_Helper_Gateway::get_nice_name( $result->gateway ); echo '<li>' . sprintf( __( 'Previous Payment Gateway: <strong>%s</strong>', 'psts' ), $nicename ) . '</li>'; } if ( $term ) { echo '<li>' . sprintf( __( 'Previous Payment Term: <strong>%s</strong>', 'psts' ), $term ) . '</li>'; } echo '</ul>'; } else { echo '<p><strong>"' . get_blog_option( $blog_id, 'blogname' ) . '" ' . __( 'has never been a Pro Site.', 'psts' ) . '</strong></p>'; } //meta boxes hooked by gateway plugins if ( has_action( 'psts_subscription_info' ) || has_action( 'psts_subscriber_info' ) ) { ?> <div class="metabox-holder"> <?php if ( has_action( 'psts_subscription_info' ) ) { ?> <div style="width: 49%;" class="postbox-container"> <div class="postbox"> <h3 class="hndle" style="cursor:auto;"> <span><?php _e( 'Subscription Information', 'psts' ); ?></span></h3> <div class="inside"> <?php do_action( 'psts_subscription_info', $blog_id ); ?> </div> </div> </div> <?php } ?> <?php if ( has_action( 'psts_subscriber_info' ) ) { ?> <div style="width: 49%;margin-left: 2%;" class="postbox-container"> <div class="postbox"> <h3 class="hndle" style="cursor:auto;"> <span><?php _e( 'Subscriber Information', 'psts' ); ?></span></h3> <div class="inside"> <?php do_action( 'psts_subscriber_info', $blog_id ); ?> </div> </div> </div> <?php } ?> <div class="clear"></div> </div> <?php } ?> <div id="poststuff" class="metabox-holder"> <div class="postbox"> <h3 class="hndle" style="cursor:auto;"><span><?php _e( 'Account History', 'psts' ) ?></span></h3> <div class="inside"> <span class="description"><?php _e( 'This logs basically every action done in the system regarding the site for an audit trail.', 'psts' ); ?></span> <div style="height:150px;overflow:auto;margin-top:5px;margin-bottom:5px;"> <table class="widefat"> <?php $log = get_blog_option( $blog_id, 'psts_action_log' ); $time_offset = ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ); if ( is_array( $log ) && count( $log ) ) { $log = array_reverse( $log, true ); foreach ( $log as $timestamp => $memo ) { $class = ( isset( $class ) && $class == 'alternate' ) ? '' : 'alternate'; $localtime = $timestamp + $time_offset; echo '<tr class="'.$class.'"><td><strong>' . date_i18n( __('Y-m-d g:i:s a', 'psts'), $localtime ) . '</strong></td><td>' . esc_html($memo) . '</td></tr>'; } } else { echo '<tr><td colspan="2">' . __( 'No history recorded for this site yet.', 'psts' ) . '</td></tr>'; } ?> </table> </div> <form method="post" action=""> <input type="text" placeholder="<?php _e( 'Add a custom log entry...', 'psts' ); ?>" name="log_entry" style="width:91%;"/> <input type="submit" class="button-secondary" name="add_log_entry" value="<?php _e( 'Add »', 'psts' ) ?>" style="width:8%;float:right;"/> </form> </div> </div> </div> <div id="poststuff" class="metabox-holder"> <div style="width: 49%;" class="postbox-container"> <div class="postbox"> <h3 class="hndle" style="cursor:auto;"> <span><?php _e( 'Manually Extend Pro Site Status', 'psts' ) ?></span></h3> <div class="inside"> <span class="description"><?php _e( 'Please note that these changes will not adjust the payment dates or level for any existing subscription.', 'psts' ); ?></span> <form method="post" action=""> <table class="form-table"> <?php wp_nonce_field( 'psts_extend' ) ?> <input type="hidden" name="bid" value="<?php echo $blog_id; ?>"/> <tr valign="top"> <th scope="row"><?php _e( 'Period', 'psts' ) ?></th> <td><select name="extend_months"> <?php for ( $counter = 0; $counter <= 36; $counter += 1 ) { echo '<option value="' . $counter . '">' . $counter . '</option>' . "\n"; } ?> </select><?php _e( 'Months', 'psts' ); ?> <select name="extend_days"> <?php for ( $counter = 0; $counter <= 30; $counter += 1 ) { echo '<option value="' . $counter . '">' . $counter . '</option>' . "\n"; } ?> </select><?php _e( 'Days', 'psts' ); ?> <?php _e( 'or', 'psts' ); ?> <label><input type="checkbox" name="extend_permanent" value="1"/> <?php _e( 'Permanent', 'psts' ); ?> </label> <br/><?php _e( 'Period you wish to extend the site. Leave at zero to only change the level.', 'psts' ); ?> </td> </tr> <tr valign="top"> <th scope="row"><?php _e( 'Level', 'psts' ) ?></th> <td><select name="extend_level"> <?php foreach ( $levels as $level => $value ) { ?> <option value="<?php echo $level; ?>"<?php selected( $current_level, $level ) ?>><?php echo $level . ': ' . esc_attr( $value['name'] ); ?></option><?php } ?> </select> <br/><?php _e( 'Choose what level the site should have access to.', 'psts' ); ?> </td> </tr> <tr valign="top"> <td colspan="2" style="text-align:right;"> <input class="button-primary" type="submit" name="psts_extend" value="<?php _e( 'Extend »', 'psts' ) ?>"/> </td> </tr> </table> <hr/> <table class="form-table"> <tr valign="top"> <td><label>Transfer Pro status to Blog ID: <input type="text" name="new_bid" size="3"/></label></td> <td style="text-align:right;"> <input class="button-primary psts_confirm" type="submit" name="psts_transfer_pro" value="<?php _e( 'Transfer »', 'psts' ) ?>"/> </td> </tr> </table> </form> </div> </div> </div> <?php if ( is_pro_site( $blog_id ) || has_action( 'psts_modify_form' ) ) { ?> <div style="width: 49%;margin-left: 2%;" class="postbox-container"> <div class="postbox"> <h3 class="hndle" style="cursor:auto;"> <span><?php _e( 'Modify Pro Site Status', 'psts' ) ?></span></h3> <div class="inside"> <form method="post" action=""> <?php wp_nonce_field( 'psts_modify' ) ?> <input type="hidden" name="bid" value="<?php echo $blog_id; ?>"/> <?php do_action( 'psts_modify_form', $blog_id ); ?> <?php if ( is_pro_site( $blog_id ) ) { ?> <p> <label><input type="checkbox" name="psts_remove" value="1"/> <?php _e( 'Remove Pro status from this site.', 'psts' ); ?> </label></p> <?php } ?> <?php if ( $last_payment = $this->last_transaction( $blog_id ) ) { ?> <p> <label><input type="checkbox" name="psts_receipt" value="1"/> <?php _e( 'Email a receipt copy for last payment to:', 'psts' ); ?> <input type="text" name="receipt_email" value="<?php echo get_blog_option( $blog_id, 'admin_email' ); ?>"/></label> </p> <?php } ?> <p class="submit"> <input type="submit" name="psts_modify" class="button-primary psts_confirm" value="<?php _e( 'Modify »', 'psts' ) ?>"/> </p> </form> </div> </div> </div> <?php } ?> </div> <?php //show blog_id form } else { ?> <div class="metabox-holder"> <div class="postbox"> <h3 class="hndle" style="cursor:auto;"><span><?php _e( 'Manage a Site', 'psts' ) ?></span></h3> <div class="inside"> <form method="get" action=""> <table class="form-table"> <input type="hidden" name="page" value="psts"/> <tr valign="top"> <th scope="row"><?php _e( 'Blog ID:', 'psts' ) ?></th> <td><input type="text" size="17" name="bid" value=""/> <input class="button-secondary" type="submit" value="<?php _e( 'Continue »', 'psts' ) ?>"/> </td> </tr> </table> </form> <hr /> <form method="get" action=""> <table class="form-table"> <input type="hidden" name="page" value="psts"/> <tr valign="top"> <th scope="row"><?php _e( 'Activation Key:', 'psts' ) ?></th> <td><input type="text" size="17" name="activation_key" value=""/> <input class="button-secondary" type="submit" value="<?php _e( 'Activate Blog »', 'psts' ) ?>"/> </td> </tr> </table> </form> <hr/> <form method="get" action="sites.php" name="searchform"> <table class="form-table"> <tr valign="top"> <th scope="row"><?php _e( 'Or search for a site:<br /><small>By Blog ID, IP address or Path/Domain</small>', 'psts' ) ?></th> <td><input type="text" size="17" value="" name="s"/> <input class="button-secondary" type="submit" value="<?php _e( 'Search Sites »', 'psts' ) ?>" id="submit_sites" name="submit"/> </td> </tr> </table> </form> </div> </div> </div> <?php } echo '</div>'; }
public static function ajax_check_prosite_blog() { global $psts, $current_site; $blog_data = array(); // Add ajax session var ProSites_Helper_Session::session('psts_ajax_session_activated', true); // Introduce a fake error because we don't want to actually create the blog yet. add_filter('registration_errors', array('ProSites_Model_Registration', 'prosite_blog_check_only'), 10, 3); // replace $_POST with array data $params = array(); parse_str($_POST['data'], $params); $period = (int) $_POST['period']; $level = 'free' == $_POST['level'] ? $_POST['level'] : (int) $_POST['level']; $_POST = $params; $doing_ajax = defined('DOING_AJAX') && DOING_AJAX ? true : false; $ajax_response = array(); if ($doing_ajax) { $user_name = sanitize_text_field($_POST['user_name']); $user_email = sanitize_email($_POST['user_email']); $blogname = sanitize_text_field($_POST['blogname']); $blog_title = sanitize_text_field(urldecode($_POST['blog_title'])); // Process some cleaning up if needed do_action('prosite_register_blog_pre_validation', $user_name, $user_email, $blogname); $blog_validation = wpmu_validate_blog_signup($blogname, $blog_title); // Attempt to create a new user (knowing that it will fail, but it should only have our error) if (!isset($_POST['new_blog'])) { $validation = wpmu_validate_user_signup($user_name, $user_email); // nicer errors, but doesn't deal with custom fields $user_check = register_new_user($user_name, $user_email); // checks custom fields, but ugly errors $user_check->errors = array_merge($user_check->errors, $validation['errors']->errors); $user_check->errors = array_merge($user_check->errors, $blog_validation['errors']->errors); } else { $user_check = new WP_Error(); $user_check->errors = array_merge($user_check->errors, $blog_validation['errors']->errors); } // Replaced session vars to make it semi-stateless, will pick these up in a session later $blog_data['new_blog_details'] = array(); $blog_data['new_blog_details']['username'] = $user_name; $blog_data['new_blog_details']['email'] = $user_email; $blog_data['new_blog_details']['blogname'] = $blogname; $blog_data['new_blog_details']['title'] = $blog_title; $blog_data['new_blog_details']['level'] = $level; $blog_data['new_blog_details']['period'] = $period; $username_available = true; $email_available = true; $blogname_available = true; $blogtitle_available = true; // Checking passed... if (!empty($user_check->errors) && 1 == count($user_check->errors) && !isset($_POST['new_blog']) || 0 == count($user_check->errors) && isset($_POST['new_blog'])) { $keys = array_keys($user_check->errors); if ($keys && !in_array('availability_check_only', $keys) && !isset($_POST['new_blog'])) { // Something went wrong! $ajax_response['user_available'] = false; } else { // All good! We're ready to create the user/site /** User is validated using register_new_user so that we can use the hooks and make them available, * but we still need to actually create and activate the signup to get the $user_id. */ $blog = $blog_validation; $domain = $blog['domain']; $path = $blog['path']; $blogname = $blog['blogname']; $blog_title = $blog['blog_title']; $errors = $blog['errors']; // Privacy setting $public = (int) $_POST['blog_public']; $signup_meta = array('lang_id' => 1, 'public' => $public); // Create the signup $meta = apply_filters('add_signup_meta', $signup_meta); $result = ProSites_Helper_Registration::signup_blog($domain, $path, $blog_title, $user_name, $user_email, $meta); $blog_data['activation_key'] = $result['activation_key']; if (isset($result['user_pass']) && !empty($result['user_pass'])) { $blog_data['new_blog_details']['user_pass'] = $result['user_pass']; } $trial_days = $psts->get_setting('trial_days', 0); $trial_active = !empty($trial_days); $site_name = ''; if (!is_subdomain_install()) { $site_name = $current_site->domain . $current_site->path . $blogname; } else { $site_name = $blogname . '.' . ($site_domain = preg_replace('|^www\\.|', '', $current_site->domain)); } if ($trial_active) { $recurring = $psts->get_setting('recurring_subscriptions', 1); if ($recurring) { $blog_data['new_blog_details']['reserved_message'] = sprintf('<div class="reserved_msg"><h2>' . __('Activate your site', 'psts') . '</h2>' . __('<p>Your site <strong>(%s)</strong> has been reserved but is not yet activated.</p><p>Once payment information has been verified your trial period will begin. When your trial ends you will be automatically upgraded to your chosen plan. Your reservation only last for 48 hours upon which your site name will become available again.</p><p>Please use the form below to setup your payment information.</p>', 'psts') . '</div>', $site_name); } else { // Non-recurring sites really should not do anything at checkout other than activate. $result = ProSites_Helper_Registration::activate_blog($blog_data, true, $period, $level); $blog_id = $result['blog_id']; if (isset($result['password'])) { $blog_data['new_blog_details']['user_pass'] = $result['password']; } ProSites_Helper_Registration::set_trial($blog_id, 1); //Update Activation Key for blog ProSites_Helper_Registration::update_activation_key($blog_id, $blog_data['activation_key']); $psts->record_stat($blog_id, 'signup'); $ajax_response['show_finish'] = true; $ajax_response['finish_content'] = ProSites_View_Front_Gateway::render_payment_submitted($blog_data, true); } } else { $blog_data['new_blog_details']['reserved_message'] = sprintf('<div class="reserved_msg"><h2>' . __('Activate your site', 'psts') . '</h2>' . __('<p>Your site <strong>(%s)</strong> has been reserved but is not yet activated.</p><p>Once payment has been processed your site will become active with your chosen plan. Your reservation only last for 48 hours upon which your site name will become available again.</p><p>Please use the form below to setup your payment information.</p>', 'psts') . '</div>', $site_name); } // FREE basic site if ('free' == $blog_data['new_blog_details']['level']) { if (isset($blog_data['new_blog_details']['reserved_message'])) { unset($blog_data['new_blog_details']['reserved_message']); } $result = ProSites_Helper_Registration::activate_blog($blog_data, false, false, false); $blog_data['new_blog_details']['blog_id'] = $result['blog_id']; if (isset($result['password'])) { $blog_data['new_blog_details']['user_pass'] = $result['password']; } $ajax_response['show_finish'] = true; $ajax_response['finish_content'] = ProSites_View_Front_Gateway::render_free_confirmation($blog_data); } if (isset($blog_data['new_blog_details']['reserved_message'])) { $ajax_response['reserved_message'] = $blog_data['new_blog_details']['reserved_message']; } } // If WP 4.0+ and user is logged in it will use WP_Session_Tokens, else $_SESSION ProSites_Helper_Session::session('new_blog_details', $blog_data['new_blog_details']); ProSites_Helper_Session::session('activation_key', $blog_data['activation_key']); $ajax_response['gateways_form'] = ProSites_View_Front_Gateway::render_checkout($blog_data); } else { // We had registration errors, redraw the form displaying errors if (!empty($user_check) && isset($user_check->errors)) { $ajax_response['form'] = ProSites_View_Front_Registration::render_signup_form($blog_data, $user_check); $ajax_response['user_available'] = false; } // Isolate which standard fields are valid $error_keys = array_keys($user_check->errors); foreach ($error_keys as $key) { if (preg_match('/username|user_name/', $key)) { $username_available = false; } if (preg_match('/email/', $key)) { $email_available = false; } if (preg_match('/blogname/', $key)) { $blogname_available = false; } if (preg_match('/blog_title/', $key)) { $blogtitle_available = false; } } } $ajax_response['username_available'] = $username_available; $ajax_response['email_available'] = $email_available; $ajax_response['blogname_available'] = $blogname_available; $ajax_response['blog_title_available'] = $blogtitle_available; $response = array('what' => 'response', 'action' => 'check_prosite_blog', 'id' => 1, 'data' => json_encode($ajax_response)); // No longer need ajax session ProSites_Helper_Session::unset_session('psts_ajax_session_activated'); // Buffer used to isolate AJAX response from unexpected output @ob_end_clean(); ob_start(); $xmlResponse = new WP_Ajax_Response($response); $xmlResponse->send(); ob_end_flush(); } }