/**
     * Returns the contens of the dialog
     *
     * @since  1.0.0
     *
     * @return object
     */
    public function get_contents($data)
    {
        $subscription = $data['model'];
        $gateways = MS_Model_Gateway::get_gateway_names(false, true);
        if (isset($gateways[$subscription->gateway_id])) {
            $gateway = $gateways[$subscription->gateway_id];
        } elseif (empty($subscription->gateway_id)) {
            $gateway = __('- No Gateway -', 'membership2');
        } else {
            $gateway = '(' . $subscription->gateway_id . ')';
        }
        $events = MS_Model_Event::get_events(array('topic' => 'membership', 'nopaging' => true, 'relationship_id' => $subscription->id));
        $sub_details = array('title' => __('Subscription Details', 'membership2'), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(array('Subscription ID', $subscription->id), array('Membership', $subscription->get_membership()->name), array('Payment Gateway', $gateway), array('Payment Type', $subscription->get_payment_description(null, true)), array('Subscription Start', $subscription->start_date), array('Subscription End', $subscription->expire_date), array('Status', $subscription->status)), 'field_options' => array('head_col' => true));
        $evt_details = array();
        foreach ($events as $event) {
            $evt_details[] = array('title' => __('Event Details', 'membership2'), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(array('Event ID', $event->id), array('Date', $event->date), array('Description', $event->description)), 'field_options' => array('head_col' => true));
        }
        ob_start();
        ?>
		<div>
			<?php 
        MS_Helper_Html::html_element($sub_details);
        MS_Helper_Html::html_separator();
        foreach ($evt_details as $detail) {
            MS_Helper_Html::html_element($detail);
        }
        ?>
		</div>
		<?php 
        $html = ob_get_clean();
        return apply_filters('ms_view_member_subscription_to_html', $html);
    }
 /**
  * Load and get all registered gateways.
  *
  * @since  1.0.0
  * @param bool $only_active Optional. When to return only activated gateways.
  */
 public static function get_gateways($only_active = false)
 {
     static $Done = false;
     $res = null;
     if (!$Done) {
         self::$_gateways = array();
         $gateways = array();
         $Done = true;
         self::load_core_gateways();
         /**
          * Register new gateways.
          *
          * @since  1.0.0
          */
         $gateways = apply_filters('ms_model_gateway_register', $gateways);
         foreach ($gateways as $key => $class) {
             self::$_gateways[$key] = MS_Factory::load($class);
         }
     }
     $res = self::$_gateways;
     if ($only_active) {
         foreach ($res as $id => $gateway) {
             if (!$gateway->active) {
                 unset($res[$id]);
             }
         }
     }
     return apply_filters('ms_model_gateway_get_gateways', $res, $only_active);
 }
    /**
     * Returns the contens of the dialog
     *
     * @since  1.0.0
     *
     * @return object
     */
    public function get_contents($data)
    {
        $subscription = $data['model'];
        $gateways = MS_Model_Gateway::get_gateway_names();
        $invoices = $subscription->get_invoices();
        $pay_details = array();
        $inv_details = array();
        foreach ($subscription->get_payments() as $payment) {
            if (isset($gateways[$payment['gateway']])) {
                $gateway = $gateways[$payment['gateway']];
            } else {
                $gateway = '(' . $payment['gateway'] . ')';
            }
            $pay_details[] = array('title' => __('Recorded Payment', 'membership2'), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(0 => array('Payment Date', $payment['date']), 1 => array('Payment Gateway', $gateway), 2 => array('Amount', $payment['amount']), 3 => array('External ID', $payment['external_id'])), 'field_options' => array('head_col' => true));
        }
        $invoice_list = array();
        foreach ($invoices as $invoice) {
            if (isset($gateways[$invoice->gateway_id])) {
                $gateway = $gateways[$invoice->gateway_id];
            } else {
                $gateway = '(' . $invoice->gateway_id . ')';
            }
            $transaction_log = sprintf(' <small>- <a href="%s" target="_blank">%s</a></small>', MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs', 'invoice' => $invoice->id)), __('Show Transaction', 'membership2'));
            $invoice_list[] = $invoice->id;
            $inv_details[$invoice->id] = array('title' => sprintf(__('Invoice %s', 'membership2'), $invoice->id), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(0 => array('Invoice ID', $invoice->id . $transaction_log), 2 => array('Create Date', $invoice->invoice_date), 1 => array('Payment Gateway', $gateway), 2 => array('Due Date', $invoice->due_date), 3 => array('Regular amount', $invoice->amount), 4 => array('Total billed', $invoice->total), 5 => array('Status', $invoice->status), 6 => array('Notes', $invoice->description), 7 => array('Checkout IP', $invoice->checkout_ip), 8 => array('Checkout Date', $invoice->checkout_date)), 'field_options' => array('head_col' => true));
            if ($invoice->amount == $invoice->total) {
                unset($inv_details[$invoice->id]['value'][3]);
                $inv_details[$invoice->id]['value'] = array_values($inv_details[$invoice->id]['value']);
            }
        }
        $transaction_url = MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs', 'invoice' => implode(',', $invoice_list)));
        $transaction_log = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'value' => __('Show all Transactions for this subscription', 'membership2'), 'url' => $transaction_url, 'target' => '_blank');
        ob_start();
        ?>
		<div class="wpmui-grid-8 ms-payment-infos">
			<div class="col-5">
				<?php 
        foreach ($inv_details as $detail) {
            MS_Helper_Html::html_element($detail);
        }
        ?>
			</div>
			<div class="col-3">
				<?php 
        MS_Helper_Html::html_element($transaction_log);
        MS_Helper_Html::html_separator();
        foreach ($pay_details as $detail) {
            MS_Helper_Html::html_element($detail);
        }
        ?>
			</div>
		</div>
		<?php 
        $html = ob_get_clean();
        return apply_filters('ms_view_member_payment_to_html', $html);
    }
 /**
  * Tests the Stripe Subscription gateway
  * @test
  */
 function stripeplan_subscription()
 {
     $gateway = MS_Model_Gateway::factory(MS_Gateway_Stripeplan::ID);
     $user_id = TData::id('user', 'editor');
     $membership_id = TData::id('membership', 'recurring');
     $subscription = TData::subscribe($user_id, $membership_id);
     $controller = MS_Factory::load('MS_Controller_Gateway');
     $gateway->update_stripe_data();
     $data = array('card' => array('number' => '4242424242424242', 'exp_month' => 12, 'exp_year' => date('Y') + 1, 'cvc' => '314'));
     $res = M2_Stripe_Token::create($data);
     $token = $res->id;
     $form_data = array('_wpnonce' => wp_create_nonce($gateway->id . '_' . $subscription->id), 'gateway' => $gateway->id, 'ms_relationship_id' => $subscription->id, 'step' => 'process_purchase', 'stripeToken' => $token, 'stripeTokenType' => 'card', 'stripeEmail' => '*****@*****.**');
     $_POST = $form_data;
     $_REQUEST = $_POST;
     // Right now the subscription must have status PENDING
     $this->assertEquals(MS_Model_Relationship::STATUS_PENDING, $subscription->status);
     /*
      * This function processes the purchase and will set the subscription
      * to active.
      */
     $controller->process_purchase();
     // Check the subscription status.
     $this->assertEquals(MS_Model_Relationship::STATUS_ACTIVE, $subscription->status);
     $this->assertEquals(1, count($subscription->payments));
     // Modify the expiration date to trigger another payment.
     $today = date('Y-m-d');
     $subscription->expire_date = $today;
     $this->assertEquals($today, $subscription->expire_date);
     $this->assertEquals(0, $subscription->get_remaining_period());
     // Trigger next payment and validate it.
     $subscription->check_membership_status();
     $this->assertEquals(2, count($subscription->payments));
     // Modify the expiration date to trigger another payment.
     $subscription->expire_date = $today;
     $this->assertEquals($today, $subscription->expire_date);
     $this->assertEquals(0, $subscription->get_remaining_period());
     // Trigger next payment and validate it.
     // THIS TIME NO PAYMENT SHOULD BE MADE because paycycle_repetitions = 2!
     $subscription->check_membership_status();
     $this->assertEquals(2, count($subscription->payments));
     // Also the subscription should be cancelled at stripe now.
     $customer_id = $subscription->get_member()->get_gateway_profile(MS_Gateway_Stripe_Api::ID, 'customer_id');
     $customer = M2_Stripe_Customer::retrieve($customer_id);
     $invoice = $subscription->get_previous_invoice();
     $stripe_sub_id = $invoice->external_id;
     $stripe_sub = $customer->subscriptions->retrieve($stripe_sub_id);
     $this->assertEquals('active', $stripe_sub->status);
     $this->assertTrue($stripe_sub->cancel_at_period_end);
     // Clean up.
     $customer->delete();
 }
    /**
     * Returns the contens of the dialog
     *
     * @since  1.0.0
     *
     * @return object
     */
    public function get_contents($data)
    {
        $subscription = $data['model'];
        $gateways = MS_Model_Gateway::get_gateway_names();
        $invoices = $subscription->get_invoices();
        $pay_details = array();
        $inv_details = array();
        foreach ($subscription->payments as $payment) {
            if (isset($gateways[$payment['gateway']])) {
                $gateway = $gateways[$payment['gateway']];
            } else {
                $gateway = '(' . $payment['gateway'] . ')';
            }
            $pay_details[] = array('title' => __('Recorded Payment', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(0 => array('Payment Date', $payment['date']), 1 => array('Payment Gateway', $gateway), 2 => array('Amount', $payment['amount'])), 'field_options' => array('head_col' => true));
        }
        if (!empty($pay_details)) {
            $pay_details[] = array('type' => MS_Helper_Html::TYPE_HTML_SEPARATOR);
        }
        foreach ($invoices as $invoice) {
            if (isset($gateways[$invoice->gateway_id])) {
                $gateway = $gateways[$invoice->gateway_id];
            } else {
                $gateway = '(' . $invoice->gateway_id . ')';
            }
            $inv_details[$invoice->id] = array('title' => sprintf(__('Invoice %s', MS_TEXT_DOMAIN), $invoice->id), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(0 => array('Invoice ID', $invoice->id), 1 => array('Payment Gateway', $gateway), 2 => array('Due Date', $invoice->due_date), 3 => array('Regular amount', $invoice->amount), 4 => array('Total billed', $invoice->total), 5 => array('Status', $invoice->status), 6 => array('Notes', $invoice->description)), 'field_options' => array('head_col' => true));
            if ($invoice->amount == $invoice->total) {
                unset($inv_details[$invoice->id]['value'][3]);
                $inv_details[$invoice->id]['value'] = array_values($inv_details[$invoice->id]['value']);
            }
        }
        ob_start();
        ?>
		<div>
			<?php 
        foreach ($pay_details as $detail) {
            MS_Helper_Html::html_element($detail);
        }
        foreach ($inv_details as $detail) {
            MS_Helper_Html::html_element($detail);
        }
        ?>
		</div>
		<?php 
        $html = ob_get_clean();
        return apply_filters('ms_view_member_payment_to_html', $html);
    }
 /**
  * Prepare html fields.
  *
  * @since  1.0.1.0
  *
  * @return array
  */
 function prepare_fields()
 {
     $member = $this->data['member'];
     $userlist = $this->data['users'];
     $log = $this->data['log'];
     $data_action = MS_Controller_Billing::AJAX_ACTION_TRANSACTION_LINK_DATA;
     $update_action = MS_Controller_Billing::AJAX_ACTION_TRANSACTION_UPDATE;
     $fields = array();
     $member_id = 0;
     if ($member && $member->id) {
         $member_id = $member->id;
     }
     $fields['info'] = array('id' => array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'title' => __('Transaction ID', MS_TEXT_DOMAIN), 'value' => $log->id), 'gateway' => array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'title' => __('Payment Gateway', MS_TEXT_DOMAIN), 'value' => MS_Model_Gateway::get_name($log->gateway_id, true)), 'amount' => array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'title' => __('Transaction Amount', MS_TEXT_DOMAIN), 'value' => MS_Helper_Billing::format_price($log->amount)), 'details' => array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'title' => __('Transaction Details', MS_TEXT_DOMAIN), 'value' => $log->description), 'sep' => array('type' => MS_Helper_Html::TYPE_HTML_SEPARATOR, 'value' => 'vertical'));
     $fields['member'] = array('user_id' => array('id' => 'user_id', 'title' => __('1. Payment by user', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $member_id, 'field_options' => $userlist));
     $fields['subscription'] = array('subscription_id' => array('id' => 'subscription_id', 'title' => __('2. Payment for subscription', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => 0, 'field_options' => array()));
     $fields['invoice'] = array('invoice_id' => array('id' => 'invoice_id', 'title' => __('3. Link payment with invoice', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => 0, 'field_options' => array(), 'after' => __('The selected Invoice will be marked as "paid"', MS_TEXT_DOMAIN)));
     $fields['buttons'] = array('nonce_link_data' => array('id' => 'nonce_link_data', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => wp_create_nonce($data_action)), 'nonce_update' => array('id' => 'nonce_update', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => wp_create_nonce($update_action)), 'log_id' => array('id' => 'log_id', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $log->id), 'cancel' => array('id' => 'cancel', 'type' => MS_Helper_Html::INPUT_TYPE_BUTTON, 'value' => __('Cancel', MS_TEXT_DOMAIN), 'class' => 'wpmui-field-button button close'), 'submit' => array('id' => 'submit', 'type' => MS_Helper_Html::INPUT_TYPE_SUBMIT, 'value' => __('Save Transaction', MS_TEXT_DOMAIN)));
     return apply_filters('ms_view_billing_link_prepare_fields', $fields, $this);
 }
 /**
  * Input fields displayed in the "Edit Member" screen.
  *
  * @since  1.0.1.0
  * @return array
  */
 public function prepare_fields_edit()
 {
     $action_update = MS_Controller_Member::ACTION_UPDATE_MEMBER;
     $action_modify = MS_Controller_Member::ACTION_MODIFY_SUBSCRIPTIONS;
     $user_id = $this->data['user_id'];
     $user = MS_Factory::load('MS_Model_Member', $user_id);
     $unused_memberships = array();
     $temp_memberships = MS_Model_Membership::get_memberships(array('include_guest' => 0));
     foreach ($temp_memberships as $membership) {
         $unused_memberships[$membership->id] = $membership;
     }
     $fields = array();
     $fields['editor'] = array('title' => array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'class' => 'group-title', 'value' => __('Basic Profile details', MS_TEXT_DOMAIN)), 'username' => array('id' => 'username', 'type' => MS_Helper_Html::INPUT_TYPE_TEXT, 'title' => __('Username', MS_TEXT_DOMAIN), 'value' => $user->username, 'class' => 'ms-text-medium', 'config' => array('disabled' => 'disabled')), 'email' => array('id' => 'email', 'type' => MS_Helper_Html::INPUT_TYPE_TEXT, 'title' => __('Email', MS_TEXT_DOMAIN), 'value' => $user->email, 'class' => 'ms-text-medium'), 'first_name' => array('id' => 'first_name', 'type' => MS_Helper_Html::INPUT_TYPE_TEXT, 'title' => __('First Name', MS_TEXT_DOMAIN), 'value' => $user->first_name, 'class' => 'ms-text-medium'), 'last_name' => array('id' => 'last_name', 'type' => MS_Helper_Html::INPUT_TYPE_TEXT, 'title' => __('Last Name', MS_TEXT_DOMAIN), 'value' => $user->last_name, 'class' => 'ms-text-medium'), 'displayname' => array('id' => 'displayname', 'type' => MS_Helper_Html::INPUT_TYPE_TEXT, 'title' => __('Display Name', MS_TEXT_DOMAIN), 'value' => $user->get_user()->display_name, 'class' => 'ms-text-medium'), 'sep' => array('type' => MS_Helper_Html::TYPE_HTML_SEPARATOR), 'user_id' => array('id' => 'user_id', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $user->id), 'button' => array('id' => 'btn_save', 'type' => MS_Helper_Html::INPUT_TYPE_SUBMIT, 'value' => __('Save', MS_TEXT_DOMAIN)), 'profile' => array('id' => 'user_profile', 'type' => MS_Helper_Html::TYPE_HTML_LINK, 'value' => __('Full User Profile', MS_TEXT_DOMAIN) . ' &raquo;', 'url' => admin_url('user-edit.php?user_id=' . $user->id), 'class' => 'button wpmui-field-input'), 'action' => array('id' => 'action', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $action_update), '_wpnonce' => array('id' => '_wpnonce', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => wp_create_nonce($action_update)));
     $fields['subscriptions'] = array();
     // Section: Edit existing subscriptions.
     $fields['subscriptions'][] = array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'class' => 'group-title', 'value' => __('Manage Subscriptions', MS_TEXT_DOMAIN));
     if ($user->subscriptions) {
         $gateways = MS_Model_Gateway::get_gateway_names(false, true);
         foreach ($user->subscriptions as $subscription) {
             if (MS_Model_Relationship::STATUS_DEACTIVATED == $subscription->status) {
                 continue;
             }
             $the_membership = $subscription->get_membership();
             unset($unused_memberships[$the_membership->id]);
             $status_options = array(MS_Model_Relationship::STATUS_PENDING => __('Pending (activate on next payment)', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_WAITING => __('Waiting (activate on start date)', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_TRIAL => __('Trial Active', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_ACTIVE => __('Active', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_CANCELED => __('Cancelled (deactivate on expire date)', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_TRIAL_EXPIRED => __('Trial Expired (activate on next payment)', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_EXPIRED => __('Expired (no access) ', MS_TEXT_DOMAIN), MS_Model_Relationship::STATUS_DEACTIVATED => __('Deactivated (no access)', MS_TEXT_DOMAIN));
             if (!$the_membership->has_trial()) {
                 unset($status_options[MS_Model_Relationship::STATUS_TRIAL]);
                 unset($status_options[MS_Model_Relationship::STATUS_TRIAL_EXPIRED]);
             }
             if (isset($gateways[$subscription->gateway_id])) {
                 $gateway_name = $gateways[$subscription->gateway_id];
             } elseif (empty($subscription->gateway_id)) {
                 $gateway_name = __('- No Gateway -', MS_TEXT_DOMAIN);
             } else {
                 $gateway_name = '(' . $subscription->gateway_id . ')';
             }
             $field_start = array('name' => 'mem_' . $the_membership->id . '[start]', 'type' => MS_Helper_Html::INPUT_TYPE_DATEPICKER, 'value' => $subscription->start_date);
             $field_expire = array('name' => 'mem_' . $the_membership->id . '[expire]', 'type' => MS_Helper_Html::INPUT_TYPE_DATEPICKER, 'value' => $subscription->expire_date);
             $field_status = array('name' => 'mem_' . $the_membership->id . '[status]', 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $subscription->status, 'field_options' => $status_options);
             $fields['subscriptions'][] = array('name' => 'memberships[]', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $the_membership->id);
             $fields['subscriptions'][] = array('title' => $the_membership->get_name_tag(), 'type' => MS_Helper_Html::TYPE_HTML_TABLE, 'value' => array(array(__('Subscription ID', MS_TEXT_DOMAIN), $subscription->id), array(__('Payment Gateway', MS_TEXT_DOMAIN), $gateway_name), array(__('Payment Type', MS_TEXT_DOMAIN), $subscription->get_payment_description(null, true)), array(__('Start Date', MS_TEXT_DOMAIN) . ' <sup>*)</sup>', MS_Helper_Html::html_element($field_start, true)), array(__('Expire Date', MS_TEXT_DOMAIN) . ' <sup>*)</sup>', MS_Helper_Html::html_element($field_expire, true)), array(__('Status', MS_TEXT_DOMAIN) . ' <sup>*)</sup>', MS_Helper_Html::html_element($field_status, true))), 'field_options' => array('head_col' => true));
         }
     } else {
         $fields['subscriptions'][] = array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'value' => __('This user does not have any subscriptions yet.', MS_TEXT_DOMAIN));
     }
     // Section: Add new subscription.
     if (count($unused_memberships)) {
         $options = array();
         if (MS_Model_Addon::is_enabled(MS_Model_Addon::ADDON_MULTI_MEMBERSHIPS)) {
             $field_type = MS_Helper_Html::INPUT_TYPE_CHECKBOX;
             $group_title = __('Add Subscriptions', MS_TEXT_DOMAIN);
         } else {
             $field_type = MS_Helper_Html::INPUT_TYPE_RADIO;
             $group_title = __('Set Subscription', MS_TEXT_DOMAIN);
         }
         $fields['subscriptions'][] = array('type' => MS_Helper_Html::TYPE_HTML_SEPARATOR);
         $fields['subscriptions'][] = array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'class' => 'group-title', 'value' => $group_title);
         foreach ($unused_memberships as $the_membership) {
             $options[$the_membership->id] = $the_membership->get_name_tag();
         }
         $fields['subscriptions'][] = array('id' => 'subscribe', 'type' => $field_type, 'field_options' => $options);
         $fields['subscriptions'][] = array('id' => 'user_id', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $user->id);
     }
     if ($user->subscriptions) {
         $fields['subscriptions'][] = array('type' => MS_Helper_Html::TYPE_HTML_SEPARATOR);
         $fields['subscriptions'][] = array('type' => MS_Helper_Html::TYPE_HTML_TEXT, 'value' => '<sup>*)</sup> ' . __('Subscription Dates and Status are validated when saved and might result in a different value then the one specified above.', MS_TEXT_DOMAIN), 'class' => 'info-field');
     }
     $fields['subscriptions'][] = array('id' => 'btn_modify', 'type' => MS_Helper_Html::INPUT_TYPE_SUBMIT, 'value' => __('Save Changes', MS_TEXT_DOMAIN));
     $fields['subscriptions'][] = array('id' => 'history', 'type' => MS_Helper_Html::TYPE_HTML_LINK, 'value' => '<i class="dashicons dashicons-id"></i>' . __('History and logs', MS_TEXT_DOMAIN), 'url' => '#history', 'class' => 'button wpmui-field-input', 'config' => array('data-ms-dialog' => 'View_Member_Dialog', 'data-ms-data' => array('member_id' => $user->id)));
     $fields['subscriptions'][] = array('id' => 'action', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $action_modify);
     $fields['subscriptions'][] = array('id' => '_wpnonce', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => wp_create_nonce($action_modify));
     return apply_filters('ms_view_member_editor_fields_edit', $fields);
 }
 /**
  * Completely whipe all Membership data from Database.
  *
  * Note: This function is not used currently...
  *
  * @since  1.0.0
  */
 private static function cleanup_db()
 {
     global $wpdb;
     $sql = array();
     $trash_ids = array();
     // Delete membership meta-data from users.
     $users = MS_Model_Member::get_members();
     foreach ($users as $user) {
         $user->delete_all_membership_usermeta();
         $user->save();
     }
     // Determine IDs of Membership Pages.
     $page_types = MS_Model_Pages::get_page_types();
     foreach ($page_types as $type => $name) {
         $page_id = MS_Model_Pages::get_setting($type);
         $trash_ids[] = $page_id;
     }
     /**
      * Delete all plugin settings.
      * Settings are saved by classes that extend MS_Model_option
      */
     foreach (MS_Model_Gateway::get_gateways() as $option) {
         $option->delete();
     }
     MS_Factory::load('MS_Model_Addon')->delete();
     MS_Factory::load('MS_Model_Pages')->delete();
     MS_Factory::load('MS_Model_Settings')->delete();
     /**
      * Delete transient data
      * Transient data is saved by classed that extend MS_Model_Transient
      */
     MS_Factory::load('MS_Model_Simulate')->delete();
     /**
      * Delete all plugin content.
      * Content is saved by classes that extend MS_Model_CustomPostType
      */
     $ms_posttypes = array(MS_Model_Communication::get_post_type(), MS_Model_Event::get_post_type(), MS_Model_Invoice::get_post_type(), MS_Model_Transactionlog::get_post_type(), MS_Model_Membership::get_post_type(), MS_Model_Relationship::get_post_type(), MS_Addon_Coupon_Model::get_post_type(), MS_Addon_Invitation_Model::get_post_type());
     foreach ($ms_posttypes as $type) {
         $sql[] = $wpdb->prepare("DELETE FROM {$wpdb->posts} WHERE post_type = %s;", $type);
     }
     // Remove orphaned post-metadata.
     $sql[] = "\n\t\tDELETE FROM {$wpdb->postmeta}\n\t\tWHERE NOT EXISTS (\n\t\t\tSELECT 1 FROM {$wpdb->posts} tmp WHERE tmp.ID = post_id\n\t\t);\n\t\t";
     // Clear all WP transient cache.
     $sql[] = "\n\t\tDELETE FROM {$wpdb->options}\n\t\tWHERE option_name LIKE '_transient_%';\n\t\t";
     foreach ($sql as $s) {
         $wpdb->query($s);
     }
     // Move Membership pages to trash.
     foreach ($trash_ids as $id) {
         wp_delete_post($id, true);
     }
     // Clear all data from WP Object cache.
     wp_cache_flush();
     // Redirect to the main page.
     wp_safe_redirect(MS_Controller_Plugin::get_admin_url());
     exit;
 }
 /**
  * Get related gateway model.
  *
  * @since  1.0.0
  * @api
  *
  * @return MS_Model_Gateway
  */
 public function get_gateway()
 {
     $gateway = MS_Model_Gateway::factory($this->gateway_id);
     return apply_filters('ms_model_relationship_get_gateway', $gateway);
 }
    /**
     * Renders Authorize.net CIM profiles.
     *
     * @since  1.0.0
     *
     * @access protected
     */
    protected function render_cim_profiles($fields)
    {
        // if profile is empty, then return
        if (empty($this->data['cim_profiles'])) {
            return;
        }
        $gateway = MS_Model_Gateway::factory(MS_Gateway_Authorize::ID);
        $cim_profiles = $this->data['cim_profiles'];
        // if we have one record in profile, then wrap it into array to make it
        // compatible with case when we have more then one payment methods added
        if (isset($cim_profiles['billTo'])) {
            $cim_profiles = array($cim_profiles);
        }
        $first_key = null;
        foreach ($cim_profiles as $index => $profile) {
            if (is_array($profile) && !empty($profile['customerPaymentProfileId'])) {
                $options[$profile['customerPaymentProfileId']] = esc_html(sprintf("%s %s's - **** **** **** %s ", $profile['billTo']['firstName'], $profile['billTo']['lastName'], str_replace('XXXX', '', $profile['payment']['creditCard']['cardNumber'])));
                if (!$first_key) {
                    $first_key = $profile['customerPaymentProfileId'];
                }
            }
        }
        $options[0] = __('Enter a new credit card', 'membership2');
        $cim = array('id' => 'profile', 'type' => MS_Helper_Html::INPUT_TYPE_RADIO, 'field_options' => $options, 'value' => $first_key);
        if ($this->data['cim_payment_profile_id']) {
            $cim['value'] = $this->data['cim_payment_profile_id'];
        }
        $card_cvc = array('id' => 'card_code', 'title' => __('Enter the credit cards CVC code to verify the payment', 'membership2'), 'type' => MS_Helper_Html::INPUT_TYPE_TEXT, 'placeholder' => 'CVC', 'maxlength' => 4);
        ?>
		<form id="ms-authorize-extra-form" method="post" class="ms-form">
			<?php 
        foreach ($fields['hidden'] as $field) {
            ?>
				<?php 
            MS_Helper_Html::html_element($field);
            ?>
			<?php 
        }
        ?>

			<div id="ms-authorize-cim-profiles-wrapper" class="authorize-form-block">
				<table>
					<tr>
						<td class="ms-title-row"><?php 
        _e('Stored Credit Cards', 'membership2');
        ?>
</td>
					</tr>
					<tr>
						<td class="ms-col-cim_profiles">
						<?php 
        MS_Helper_Html::html_element($cim);
        ?>
						</td>
					</tr>
					<?php 
        if (lib3()->is_true($gateway->secure_cc)) {
            ?>
					<tr class="ms-row-card_cvc">
						<td>
						<?php 
            MS_Helper_Html::html_element($card_cvc);
            ?>
						</td>
					</tr>
					<?php 
        }
        ?>
					<tr class="ms-row-submit">
						<td class="ms-col-submit">
							<?php 
        MS_Helper_Html::html_element($fields['submit']);
        ?>
						</td>
					</tr>
				</table>
			</div>
		</form>
		<?php 
    }
Example #11
0
 /**
  * Resets the database.
  *
  * @since  1.0.0
  */
 public static function reset()
 {
     global $wpdb;
     // wipe all existing data.
     $wpdb->query("TRUNCATE TABLE {$wpdb->users};");
     $wpdb->query("TRUNCATE TABLE {$wpdb->usermeta};");
     $wpdb->query("TRUNCATE TABLE {$wpdb->posts};");
     $wpdb->query("TRUNCATE TABLE {$wpdb->postmeta};");
     $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '%transient_%';");
     $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'MS_%';");
     self::$ids = array('user' => array(), 'post' => array(), 'membership' => array());
     // create demo users
     $users = array('admin' => array('role' => 'administrator'), 'editor' => array('role' => 'editor'));
     foreach ($users as $login => $data) {
         $defaults = array('user_login' => $login, 'user_pass' => $login . '-password', 'user_email' => $login . '@local.dev', 'role' => 'subscriber', 'user_nicename' => '', 'user_url' => '', 'display_name' => 'User ' . $login, 'nickname' => '', 'first_name' => '', 'last_name' => '', 'description' => '', 'user_registered' => '');
         $data = shortcode_atts($defaults, $data);
         $id = wp_insert_user($data);
         if (!empty($data['meta'])) {
             foreach ($data['meta'] as $key => $val) {
                 $val = maybe_serialize($val);
                 update_user_meta($id, $key, $val);
             }
         }
         self::$ids['user'][$login] = $id;
     }
     // create demo posts
     $posts = array('sample-post' => array('post_content' => 'Just a very simple sample post...'), 'sample-page' => array('post_type' => 'page', 'post_content' => 'Just a very simple sample page...'));
     foreach ($posts as $slug => $data) {
         $defaults = array('post_type' => 'post', 'post_author' => self::id('user', 'admin'), 'post_title' => $slug, 'post_name' => $slug);
         $data = shortcode_atts($defaults, $data);
         $id = wp_insert_post($data);
         if (!empty($data['meta'])) {
             foreach ($data['meta'] as $key => $val) {
                 $val = maybe_serialize($val);
                 update_post_meta($id, $key, $val);
             }
         }
         self::$ids['post'][$slug] = $id;
     }
     // create demo memberships
     $memberships = array('simple' => array('name' => 'Simple Membership', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_PERMANENT, 'price' => 29, 'rule_values' => array()), 'simple-free' => array('name' => 'Simple Membership', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_PERMANENT, 'is_free' => true, 'price' => 0, 'rule_values' => array()), 'simple-trial' => array('name' => 'Simple Membership with Trial', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_PERMANENT, 'price' => 29, 'rule_values' => array(), 'trial_period_enabled' => true, 'trial_period' => array('period_unit' => 14, 'period_type' => 'days')), 'limited' => array('name' => 'Limited Membership', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_FINITE, 'price' => 19, 'rule_values' => array(), 'period' => array('period_unit' => 28, 'period_type' => 'days')), 'limited-trial' => array('name' => 'Limited Membership with Trial', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_FINITE, 'price' => 19, 'rule_values' => array(), 'period' => array('period_unit' => 28, 'period_type' => 'days'), 'trial_period_enabled' => true, 'trial_period' => array('period_unit' => 14, 'period_type' => 'days')), 'daterange-trial' => array('name' => 'Date-Range Membership with Trial', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_DATE_RANGE, 'price' => 39, 'rule_values' => array(), 'period_date_start' => date('Y-m-d', time() + self::ONE_DAY), 'period_date_end' => date('Y-m-d', time() + 10 * self::ONE_DAY), 'trial_period_enabled' => true, 'trial_period' => array('period_unit' => 14, 'period_type' => 'days')), 'free-limited' => array('name' => 'Free Limited Membership', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_FINITE, 'is_free' => true, 'price' => 0, 'rule_values' => array(), 'period' => array('period_unit' => 28, 'period_type' => 'days')), 'recurring' => array('name' => 'Unit-Test Recurring', 'type' => MS_Model_Membership::TYPE_STANDARD, 'payment_type' => MS_Model_Membership::PAYMENT_TYPE_RECURRING, 'is_free' => false, 'price' => 4, 'rule_values' => array(), 'pay_cycle_period' => array('period_unit' => 7, 'period_type' => 'days'), 'pay_cycle_repetitions' => 2));
     foreach ($memberships as $key => $data) {
         $item = new MS_Model_Membership();
         foreach ($data as $prop => $val) {
             if (!property_exists($item, $prop)) {
                 continue;
             }
             $item->{$prop} = $val;
         }
         $item->save();
         $id = $item->id;
         self::$ids['membership'][$key] = $id;
     }
     // Prepare Payment Gateways.
     $gateway = MS_Model_Gateway::factory(MS_Gateway_Stripe::ID);
     $gateway->mode = MS_Gateway::MODE_SANDBOX;
     $gateway->active = true;
     $gateway->test_secret_key = 'sk_test_MSKvYHhIm3kKNr4tshnZHIEk';
     $gateway->test_publishable_key = 'pk_test_h8fk0CAW287ToA3o6aeehThB';
     $gateway->save();
     $gateway = MS_Model_Gateway::factory(MS_Gateway_Stripeplan::ID);
     $gateway->mode = MS_Gateway::MODE_SANDBOX;
     $gateway->active = true;
     $gateway->test_secret_key = 'sk_test_MSKvYHhIm3kKNr4tshnZHIEk';
     $gateway->test_publishable_key = 'pk_test_h8fk0CAW287ToA3o6aeehThB';
     $gateway->save();
     // Clear the plugin Factory-Cache
     MS_Factory::_reset();
 }
 /**
  * Membership invoice shortcode callback function.
  *
  * @since  1.0.0
  *
  * @param mixed[] $atts Shortcode attributes.
  */
 public function membership_invoice($atts)
 {
     MS_Helper_Shortcode::did_shortcode(MS_Helper_Shortcode::SCODE_MS_INVOICE);
     $data = apply_filters('ms_controller_shortcode_invoice_atts', shortcode_atts(array('post_id' => 0, 'id' => 0, 'pay_button' => 1), $atts, MS_Helper_Shortcode::SCODE_MS_INVOICE));
     if (!empty($data['id'])) {
         $data['post_id'] = $data['id'];
     }
     if (!empty($data['post_id'])) {
         $invoice = MS_Factory::load('MS_Model_Invoice', $data['post_id']);
         $subscription = MS_Factory::load('MS_Model_Relationship', $invoice->ms_relationship_id);
         $data['invoice'] = $invoice;
         $data['member'] = MS_Factory::load('MS_Model_Member', $invoice->user_id);
         $data['ms_relationship'] = $subscription;
         $data['membership'] = $subscription->get_membership();
         $data['gateway'] = MS_Model_Gateway::factory($invoice->gateway_id);
         $view = MS_Factory::create('MS_View_Shortcode_Invoice');
         $view->data = apply_filters('ms_view_shortcode_invoice_data', $data, $this);
         return $view->to_html();
     }
 }
 /**
  * Returns field definitions to render the payment box for the specified
  * membership.
  *
  * @since  1.0.0
  *
  * @return array An array containing all field definitions.
  */
 private function get_fields()
 {
     global $wp_locale;
     $membership = $this->data['membership'];
     $action = MS_Controller_Membership::AJAX_ACTION_UPDATE_MEMBERSHIP;
     $nonce = wp_create_nonce($action);
     $fields = array();
     $fields['price'] = array('id' => 'price', 'title' => __('Payment Amount', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_NUMBER, 'before' => MS_Plugin::instance()->settings->currency_symbol, 'value' => $membership->price, 'class' => 'ms-text-smallish', 'config' => array('step' => 'any', 'min' => 0), 'placeholder' => '0' . $wp_locale->number_format['decimal_point'] . '00', 'ajax_data' => array(1));
     $fields['payment_type'] = array('id' => 'payment_type', 'title' => __('This Membership requires', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $membership->payment_type, 'field_options' => MS_Model_Membership::get_payment_types(), 'ajax_data' => array(1));
     $fields['period_unit'] = array('id' => 'period_unit', 'title' => __('Grant access for', MS_TEXT_DOMAIN), 'name' => '[period][period_unit]', 'type' => MS_Helper_Html::INPUT_TYPE_NUMBER, 'value' => $membership->period_unit, 'class' => 'ms-text-small', 'config' => array('step' => 1, 'min' => 1), 'placeholder' => '1', 'ajax_data' => array(1));
     $fields['period_type'] = array('id' => 'period_type', 'name' => '[period][period_type]', 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $membership->period_type, 'field_options' => MS_Helper_Period::get_period_types('plural'), 'ajax_data' => array(1));
     $fields['pay_cycle_period_unit'] = array('id' => 'pay_cycle_period_unit', 'title' => __('Payment Frequency', MS_TEXT_DOMAIN), 'name' => '[pay_cycle_period][period_unit]', 'type' => MS_Helper_Html::INPUT_TYPE_NUMBER, 'value' => $membership->pay_cycle_period_unit, 'class' => 'ms-text-small', 'config' => array('step' => 1, 'min' => 1), 'placeholder' => '1', 'ajax_data' => array(1));
     $fields['pay_cycle_period_type'] = array('id' => 'pay_cycle_period_type', 'name' => '[pay_cycle_period][period_type]', 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $membership->pay_cycle_period_type, 'field_options' => MS_Helper_Period::get_period_types('plural'), 'ajax_data' => array(1));
     $fields['pay_cycle_repetitions'] = array('id' => 'pay_cycle_repetitions', 'title' => __('Total Payments', MS_TEXT_DOMAIN), 'name' => '[pay_cycle_repetitions]', 'type' => MS_Helper_Html::INPUT_TYPE_NUMBER, 'after' => __('payments (0 = unlimited)', MS_TEXT_DOMAIN), 'value' => $membership->pay_cycle_repetitions, 'class' => 'ms-text-small', 'config' => array('step' => '1', 'min' => 0), 'placeholder' => '0', 'ajax_data' => array(1));
     $fields['period_date_start'] = array('id' => 'period_date_start', 'title' => __('Grant access from', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_DATEPICKER, 'value' => $membership->period_date_start, 'placeholder' => __('Start Date...', MS_TEXT_DOMAIN), 'ajax_data' => array(1));
     $fields['period_date_end'] = array('id' => 'period_date_end', 'type' => MS_Helper_Html::INPUT_TYPE_DATEPICKER, 'value' => $membership->period_date_end, 'before' => _x('to', 'date range', MS_TEXT_DOMAIN), 'placeholder' => __('End Date...', MS_TEXT_DOMAIN), 'ajax_data' => array(1));
     $fields['on_end_membership_id'] = array('id' => 'on_end_membership_id', 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'title' => __('After this membership ends', MS_TEXT_DOMAIN), 'value' => $membership->on_end_membership_id, 'field_options' => $membership->get_after_ms_ends_options(), 'ajax_data' => array(1));
     $fields['enable_trial_addon'] = array('id' => 'enable_trial_addon', 'type' => MS_Helper_Html::INPUT_TYPE_BUTTON, 'value' => __('Yes, enable Trial Memberships!', MS_TEXT_DOMAIN), 'button_value' => 1, 'ajax_data' => array('action' => MS_Controller_Addon::AJAX_ACTION_TOGGLE_ADDON, '_wpnonce' => wp_create_nonce(MS_Controller_Addon::AJAX_ACTION_TOGGLE_ADDON), 'addon' => MS_Model_Addon::ADDON_TRIAL, 'field' => 'active'));
     $fields['trial_period_enabled'] = array('id' => 'trial_period_enabled', 'type' => MS_Helper_Html::INPUT_TYPE_RADIO_SLIDER, 'title' => '<strong>' . __('Trial Period', MS_TEXT_DOMAIN) . '</strong>', 'after' => __('Offer Free Trial', MS_TEXT_DOMAIN), 'value' => $membership->trial_period_enabled, 'ajax_data' => array(1));
     $fields['trial_period_unit'] = array('id' => 'trial_period_unit', 'name' => '[trial_period][period_unit]', 'before' => __('The Trial is free and lasts for', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_NUMBER, 'value' => $membership->trial_period_unit, 'class' => 'ms-text-small', 'config' => array('step' => 1, 'min' => 1), 'placeholder' => '1', 'ajax_data' => array(1));
     $fields['trial_period_type'] = array('id' => 'trial_period_type', 'name' => '[trial_period][period_type]', 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $membership->trial_period_type, 'field_options' => MS_Helper_Period::get_period_types('plural'), 'ajax_data' => array(1));
     $fields['membership_id'] = array('id' => 'membership_id', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $membership->id);
     $fields['action'] = array('id' => 'action', 'type' => MS_Helper_Html::INPUT_TYPE_HIDDEN, 'value' => $action);
     // Get a list of all payment gateways.
     $gateways = MS_Model_Gateway::get_gateways();
     $fields['gateways'] = array();
     foreach ($gateways as $gateway) {
         if ('free' == $gateway->id) {
             continue;
         }
         if (!$gateway->active) {
             continue;
         }
         $payment_types = $gateway->supported_payment_types();
         $wrapper_class = 'ms-payment-type-' . implode(' ms-payment-type-', array_keys($payment_types));
         $fields['gateways'][$gateway->id] = array('id' => 'disabled-gateway-' . $gateway->id, 'type' => MS_Helper_Html::INPUT_TYPE_RADIO_SLIDER, 'title' => $gateway->name, 'before' => __('Available', MS_TEXT_DOMAIN), 'after' => __('Not available', MS_TEXT_DOMAIN), 'value' => !$membership->can_use_gateway($gateway->id), 'class' => 'reverse', 'wrapper_class' => 'ms-payment-type-wrapper ' . $wrapper_class, 'ajax_data' => array('field' => 'disabled_gateways[' . $gateway->id . ']', '_wpnonce' => $nonce, 'action' => $action, 'membership_id' => $membership->id));
     }
     // Modify some fields for free memberships.
     if ($membership->is_free) {
         $fields['price'] = '';
         $fields['payment_type'] = array('id' => 'payment_type', 'title' => __('Access Structure:', MS_TEXT_DOMAIN), 'type' => MS_Helper_Html::INPUT_TYPE_SELECT, 'value' => $membership->payment_type, 'field_options' => MS_Model_Membership::get_payment_types('free'), 'ajax_data' => array(1));
     }
     // Process the fields and add missing default attributes.
     foreach ($fields as $key => $field) {
         if (!empty($field['ajax_data'])) {
             if (!empty($field['ajax_data']['action'])) {
                 continue;
             }
             if (!isset($fields[$key]['ajax_data']['field'])) {
                 $fields[$key]['ajax_data']['field'] = $fields[$key]['id'];
             }
             $fields[$key]['ajax_data']['_wpnonce'] = $nonce;
             $fields[$key]['ajax_data']['action'] = $action;
             $fields[$key]['ajax_data']['membership_id'] = $membership->id;
         }
     }
     return apply_filters('ms_view_membership_tab_payment_fields', $fields);
 }
 /**
  * Returns the default admin menu items for Membership2.
  * Helper function used by add_menu_pages
  *
  * @since  1.0.0
  * @return array
  */
 private function get_default_menu_pages()
 {
     $show_billing = false;
     $pages = array('memberships' => array('title' => __('Memberships', 'membership2'), 'slug' => ''), 'protected-content' => array('title' => __('Protection Rules', 'membership2'), 'slug' => 'protection'), 'members' => array('title' => __('All Members', 'membership2'), 'slug' => 'members'), 'add-member' => array('title' => __('Add Member', 'membership2'), 'slug' => 'add-member'), 'billing' => false, 'addon' => array('title' => __('Add-ons', 'membership2'), 'slug' => 'addon'), 'settings' => array('title' => __('Settings', 'membership2'), 'slug' => 'settings'), 'help' => array('title' => __('Help', 'membership2'), 'slug' => 'help'));
     $show_billing = MS_Model_Membership::have_paid_membership();
     if ($show_billing) {
         $bill_count = MS_Model_Invoice::get_unpaid_invoice_count(null, true);
         if ($bill_count > 0) {
             $msg = '%1$s <span class="awaiting-mod count-%3$s"><span class="pending-count"><i class="hidden">(</i>%2$s<i class="hidden">)</i></span></span>';
         } else {
             $msg = '%1$s';
         }
         $pages['billing'] = array('title' => sprintf($msg, __('Billing', 'membership2'), $bill_count, sanitize_html_class($bill_count, '0')), 'slug' => 'billing');
         /*
          * This condition checks if the site has configured some payment
          * gateways - if not then users cannot sign up for a membership.
          * Show a notice if no payment gateway is configured/activated.
          */
         $gateways = MS_Model_Gateway::get_gateways(true);
         $payment_possible = false;
         foreach ($gateways as $key => $gateway) {
             if ('free' == $key) {
                 continue;
             }
             $payment_possible = true;
             break;
         }
         if (!$payment_possible) {
             lib3()->ui->admin_message(sprintf(__('Oops, looks like you did not activate a payment gateway yet.<br />You need to set up and activate at least one gateway, otherwise your members cannot sign up to a paid membership.<br />%sFix this now &raquo;%s', 'membership2'), '<a href="' . self::get_admin_url('settings', array('tab' => MS_Controller_Settings::TAB_PAYMENT)) . '">', '</a>'), 'err');
         }
     }
     return $pages;
 }
 /**
  * Checks if a specific payment gateway is allowed for the current
  * membership.
  *
  * @since  1.0.0
  * @param  string $gateway_id The payment gateway ID.
  * @return bool
  */
 public function can_use_gateway($gateway_id)
 {
     $result = true;
     $this->disabled_gateways = lib3()->array->get($this->disabled_gateways);
     if (isset($this->disabled_gateways[$gateway_id])) {
         $state = $this->disabled_gateways[$gateway_id];
         $result = !lib3()->is_true($state);
     }
     if ($result) {
         $gateway = MS_Model_Gateway::factory($gateway_id);
         $result = $gateway->payment_type_supported($this);
     }
     $result = apply_filters('ms_model_membership_can_use_gateway', $result, $gateway_id, $this);
     return $result;
 }
    /**
     * Displays the edit form for all payment gateways.
     *
     * @since  1.0.0
     */
    protected function gateway_settings()
    {
        $gateways = MS_Model_Gateway::get_gateways();
        $groups = array();
        foreach ($gateways as $gateway) {
            $group = $gateway->group;
            if (empty($group)) {
                continue;
            }
            $groups[$group] = lib2()->array->get($groups[$group]);
            $groups[$group][$gateway->id] = $gateway;
        }
        foreach ($groups as $label => $group) {
            ?>
		<div class="ms-gateway-group">
			<h4><?php 
            echo $label;
            ?>
</h4>

			<?php 
            foreach ($group as $gateway) {
                $this->gateway_item_settings($gateway);
            }
            ?>

		</div>
		<?php 
        }
    }
    /**
     * Create view output.
     *
     * @since  1.0.0
     *
     * @return string
     */
    public function to_html()
    {
        $this->check_simulation();
        $buttons = array();
        // Count invalid transactions.
        $args = array('state' => 'err');
        $error_count = MS_Model_Transactionlog::get_item_count($args);
        if ($error_count && (empty($_GET['state']) || 'err' != $_GET['state'])) {
            if (1 == $error_count) {
                $message = __('One transaction failed. Please %2$sreview the logs%3$s and decide if you want to ignore the transaction or manually assign it to an invoice.', MS_TEXT_DOMAIN);
            } else {
                $message = __('%1$s transactions failed. Please %2$sreview the logs%3$s and decide if you want to ignore the transaction or manually assign it to an invoice.', MS_TEXT_DOMAIN);
            }
            $review_url = MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs', 'state' => 'err'));
            lib2()->ui->admin_message(sprintf($message, $error_count, '<a href="' . $review_url . '">', '</a>'), 'err');
        }
        if (isset($_GET['show']) && 'logs' == $_GET['show']) {
            $title = __('Transaction Logs', MS_TEXT_DOMAIN);
            $listview = MS_Factory::create('MS_Helper_ListTable_TransactionLog');
            $listview->prepare_items();
            $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing'), 'value' => __('Show Invoices', MS_TEXT_DOMAIN), 'class' => 'button');
        } else {
            $title = __('Billing', MS_TEXT_DOMAIN);
            $listview = MS_Factory::create('MS_Helper_ListTable_Billing');
            $listview->prepare_items();
            $buttons[] = array('id' => 'add_new', 'type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing', array('action' => MS_Controller_Billing::ACTION_EDIT, 'invoice_id' => 0)), 'value' => __('Create new Invoice', MS_TEXT_DOMAIN), 'class' => 'button');
            $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs')), 'value' => __('Show Transaction Logs', MS_TEXT_DOMAIN), 'class' => 'button');
            if (!empty($_GET['gateway_id'])) {
                $gateway = MS_Model_Gateway::factory($_GET['gateway_id']);
                if ($gateway->name) {
                    $title .= ' - ' . $gateway->name;
                }
            }
        }
        ob_start();
        ?>

		<div class="wrap ms-wrap ms-billing">
			<?php 
        MS_Helper_Html::settings_header(array('title' => $title, 'title_icon_class' => 'wpmui-fa wpmui-fa-credit-card'));
        ?>
			<div>
				<?php 
        foreach ($buttons as $button) {
            MS_Helper_Html::html_element($button);
        }
        ?>
			</div>
			<?php 
        $listview->views();
        $listview->search_box(__('User', MS_TEXT_DOMAIN), 'search');
        ?>
			<form action="" method="post">
				<?php 
        $listview->display();
        ?>
			</form>
		</div>

		<?php 
        $html = ob_get_clean();
        return apply_filters('ms_view_billing_list', $html, $this);
    }
 /**
  * Tries to process a single transaction again.
  *
  * This function is only useful when the transaction matching was added
  * before callig it again.
  *
  * @since  1.0.1.2
  * @param  int $transaction_id The ID of the transaction log item.
  * @return bool True means that the transaction was processed.
  */
 public static function retry_to_process($transaction_id)
 {
     $res = false;
     $log = MS_Factory::load('MS_Model_Transactionlog', $transaction_id);
     if (empty($log) || $log->id != $transaction_id) {
         // Could not find the requested transaction log item.
         return $res;
     }
     if ('ok' == $log->state) {
         // The transaction was already processed (automatically or manual).
         return $res;
     }
     $post_data = $log->post;
     if (empty($post_data) || !is_array($post_data)) {
         // We do not have POST data available for the transaction.
         // Re-Processing is not possible.
         return $res;
     }
     $orig_post = $_POST;
     $orig_req = $_REQUEST;
     // Set up the PHP environment to process the transaction again.
     $gateway = MS_Model_Gateway::factory($log->gateway_id);
     $_POST = $post_data;
     $_REQUEST = $post_data;
     switch ($log->method) {
         case 'request':
             // Intentionally not implemented:
             // Request payment needs a subscription to work.
             break;
         case 'process':
             // Intentionally not implemented:
             // Request payment needs a subscription to work.
             break;
         case 'handle':
             $log = $gateway->handle_return($log);
             break;
     }
     if ('ok' == $log->state) {
         $res = true;
     }
     $_POST = $orig_post;
     $_REQUEST = $orig_req;
     return $res;
 }
 /**
  * Handle update credit card information in gateway.
  *
  * Used to change credit card info in account's page.
  *
  * Related action hooks:
  * - template_redirect
  *
  * @since  1.0.0
  */
 public function update_card()
 {
     if (!empty($_POST['gateway'])) {
         $gateway = MS_Model_Gateway::factory($_POST['gateway']);
         $member = MS_Model_Member::get_current_member();
         switch ($gateway->id) {
             case MS_Gateway_Stripe::ID:
                 if (!empty($_POST['stripeToken']) && $this->verify_nonce()) {
                     lib2()->array->strip_slashes($_POST, 'stripeToken');
                     $gateway->add_card($member, $_POST['stripeToken']);
                     if (!empty($_POST['ms_relationship_id'])) {
                         $ms_relationship = MS_Factory::load('MS_Model_Relationship', $_POST['ms_relationship_id']);
                         MS_Model_Event::save_event(MS_Model_Event::TYPE_UPDATED_INFO, $ms_relationship);
                     }
                     wp_safe_redirect(esc_url_raw(add_query_arg(array('msg' => 1))));
                     exit;
                 }
                 break;
             case MS_Gateway_Authorize::ID:
                 if ($this->verify_nonce()) {
                     do_action('ms_controller_frontend_signup_gateway_form', $this);
                 } elseif (!empty($_POST['ms_relationship_id']) && $this->verify_nonce($_POST['gateway'] . '_' . $_POST['ms_relationship_id'])) {
                     $gateway->update_cim_profile($member);
                     $gateway->save_card_info($member);
                     if (!empty($_POST['ms_relationship_id'])) {
                         $ms_relationship = MS_Factory::load('MS_Model_Relationship', $_POST['ms_relationship_id']);
                         MS_Model_Event::save_event(MS_Model_Event::TYPE_UPDATED_INFO, $ms_relationship);
                     }
                     wp_safe_redirect(esc_url_raw(add_query_arg(array('msg' => 1))));
                     exit;
                 }
                 break;
             default:
                 break;
         }
     }
     do_action('ms_controller_gateway_update_card', $this);
 }
 /**
  * Output column content
  *
  * @since  1.0.0
  * @param  object $item The item that is displayed.
  * @return string The HTML code to output.
  */
 public function column_gateway($item, $column_name)
 {
     $html = MS_Model_Gateway::get_name($item->gateway_id, true);
     return $html;
 }
    /**
     * Create view output.
     *
     * @since  1.0.0
     *
     * @return string
     */
    public function to_html()
    {
        $this->check_simulation();
        $buttons = array();
        $module = 'billing';
        if (isset($_GET['show'])) {
            $module = $_GET['show'];
        }
        if (!$module) {
            // Show a message if there are error-state transactions.
            $args = array('state' => 'err');
            $error_count = MS_Model_Transactionlog::get_item_count($args);
            if ($error_count) {
                if (1 == $error_count) {
                    $message = __('One transaction failed. Please %2$sreview the logs%3$s and decide if you want to ignore the transaction or manually assign it to an invoice.', 'membership2');
                } else {
                    $message = __('%1$s transactions failed. Please %2$sreview the logs%3$s and decide if you want to ignore the transaction or manually assign it to an invoice.', 'membership2');
                }
                $review_url = MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs', 'state' => 'err'));
                lib3()->ui->admin_message(sprintf($message, $error_count, '<a href="' . $review_url . '">', '</a>'), 'err');
            }
        }
        // Decide which list to display in the Billings page.
        switch ($module) {
            // Transaction logs.
            case 'logs':
                $title = __('Transaction Logs', 'membership2');
                $listview = MS_Factory::create('MS_Helper_ListTable_TransactionLog');
                $listview->prepare_items();
                $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing'), 'value' => __('Show Invoices', 'membership2'), 'class' => 'button');
                break;
                // M1 Migration matching.
            // M1 Migration matching.
            case 'matching':
                $title = __('Automatic Transaction Matching', 'membership2');
                $listview = MS_Factory::create('MS_Helper_ListTable_TransactionMatching');
                $listview->prepare_items();
                $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing'), 'value' => __('Show Invoices', 'membership2'), 'class' => 'button');
                $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs')), 'value' => __('Show Transaction Logs', 'membership2'), 'class' => 'button');
                break;
                // Default billings list.
            // Default billings list.
            case 'billing':
            default:
                $title = __('Billing', 'membership2');
                $listview = MS_Factory::create('MS_Helper_ListTable_Billing');
                $listview->prepare_items();
                $buttons[] = array('id' => 'add_new', 'type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing', array('action' => MS_Controller_Billing::ACTION_EDIT, 'invoice_id' => 0)), 'value' => __('Create new Invoice', 'membership2'), 'class' => 'button');
                $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing', array('show' => 'logs')), 'value' => __('Show Transaction Logs', 'membership2'), 'class' => 'button');
                if (!empty($_GET['gateway_id'])) {
                    $gateway = MS_Model_Gateway::factory($_GET['gateway_id']);
                    if ($gateway->name) {
                        $title .= ' - ' . $gateway->name;
                    }
                }
                break;
        }
        if ('matching' != $module) {
            if (MS_Model_Import::can_match()) {
                $btn_label = __('Setup automatic matching', 'membership2');
                $btn_class = 'button';
            } else {
                $btn_label = '(' . __('Setup automatic matching', 'membership2') . ')';
                $btn_class = 'button button-link';
            }
            $buttons[] = array('type' => MS_Helper_Html::TYPE_HTML_LINK, 'url' => MS_Controller_Plugin::get_admin_url('billing', array('show' => 'matching')), 'value' => $btn_label, 'class' => $btn_class);
        }
        // Default list view part - dislay prepared values from above.
        ob_start();
        ?>

		<div class="wrap ms-wrap ms-billing">
			<?php 
        MS_Helper_Html::settings_header(array('title' => $title, 'title_icon_class' => 'wpmui-fa wpmui-fa-credit-card'));
        ?>
			<div>
				<?php 
        foreach ($buttons as $button) {
            MS_Helper_Html::html_element($button);
        }
        ?>
			</div>
			<?php 
        $listview->views();
        $listview->search_box(__('User', 'membership2'), 'search');
        ?>
			<form action="" method="post">
				<?php 
        $listview->display();
        ?>
			</form>
		</div>

		<?php 
        $html = ob_get_clean();
        return apply_filters('ms_view_billing_list', $html, $this);
    }