function _notify2post()
 {
     // parse
     if ($notify_response = $this->_get_notify()) {
         // log
         mgm_log($notify_response, $this->module . __FUNCTION__);
         // only if canceled
         if ($notify_response->type == 'customer.subscription.deleted') {
             // get email
             $customer_id = $notify_response->data->object->customer;
             // get transaction
             if ($tran = mgm_get_transaction_by_option('stripe_customer_id', $customer_id)) {
                 // check
                 if ($member = mgm_get_member($transaction['data']['user_id'])) {
                     // proces only when not canceled
                     if (!in_array($member->status, array(MGM_STATUS_AWAITING_CANCEL, MGM_STATUS_CANCELLED))) {
                         // set post fields
                         $_POST['custom'] = $tran['id'];
                         $_POST['notify_type'] = 'subscr_canceled';
                         //$_POST['notify_type'] = 'subscr_expired'
                         // set notify
                         $this->response = $notify_response;
                         // log
                         mgm_log('Cancelling from Notify Post' . mgm_pr($tran, true), __FUNCTION__);
                     }
                 }
             }
         }
     }
 }
 function _process_ins_messages()
 {
     // sale id
     $sale_id = $_POST['sale_id'];
     // recurring
     $recurring = (bool) $_POST['recurring'];
     // we have sale id, get transaction details from it
     $transaction = mgm_get_transaction_by_option('2checkout_sale_id', $sale_id);
     // get user id
     $user_id = $transaction['data']['user_id'];
     // user data
     $user = get_userdata($user_id);
     // mgm data
     $member = mgm_get_member($user_id);
     // update flag
     $update = false;
     // check each type
     switch ($_POST['message_type']) {
         case 'ORDER_CREATED':
             // not processed
             break;
         case 'FRAUD_STATUS_CHANGED':
         case 'INVOICE_STATUS_CHANGED':
             // check
             if ($recurring) {
                 // check
                 if (isset($_POST['fraud_status']) && $_POST['fraud_status'] == 'pass') {
                     // cancel
                     unset($member->status_reset_on, $member->status_reset_as);
                     // status
                     $member->status = MGM_STATUS_ACTIVE;
                     $member->status_str = __('Last payment was successful', 'mgm');
                     $member->last_pay_date = date('Y-m-d');
                     // mark update
                     $update = true;
                 }
             }
             break;
         case 'REFUND_ISSUED':
             // check
             if ($recurring) {
                 // refund amount less than actual order
                 if ($_POST['item_list_amount_1'] < $transaction['return_data']['total']) {
                     // cancel on , changed since partial refund will not be cancelled #734
                     // $member->status_reset_on = $member->expire_date;
                     // $member->status_reset_as = MGM_STATUS_CANCELLED;
                 } else {
                     // cancel instantly
                     $member->status_str = __('Subscription Cancelled', 'mgm');
                     $member->expire_date = date('Y-m-d');
                     // set new status
                     $member->status = MGM_STATUS_CANCELLED;
                 }
                 // mark update
                 $update = true;
             }
             break;
         case 'RECURRING_INSTALLMENT_SUCCESS':
             // check
             if ($recurring) {
                 // cancel
                 unset($member->status_reset_on, $member->status_reset_as);
                 // status
                 $member->status = MGM_STATUS_ACTIVE;
                 $member->status_str = __('Last payment was successful', 'mgm');
                 $member->last_pay_date = date('Y-m-d');
                 // mark update
                 $update = true;
             }
             break;
         case 'RECURRING_INSTALLMENT_FAILED':
             // check
             if ($recurring) {
                 // cancel on
                 $member->status_reset_on = $member->expire_date;
                 $member->status_reset_as = MGM_STATUS_CANCELLED;
                 // mark update
                 $update = true;
             }
             break;
         case 'RECURRING_STOPPED':
             // we already have this
             // check
             if ($recurring) {
                 // if today or set as instant cancel
                 if ($member->expire_date == date('Y-m-d') || $this->setting['subs_cancel'] == 'instant') {
                     $member->status_str = __('Subscription Cancelled', 'mgm');
                     $member->expire_date = date('Y-m-d');
                     // set new status
                     $member->status = MGM_STATUS_CANCELLED;
                 } else {
                     // reset on
                     $member->status_reset_on = $member->expire_date;
                     $member->status_reset_as = MGM_STATUS_CANCELLED;
                 }
                 // mark update
                 $update = true;
             }
             break;
         case 'RECURRING_COMPLETE':
             // not processed
             break;
         case 'RECURRING_RESTART':
         case 'RECURRING_RESTARTED':
             // check
             if ($recurring) {
                 // cancel
                 unset($member->status_reset_on, $member->status_reset_as);
                 // status
                 $member->status = MGM_STATUS_ACTIVE;
                 $member->status_str = __('Last payment was successful', 'mgm');
                 $member->last_pay_date = date('Y-m-d');
                 // mark update
                 $update = true;
             }
             break;
     }
     // update
     if ($update) {
         // save
         $member->save();
     }
 }
 /**
  * API helper method get transaction data by option
  *
  * @param string $option_name
  * @param string $option_value
  * @return array $transaction
  * @deprecated 
  * @see mgm_get_transaction_by_option()
  */
 function _get_transaction_by_option($option_name, $option_value)
 {
     // return
     return mgm_get_transaction_by_option($option_name, $option_value);
 }
    function _cancel_membership($user_id = NULL, $redirect = false)
    {
        // system
        $system_obj = mgm_get_class('system');
        $s_packs = mgm_get_class('subscription_packs');
        $duration_str = $s_packs->duration_str;
        $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
        $dpne = bool_from_yn($system_obj->get_setting('disable_payment_notify_emails'));
        //issue #1521
        $is_admin = is_super_admin() ? true : false;
        // if passthrough provided
        if (isset($_REQUEST['extra'])) {
            // get passthrough, stop further process if fails to parse
            $custom = $this->_get_transaction_passthrough($_REQUEST['extra']);
            // local var
            extract($custom);
        } elseif (isset($_REQUEST['SUBSCRIPTION_ID']) || isset($_REQUEST['SubscriptionID'])) {
            // get tran
            $tran = mgm_get_transaction_by_option('zombaio_subscription_id', isset($_REQUEST['SUBSCRIPTION_ID']) ? $_REQUEST['SUBSCRIPTION_ID'] : $_REQUEST['SubscriptionID']);
            // local var
            extract($tran['data']);
        } elseif (isset($_REQUEST['TRANSACTION_ID'])) {
            // get tran
            $tran = mgm_get_transaction_by_option('zombaio_transaction_id', $_REQUEST['TRANSACTION_ID']);
            // local var
            extract($tran['data']);
        } elseif (isset($_REQUEST['username'])) {
            // get user
            if ($user = get_user_by('login', $_REQUEST['username'])) {
                $user_id = $user->ID;
            }
        }
        // log
        // mgm_log($user_id, ($this->module . '_' . __FUNCTION__));
        // no user id
        if (!$user_id) {
            // message
            $message = 'Could not read member in the following REQUEST data. 
			            Please debug or contact magic members to fix the problem making sure to pass 
						on the following data. <br /><br /><pre>' . "\n\n" . print_r($_REQUEST, true) . '</pre>';
            // notify admin, only if gateway emails on
            if (!$dge) {
                // mail
                mgm_mail($system_obj->get_setting('admin_email'), 'Error in Zombaio membership cancellation', $message);
            } else {
                // log
                mgm_log($message, $this->module . '_' . __FUNCTION__);
            }
            // exit
            exit;
        }
        // find user
        $user = get_userdata($user_id);
        $member = mgm_get_member($user_id);
        // multiple membesrhip level update:
        $multiple_update = false;
        // check
        if (isset($_POST['membership_type']) && $member->membership_type != $_POST['membership_type'] || isset($membership_type) && $member->membership_type != $membership_type) {
            $multiple_update = true;
            $member = mgm_get_member_another_purchase($user_id, $_POST['membership_type']);
        }
        // get pack
        if ($member->pack_id) {
            $subs_pack = $s_packs->get_pack($member->pack_id);
        } else {
            $subs_pack = $s_packs->validate_pack($member->amount, $member->duration, $member->duration_type, $member->membership_type);
        }
        // tracking fields module_field => post_field
        $tracking_fields = array('txn_type' => 'Action', 'subscr_id' => array('SUBSCRIPTION_ID', 'SubscriptionID'), 'txn_id' => 'TRANSACTION_ID');
        // save tracking fields
        $this->_save_tracking_fields($tracking_fields, $member, $_REQUEST);
        // types
        $duration_exprs = $s_packs->get_duration_exprs();
        // default expire date
        $expire_date = $member->expire_date;
        // if lifetime:
        if ($member->duration_type == 'l') {
            $expire_date = date('Y-m-d');
        }
        // if trial on
        if ($subs_pack['trial_on'] && isset($duration_exprs[$subs_pack['trial_duration_type']])) {
            // if cancel data is before trial end, set cancel on trial expire_date
            $trial_expire_date = strtotime("+{$subs_pack['trial_duration']} {$duration_exprs[$subs_pack['trial_duration_type']]}", $member->join_date);
            // if lower
            if (time() < $trial_expire_date) {
                $expire_date = date('Y-m-d', $trial_expire_date);
            }
        }
        // transaction_id
        $trans_id = $member->transaction_id;
        // log
        // mgm_log($member, ($this->module . '_' . __FUNCTION__));
        // mgm_log($expire_date . ' ' . date('Y-m-d H:i:s'), ($this->module . '_' . __FUNCTION__));
        // if today
        if (time() >= strtotime($expire_date)) {
            // status
            $new_status = MGM_STATUS_CANCELLED;
            $new_status_str = __('Subscription cancelled', 'mgm');
            // set
            $member->status = $new_status;
            $member->status_str = $new_status_str;
            $member->expire_date = date('Y-m-d H:i:s');
            // reassign expiry membership pack if exists: issue#: 535
            $member = apply_filters('mgm_reassign_member_subscription', $user_id, $member, 'CANCEL', true);
        } else {
            // date
            $date_format = mgm_get_date_format('date_format');
            // status
            $new_status = MGM_STATUS_AWAITING_CANCEL;
            $new_status_str = sprintf(__('Subscription awaiting cancellation on %s', 'mgm'), date($date_format, strtotime($expire_date)));
            // set
            $member->status = $new_status;
            $member->status_str = $new_status_str;
            // set reset date
            $member->status_reset_on = $expire_date;
            $member->status_reset_as = MGM_STATUS_CANCELLED;
        }
        // log
        // mgm_log($member, ($this->module . '_' . __FUNCTION__));
        // update user
        // multiple membesrhip level update:
        if ($multiple_update) {
            mgm_save_another_membership_fields($member, $user_id);
        } else {
            $member->save();
        }
        // transaction status
        mgm_update_transaction_status($trans_id, $new_status, $new_status_str);
        // send email notification to client
        $blogname = get_option('blogname');
        // subject
        $subject = $system_obj->get_template('subscription_cancelled_email_template_subject', array('blogname' => $blogname), true);
        // body
        $message = $system_obj->get_template('subscription_cancelled_email_template_body', array('blogname' => $blogname, 'name' => $user->display_name, 'email' => $user->user_email, 'admin_email' => $system_obj->setting['admin_email']), true);
        // send email notification to user
        if (!$dpne) {
            //issue #862
            $subject = mgm_replace_email_tags($subject, $user_id);
            $message = mgm_replace_email_tags($message, $user_id);
            // mail
            mgm_mail($user->user_email, $subject, $message);
        }
        // notify admin, only if gateway emails on
        if (!$dge) {
            $subject = "[{$blogname}] {$user->user_email} - {$new_status}";
            $message = "\tUser display name: {$user->display_name}\n\n<br />\r\r\n\t\t\t\t\tUser email: {$user->user_email}\n\n<br />\r\r\n\t\t\t\t\tUser ID: {$user->ID}\n\n<br />\r\r\n\t\t\t\t\tMembership Type: {$membership_type}\n\n<br />\r\r\n\t\t\t\t\tNew status: {$new_status}\n\n<br />\r\r\n\t\t\t\t\tStatus message: {$member->status_str}\n\n<br />\t\t\t\t\t\r\r\n\t\t\t\t\tPayment Mode: Cancelled\n\n<br />\r\r\n\t\t\t\t\tPOST Data was: \n\n<br /><br /><pre>" . print_r($_POST, true) . '</pre>';
            mgm_mail($system_obj->setting['admin_email'], $subject, $message);
        }
        // after cancellation hook
        do_action('mgm_membership_subscription_cancelled', array('user_id' => $user_id));
        // redirect
        if ($redirect) {
            // message
            $lformat = mgm_get_date_format('date_format_long');
            $message = sprintf(__("You have successfully unsubscribed. Your account has been marked for cancellation on %s", "mgm"), $expire_date == date('Y-m-d') ? 'Today' : date($lformat, strtotime($expire_date)));
            //issue #1521
            if ($is_admin) {
                mgm_redirect(add_query_arg(array('user_id' => $user_id, 'unsubscribe_errors' => urlencode($message)), admin_url('user-edit.php')));
            }
            // redirect
            mgm_redirect(mgm_get_custom_url('membership_details', false, array('unsubscribed' => 'true', 'unsubscribe_errors' => urlencode($message))));
        }
    }
    /**
     * Sync Membership data and DataPlus Recurring transactions
     *
     */
    function update_dataplus_transactions()
    {
        // comment the below return once finished:
        // return;
        if (!($epdb = $this->_get_epdb_ref())) {
            return;
        }
        //global $wpdb;
        //skip if table doesn't exist
        if (!count($epdb->get_results("SHOW TABLES LIKE '" . TBL_MGM_EPOCH_TRANS_STATUS . "'"))) {
            return;
        }
        //consider only 'F' : Initial Free Trial Transaction
        //				'I' : Standard Initial Recurring Transaction
        //				'N'	: NonĀ­Initial Recurring Transaction
        $arr_transtypes = array('F' => 'free_trial_transaction', 'I' => 'initial_recurring_transaction', 'N' => 'recurring_transaction');
        // transtypes_in
        $transtypes_in = mgm_map_for_in(array_keys($arr_transtypes));
        // sql;
        $sql = sprintf('SELECT ets_transaction_id, ets_transaction_date, ets_transaction_type, ets_ref_trans_ids, ets_member_idx 
		                 FROM `' . TBL_MGM_EPOCH_TRANS_STATUS . '` WHERE ets_transaction_type IN(%s) 
						 AND (process_status="N" OR process_status IS NULL)
						 ORDER BY ets_transaction_date ASC LIMIT 0,50', $transtypes_in);
        // tran
        $transdata = $epdb->get_results($sql);
        // log
        mgm_log('SQL: ' . $epdb->last_query, __FUNCTION__);
        // log
        mgm_log($transdata, __FUNCTION__);
        // count
        if (count($transdata) > 0) {
            // set
            foreach ($transdata as $tdata) {
                // init
                $data = array();
                //$data['x_custom'] 		= $tdata->ets_ref_trans_ids;
                $data['trans_date'] = $tdata->ets_transaction_date;
                $data['txn_type'] = $arr_transtypes[$tdata->ets_transaction_type];
                $data['transaction_id'] = $tdata->ets_transaction_id;
                // as per Epoch Tech Support, Only Sucsessful Transactions will be inserted to EpochTransStats
                $data['ans'] = 'Y';
                //rewrite if status is dynamic
                $data['order_id'] = $tdata->ets_member_idx;
                // tran
                $tran = mgm_get_transaction_by_option('epoch_order_id', $data['order_id']);
                // verify
                if (isset($tran['id'])) {
                    // set
                    $data['x_custom'] = $tran['id'];
                    // set user
                    if (isset($tran['user_id'])) {
                        $data['user_id'] = $tran['user_id'];
                    }
                    //rewrite global $_REQUEST for parameter compatibility
                    $_REQUEST = $data;
                    // log
                    mgm_log($_REQUEST, __FUNCTION__);
                    // caller
                    $this->set_webhook_called_by('self');
                    //Update membership status
                    $this->process_notify();
                    // $this-process_rebill_status($data['user_id']);// @todo use this
                    // update code
                    // change record status to 'Y' once updated: so next time when the cron runs, current record will be skipped
                    $epdb->update(TBL_MGM_EPOCH_TRANS_STATUS, array('process_status' => 'Y'), array('ets_transaction_id' => $tdata->ets_transaction_id));
                    // log
                    mgm_log('TransStat Update SQL: ' . $epdb->last_query, __FUNCTION__);
                }
            }
        }
    }