function createEmail($fileArr, $filecount)
{
    $dbh = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    mysql_select_db(DB_NAME, $dbh);
    $sql = "SELECT ID, user_email FROM wp_users";
    $result = mysql_query($sql, $dbh);
    while ($IDs = mysql_fetch_array($result)) {
        $mgm_member = mgm_get_member($IDs[0]);
        if ($mgm_member->status == 'Active') {
            $s2_custom_fields = get_user_option('s2member_custom_fields', $IDs[0]);
            $tracks2email = $s2_custom_fields['tracks2email'];
            if ($tracks2email != "") {
                $tracks2emailArr = explode(",", $tracks2email);
                // gives an array of selected tracks of this user
                $user_info = get_userdata($IDs[0]);
                $email = $user_info->user_email;
                $first_name = $user_info->first_name;
                $string = "";
                foreach ($tracks2emailArr as $trackCode) {
                    foreach ($fileArr as $trackFile) {
                        if (substr($trackFile, 0, 3) == $trackCode) {
                            $string .= getTrackName($trackCode) . " - " . getRaceDateText(substr($trackFile, 3, 6)) . '<a target="_blank" href="http://hotdogs.com.au/format/functions/createpdf.php?file=' . $trackFile . '" class="trackdownload" > Download </a><br />';
                        }
                    }
                }
                if ($string != "") {
                    sendTrackEmail($email, $first_name, $string);
                }
                echo $email . "<br/>";
                //}
            }
        }
        //if active memeber
    }
}
Exemplo n.º 2
0
function mgm_patch_get_users($start, $limit)
{
    global $wpdb;
    $qry = 'SELECT ID from ' . $wpdb->users . ' WHERE ID <> 1 ORDER BY ID LIMIT ' . $start . ',' . $limit;
    $uids = $wpdb->get_col($qry);
    if (!count($uids)) {
        return false;
    }
    foreach ($uids as $user_id) {
        mgm_remove_excess_user_roles($user_id, true);
        $member = mgm_get_member($user_id);
        $pack = mgm_get_option('subscription_packs')->get_pack($member->pack_id);
        if (!empty($pack['membership_type']) && $pack['membership_type'] != $member->membership_type && $member->status == MGM_STATUS_ACTIVE) {
            $member->membership_type = $pack['membership_type'];
            // update_user_option($user_id, 'mgm_member', $member, true);
            $member->save();
        }
    }
    return true;
}
/**
 * get payment subscribe page html
 *
 * @param void
 * @return string
 * @since 1.5
 */
function mgm_get_payment_subscribe_page_html()
{
    // attach scripts, returns
    do_action('mgm_attach_scripts');
    // content
    $html = sprintf('<p>%s</p>', __('You are already subscribed or an error occurred. Please contact an administrator for more information.', 'mgm'));
    // get user query string
    $user = mgm_get_user_from_querystring();
    // member
    if (isset($user) && is_object($user)) {
        $member = mgm_get_member($user->ID);
    }
    // action
    $action = mgm_get_var('action', '', true);
    // print
    if (!empty($action) && count(mgm_get_class('membership_types')->membership_types) > 0) {
        // upgrade or complete
        if (in_array($action, array('upgrade', 'complete_payment'))) {
            $html = mgm_get_upgrade_buttons();
            // extend
        } elseif ($action == 'extend') {
            $html = mgm_get_extend_button();
            // extend
        } elseif ($action == 'purchase_another') {
            $html = mgm_get_purchase_another_subscription_button();
            //TODO
            // bad action
        } else {
            $html = sprintf('<p>%s</p>', sprintf(__('Error - Unknown action - "%s", Exiting...', 'mgm'), $action));
        }
    } elseif (isset($member) && is_object($member) && in_array($member->status, array(MGM_STATUS_NULL, MGM_STATUS_EXPIRED, MGM_STATUS_TRIAL_EXPIRED))) {
        $html = mgm_get_subscription_buttons($user, true);
    } elseif (isset($member) && is_object($member) && $member->status == MGM_STATUS_PENDING) {
        $html = sprintf('<p>%s</p>', __('Error - Your subscription status is pending. Please contact an administrator for more information.', 'mgm'));
    }
    // return
    return apply_filters('mgm_payment_subscribe_page_html', $html);
}
Exemplo n.º 4
0
 /**
  * This will update user expirey date/status if any issues
  * @param $user_id
  */
 function updateUserDetails($user_id = null)
 {
     if (is_numeric($user_id)) {
         $users[] = $user_id;
     } else {
         $users = mgm_get_all_userids();
     }
     //mgm_log(mgm_array_dump($users, true));
     $arr_skip = array('guest', 'free', 'trial');
     foreach ($users as $user_id) {
         $member = mgm_get_member($user_id);
         if (!isset($member->membership_type) || isset($member->membership_type) && in_array(strtolower($member->membership_type), $arr_skip)) {
             continue;
         }
         if (strtolower($member->status) == 'cancelled') {
             //mgm_log($user_id, 'not_updated_cacncelled', true);
         }
         if (isset($member->payment_info->subscr_id) && !empty($member->payment_info->subscr_id)) {
             $update = $this->getSaleDetails($member->payment_info->subscr_id);
             $update['user_id'] = $user_id;
             if ($update['status'] == 'active') {
                 if (strtotime($update['expire_date']) >= strtotime(date('Y-m-d'))) {
                     $update['user_id'] = $user_id;
                     //mgm_log(mgm_array_dump($update, true), 'updated-users', true);
                     $member->expire_date = $update['expire_date'];
                     $member->status = MGM_STATUS_ACTIVE;
                     $member->status_str = __('Last payment was successful', 'mgm');
                     $member->last_pay_date = $update['last_pay'];
                     $member->save();
                 } else {
                     //mgm_log(mgm_array_dump($update, true), 'not_updated_past_date', true);
                 }
             } else {
                 //mgm_log(mgm_array_dump($update, true), 'not_updated_no_details', true);
             }
         } else {
             //mgm_log($user_id, 'not_updated_no_saleid', true);
         }
     }
 }
Exemplo n.º 5
0
 function _verify_member_for_upgrade($user_id)
 {
     // get member
     $member = mgm_get_member((int) $user_id);
     // validate
     if ($member->payment_info->subscr_id == $_POST['originalSubscriptionId']) {
         // valid
         return true;
     }
     // return
     return false;
 }
    /**
     * Cancel Recurring Subscription
     * This is not a private function
     * @param int/string $trans_ref	
     * @param int $user_id	
     * @param int/string $subscr_id	
     * @return boolean
     */
    function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
    {
        //if coming form process return after a subscription payment
        if (!empty($trans_ref)) {
            $transdata = $this->_get_transaction_passthrough($trans_ref);
            if ($transdata['payment_type'] != 'subscription_purchase') {
                return false;
            }
            $user_id = $transdata['user_id'];
            if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
                $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
            } else {
                $member = mgm_get_member($user_id);
            }
            if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
                if (isset($member->payment_info->subscr_id)) {
                    $subscr_id = $member->payment_info->subscr_id;
                } else {
                    //check pack is recurring:
                    $pid = $pack_id ? $pack_id : $member->pack_id;
                    if ($pid) {
                        $s_packs = mgm_get_class('subscription_packs');
                        $sel_pack = $s_packs->get_pack($pid);
                        if ($sel_pack['num_cycles'] != 1) {
                            $subscr_id = 0;
                        }
                    }
                }
                //check for same module: if not call the same function of the applicale module.
                if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                    // log
                    // mgm_log('RECALLing '. $member->payment_info->module .': cancel_recurring_subscription FROM: ' . $this->code);
                    // return
                    return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
                }
                //skip if same pack is updated
                if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                    return false;
                }
            } else {
                return false;
            }
        }
        //only for subscription_purchase
        if ($subscr_id) {
            // set xml content
            $post_data = '<ARBCancelSubscriptionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
							<merchantAuthentication>
								<name>' . $this->setting['loginid'] . '</name>
								<transactionKey>' . $this->setting['tran_key'] . '</transactionKey>
							</merchantAuthentication>
							<refId>' . $user_id . '</refId>
							<subscriptionId>' . $subscr_id . '</subscriptionId>
						</ARBCancelSubscriptionRequest>';
            // end  point
            $endpoint = $this->_get_endpoint($this->status . '_arb');
            // test_arb, live_aim etc.
            // headers
            $http_headers = array('Content-Type' => 'text/xml');
            // create curl post
            $http_response = mgm_remote_post($endpoint, $post_data, array('headers' => $http_headers, 'timeout' => 30, 'sslverify' => false));
            // parse response and store into a different array:
            // do not use $this->response here as this will overwrite previous theprevious values in one scenario
            $arb_response = $this->_process_response('arb', $http_response, false);
            // check
            if (isset($arb_response['response_status']) && $arb_response['response_status'] == 1) {
                return true;
            }
        } elseif (is_null($subscr_id) || $subscr_id === 0) {
            //send email to admin if subscription Id is absent
            $system_obj = mgm_get_class('system');
            $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
            //send email only if setting enabled
            if (!$dge) {
                // blog
                $blogname = get_option('blogname');
                // user
                $user = get_userdata($user_id);
                // notify admin
                mgm_notify_admin_membership_cancellation_manual_removal_required($blogname, $user, $member);
            }
            // return
            return true;
        }
        // return
        return false;
    }
 /**
  * Cancel Recurring Subscription
  * This is not a private function
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $subscr_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
 {
     global $wpdb;
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             if (isset($member->payment_info->subscr_id)) {
                 $subscr_id = $member->payment_info->subscr_id;
             } else {
                 //check pack is recurring:
                 $pid = $pack_id ? $pack_id : $member->pack_id;
                 if ($pid) {
                     $s_packs = mgm_get_class('subscription_packs');
                     $sel_pack = $s_packs->get_pack($pid);
                     if ($sel_pack['num_cycles'] != 1) {
                         $subscr_id = 0;
                     }
                 }
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 // log
                 // mgm_log('RECALLing '. $member->payment_info->module .': cancel_recurring_subscription FROM: ' . $this->code);
                 // return
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     }
     //only for subscription_purchase
     if ($pack_id && $user_id) {
         $userInfo = get_userdata($user_id);
         $client_cache = $wpdb->get_results($wpdb->prepare('SELECT paymill_sub_id FROM ' . $wpdb->prefix . 'paymill_subscriptions WHERE mgm_user_id="%s" AND mgm_offer_id="%s"', array($user_id, $pack_id)), ARRAY_A);
         if (isset($client_cache[0]['paymill_sub_id']) && strlen($client_cache[0]['paymill_sub_id']) > 0) {
             $this->subscriptions->remove($client_cache[0]['paymill_sub_id']);
             $query = $wpdb->prepare('DELETE FROM ' . $wpdb->prefix . 'paymill_subscriptions WHERE mgm_user_id="%s" AND mgm_offer_id="%s"', array($user_id, $pack_id));
             $wpdb->query($query);
             return true;
         } else {
             return false;
         }
     }
     return false;
 }
Exemplo n.º 8
0
 $new_type_code = $membership_types_obj->get_type_code($type_name);
 //check
 if ($new_type_code != $type_code) {
     // get object
     $obj_sp = mgm_get_class('subscription_packs');
     //update new
     foreach ($obj_sp->packs as $key => $pack) {
         if ($obj_sp->packs[$key]['membership_type'] == $type_code) {
             $obj_sp->packs[$key]['membership_type'] = $new_type_code;
             $obj_sp->save();
         }
     }
     // loop
     foreach ($users as $user) {
         // get
         $member = mgm_get_member($user->ID);
         // if users with same membershiptype as that of selected
         if (isset($member->membership_type) && $member->membership_type == $type_code) {
             // set
             $member->membership_type = $new_type_code;
             // save
             $member->save();
         }
         // check if any multiple levels exist:
         if (isset($member->other_membership_types) && is_array($member->other_membership_types) && count($member->other_membership_types) > 0) {
             // loop
             foreach ($member->other_membership_types as $key => $memtypes) {
                 // make sure its an object:
                 $memtypes = mgm_convert_array_to_memberobj($memtypes, $user->ID);
                 // verify
                 if ($memtypes->membership_type == $type_code) {
/**
 * Updating coupon usage for register coupon only
 *
 * @param array $args
 * @return void
 */
function mgm_update_coupon_usage_process($args = array())
{
    global $wpdb;
    // check
    if (isset($args['user_id'])) {
        // user_id
        $user_id = $args['user_id'];
        $member = mgm_get_member($user_id);
        // check
        if (isset($member->coupon['update_usage']) && $member->coupon['update_usage']) {
            if (isset($member->coupon['coupon_usage_id']) && $member->coupon['coupon_usage_id']) {
                // id
                $coupon_id = $member->coupon['coupon_usage_id'];
                // update
                mgm_update_coupon_usage($coupon_id, 'after_payment');
                // once done reset the same since all type of coupon uses the same
                $member->coupon['coupon_usage_id'] = false;
                $member->coupon['update_usage'] = false;
                $member->save();
            }
        }
    }
    // check - issue #1421
    if (isset($args['guest_token'])) {
        //coupon_id
        $coupon_id = isset($args['coupon_id']) ? $args['coupon_id'] : 0;
        // update
        mgm_update_coupon_usage($coupon_id, 'after_payment');
    }
}
Exemplo n.º 10
0
 /**
  * Cancel Recurring Subscription
  * This is not a private function
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $subscr_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
 {
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             if (isset($member->payment_info->subscr_id)) {
                 $subscr_id = $member->payment_info->subscr_id;
             } else {
                 //check pack is recurring:
                 $pid = $pack_id ? $pack_id : $member->pack_id;
                 if ($pid) {
                     $s_packs = mgm_get_class('subscription_packs');
                     $sel_pack = $s_packs->get_pack($pid);
                     if ($sel_pack['num_cycles'] != 1) {
                         $subscr_id = 0;
                     }
                     // 0 stands for a lost subscription id
                 }
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 // mgm_log('RECALLing '. $member->payment_info->module .': cancel_recurring_subscription FROM: ' . $this->code);
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     }
     //ony for subscription_purchase
     if ($subscr_id) {
         // end  point
         $endpoint = $this->_get_endpoint('unsubscribe');
         // base
         // add query
         $url = add_query_arg(array('SUBSCRIPTION_ID' => urlencode($subscr_id), 'MERCHANT_ID' => urlencode($this->setting['merchant_id']), 'ZombaioGWPass' => urlencode($this->setting['gw_pass']), 'ReasonCode' => urlencode(11)), $endpoint);
         // create curl post
         //$buffer = $this->_curl_post($url);
         // headers
         $http_headers = array();
         // fetch
         $http_response = mgm_remote_post($url, $post_data, array('headers' => $http_headers, 'timeout' => 30, 'sslverify' => false));
         // verify
         if ($http_response == 1) {
             return true;
         } else {
             // message
             return $this->_get_cancel_error($http_response);
         }
     } elseif ($subscr_id === 0) {
         //send email to admin if subscription Id is absent
         $system_obj = mgm_get_class('system');
         $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
         //send email only if setting enabled
         if (!$dge) {
             $user = get_userdata($user_id);
             //send notification email to admin:
             $message = __('The User: '******'mgm') . $user->user_email . ' (' . $user_id . ') ' . __('has upgraded/cancelled subscription.', 'mgm');
             $message .= "<br/>" . __('Please unsubscribe the user subscription from Gateway Merchant panel.', 'mgm');
             if (!empty($member->transaction_id)) {
                 $message .= "<br/>" . __('MGM Transaction Id:', 'mgm') . $member->transaction_id;
             }
             //admin email:
             if (!empty($system_obj->setting['admin_email'])) {
                 @mgm_mail($system_obj->setting['admin_email'], sprintf(__('[%s] User Subscription Cancellation', 'mgm'), get_option('blogname')), $message);
             }
         }
         return true;
     }
     return false;
 }
Exemplo n.º 11
0
<?php

/** 
 * Objects merge/update
 */
//Restoring custom fileds to user meta
$arr_users = mgm_get_all_userids();
if (!empty($arr_users)) {
    foreach ($arr_users as $user_id) {
        //member
        $member = mgm_get_member($user_id);
        // save
        if (isset($member->custom_fields)) {
            foreach ($member->custom_fields as $key => $value) {
                // key
                $options_key = '_mgm_cf_' . $key;
                // verify
                if ($user_id) {
                    // update
                    update_user_option($user_id, $options_key, $value, true);
                }
            }
        }
    }
}
// end file
Exemplo n.º 12
0
 /**
  * Confirm notify URL.
  *
  * related to issue#: 528
  * As PAYPALPRO doesn't use overridden notifyurl, and posts IPN to default IPN settings URL on merchant panel
  * Confirm module field in transactions table/mgm_member object
  * 
  */
 function _confirm_notify()
 {
     $mod_code = '';
     //check possible params for transaction id [rp_invoice_id, invoice, custom]
     if (isset($_POST['rp_invoice_id']) && is_numeric($_POST['rp_invoice_id'])) {
         $transaction_id = $_POST['rp_invoice_id'];
     } elseif (isset($_POST['invoice']) && is_numeric($_POST['invoice'])) {
         $transaction_id = $_POST['invoice'];
     } elseif (isset($_POST['custom']) && is_numeric($_POST['custom'])) {
         $transaction_id = $_POST['custom'];
     } elseif (isset($_POST['custom']) && !is_numeric($_POST['custom']) && preg_match('/^subscription_/', $_POST['custom'])) {
         //for backward compatibility:
         //transaction cannot be found for old users:
         $transdata = $this->_get_transaction_passthrough($_POST['custom']);
         $member = mgm_get_member($transdata['user_id']);
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             $mod_code = preg_match('/mgm_/', $member->payment_info->module) ? $member->payment_info->module : 'mgm_' . $transdata['module'];
         }
     }
     //if a transaction id is found
     if (isset($transaction_id)) {
         $transdata = mgm_get_transaction($transaction_id);
         if (!empty($transdata['module'])) {
             $mod_code = preg_match('/mgm_/', $transdata['module']) ? $transdata['module'] : 'mgm_' . $transdata['module'];
         }
     }
     //if module code is found and not belongs to current module, then invode process_notify() function of the applicable module.
     if (!empty($mod_code) && $mod_code != $this->code) {
         // recall process_notifyof the module
         // keep the log untill paypal is resolved.
         // mgm_log('FROM PAYMENT: recalling ' . $mod_code .'->process_notify() FROM: '. $this->code );
         mgm_get_module($mod_code, 'payment')->process_notify();
         // return
         return false;
     }
     return true;
 }
function mgm_member_sort($field, $order_type, $sql_filter, $super_adminids = array())
{
    global $wpdb;
    $super_admin_in = count($super_adminids) == 0 ? 0 : implode(',', $super_adminids);
    // get members
    $sql = "SELECT SQL_CALC_FOUND_ROWS `ID` FROM `{$wpdb->users}` WHERE ID NOT IN ({$super_admin_in}) {$sql_filter}";
    //users
    $users = $wpdb->get_results($sql);
    // init
    $members = array();
    //sorted members
    $sorted_members = array();
    // check
    if ($users) {
        // loop
        foreach ($users as $user) {
            // member object
            $member = mgm_get_member($user->ID);
            switch ($field) {
                case 'last_pay_date':
                case 'expire_date':
                    // from custom field
                    if (isset($member->{$field}) && !empty($member->{$field})) {
                        $members[$user->ID] = date('Y-m-d', strtotime($member->{$field}));
                    } else {
                        $members[$user->ID] = '';
                    }
                    break;
            }
            unset($member);
        }
    }
    //sort the array
    if (strtolower($order_type) == 'desc') {
        arsort($members);
    }
    if (strtolower($order_type) == 'asc') {
        asort($members);
    }
    if (!empty($members)) {
        foreach ($members as $key => $value) {
            $sorted_members[] = $key;
        }
    }
    // return
    return $sorted_members;
}
Exemplo n.º 14
0
 function _buy_membership($transid = null)
 {
     // system
     $system_obj = mgm_get_class('system');
     $s_packs = mgm_get_class('subscription_packs');
     // get details
     //if transaction id is available:
     if (is_numeric($transid)) {
         $custom = $this->_get_transaction_passthrough($transid);
         extract($custom);
         // mgm_log($custom);
     } else {
         //Purchase Another Membership Level problem : issue #: 752
         $is_another_membership_purchase = 'N';
         $parts = explode('_', $_REQUEST['custom']);
         $params = array('user_id' => 0, 'duration' => '', 'duration_type' => '', 'pack_id' => 0, 'is_another_membership_purchase' => 'N', 'membership_type' => '');
         $i = 0;
         foreach ($params as $param => $default) {
             if (isset($parts[$i])) {
                 ${$param} = $parts[$i];
             } else {
                 ${$param} = $default;
             }
             $i++;
         }
     }
     // get pack
     $pack = $s_packs->get_pack($pack_id);
     // membership_type -issue #1005
     if (empty($membership_type)) {
         $membership_type = $pack['membership_type'];
     }
     // user
     if ($user = get_userdata($user_id)) {
         //Purchase Another Membership Level problem : issue #: 752
         if ($is_another_membership_purchase == 'Y') {
             // another_subscription modification
             //issue #1073
             $member = mgm_get_member_another_purchase($user_id, $membership_type);
         } else {
             // get member
             $member = mgm_get_member($user_id);
         }
         //pack currency over rides genral setting currency - issue #1602
         if (isset($pack['currency']) && !empty($pack['currency'])) {
             $currency = $pack['currency'];
         } else {
             $currency = $system_obj->setting['currency'];
         }
         // check
         //uncommented the below line as it is not updating in upgrade subscription
         //if (!$member->duration) {
         $member->duration = $duration ? $duration : 1;
         // one year
         $member->duration_type = $duration_type ? $duration_type : 'y';
         $member->amount = 0.0;
         //$member->currency        = 'USD';//not sure y hardcoded
         $member->currency = $currency;
         $member->membership_type = $membership_type;
         //}
         // set pack
         $member->pack_id = $pack_id;
         $member->active_num_cycles = isset($num_cycles) && !empty($num_cycles) ? $num_cycles : $pack['num_cycles'];
         // set status
         $member->status = MGM_STATUS_ACTIVE;
         $member->account_desc = __('Free Account', 'mgm');
         $member->last_pay_date = '';
         //reset payment_info if already set:
         if (isset($member->payment_info)) {
             unset($member->payment_info);
         }
         //unset rebill:
         if (isset($member->rebilled)) {
             unset($member->rebilled);
         }
         //unset transaction_id:
         if (isset($member->transaction_id)) {
             unset($member->transaction_id);
         }
         // join date
         $time = time();
         // set
         if (!isset($member->join_date) || isset($member->join_date) && empty($member->join_date)) {
             $member->join_date = $time;
         }
         // old content hide - issue #1227
         if (isset($hide_old_content)) {
             $member->hide_old_content = $hide_old_content;
         }
         // type expanded
         $duration_exprs = $s_packs->get_duration_exprs();
         // if not lifetime/date range
         if (in_array($member->duration_type, array_keys($duration_exprs))) {
             // take only date exprs
             // @TODO, time should be last expire date #773, 3 use cases must be tracked
             // expect new param in tran subscription_type: new, upgrade, downgrade, extend
             $expire_date_ts = !$member->expire_date ? $time : strtotime($member->expire_date);
             // time
             $expire_date_ts = strtotime("+{$member->duration} {$duration_exprs[$member->duration_type]}", $expire_date_ts);
             // formatted
             $expire_date = date('Y-m-d', $expire_date_ts);
             // date extended
             if (!$member->expire_date || $expire_date_ts > strtotime($member->expire_date)) {
                 $member->expire_date = $expire_date;
             }
         } else {
             //if lifetime:
             if ($member->duration_type == 'l') {
                 // el = lifetime
                 $member->expire_date = '';
             }
             //issue #1096
             if ($member->duration_type == 'dr') {
                 // el = /date range
                 $member->expire_date = $duration_range_end_dt;
             }
         }
         //Purchase Another Membership Level problem : issue #: 752
         if (bool_from_yn($is_another_membership_purchase)) {
             $custom = array('is_another_membership_purchase' => 'Y');
         }
         // old status
         $old_status = $member->status;
         // set new status
         $member->status = $new_status = MGM_STATUS_ACTIVE;
         // whether to subscriber the user to Autoresponder - This should happen only once
         //issue #1073
         if (!empty($transid) && $transid != null) {
             $acknowledge_ar = mgm_subscribe_to_autoresponder($member, $transid);
         } else {
             $acknowledge_ar = mgm_subscribe_to_autoresponder($member, null);
         }
         // update
         if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
             // get object - issue #1227
             $obj_sp = mgm_get_class('subscription_packs')->get($member->pack_id);
             if ($obj_sp['hide_old_content']) {
                 $member->hide_old_content = $obj_sp['hide_old_content'];
             }
             mgm_save_another_membership_fields($member, $user_id);
             // Multiple membership upgrade: first time
             if ($transid && isset($custom['multiple_upgrade_prev_packid']) && is_numeric($custom['multiple_upgrade_prev_packid'])) {
                 mgm_multiple_upgrade_save_memberobject($custom, $transid);
             }
         } else {
             // update
             $member->save();
         }
         // on status - issue #1468
         switch ($member->status) {
             case MGM_STATUS_ACTIVE:
                 //sending notification email to user
                 if ($notify_user && $is_registration == 'Y') {
                     $user_pass = mgm_decrypt_password($member->user_password, $user_id);
                     do_action('mgm_register_user_notification', $user_id, $user_pass);
                 }
                 break;
         }
         // status change event
         do_action('mgm_user_status_change', $user_id, $new_status, $old_status, 'module_' . $this->module, $member->pack_id);
         //update coupon usage
         do_action('mgm_update_coupon_usage', array('user_id' => $user_id));
         // role
         if (isset($role)) {
             $obj_role = new mgm_roles();
             $obj_role->add_user_role($user_id, $role);
         }
         // update pack/transaction
         if (is_numeric($transid)) {
             mgm_update_transaction(array('module' => $this->module, 'status_text' => __('Success', 'mgm')), $transid);
         }
         // return action
         do_action('mgm_return_' . $this->module, array('user_id' => $user_id));
         // backward compatibility
         do_action('mgm_return_subscription_payment_' . $this->module, array('user_id' => $user_id));
         // new , individual
         do_action('mgm_return_subscription_payment', array('user_id' => $user_id, 'acknowledge_ar' => $acknowledge_ar, 'mgm_member' => $member));
         // new, global: pass mgm_member object to consider multiple level purchases as well.
     }
 }
/**
 * create purchase another button
 *
 * @param array userdata
 * @retun string html output
 */
function mgm_get_purchase_another_subscription_button($args = array())
{
    global $wpdb;
    //ceck settings
    $settings = mgm_get_class('system')->get_setting();
    // check
    if (!isset($settings['enable_multiple_level_purchase']) || isset($settings['enable_multiple_level_purchase']) && !bool_from_yn($settings['enable_multiple_level_purchase'])) {
        return;
    }
    // current user
    $user = wp_get_current_user();
    // validate
    if (!$user->ID) {
        // query string
        $user = mgm_get_user_from_querystring();
    }
    // validate
    if (!$user->ID) {
        return __('No such user', 'mgm');
    }
    // userdata
    $username = $user->user_login;
    $mgm_home = get_option('siteurl');
    $member = mgm_get_member($user->ID);
    $system_obj = mgm_get_class('system');
    $membership_type = mgm_get_user_membership_type($user->ID, 'code');
    $packs_obj = mgm_get_class('subscription_packs');
    $packs = $packs_obj->get_packs('upgrade');
    $duration_str = $packs_obj->duration_str;
    $trial_taken = $member->trial_taken;
    // pack_ids
    $pack_ids = mgm_get_members_packids($member);
    $pack_membership_types = mgm_get_subscribed_membershiptypes($user->ID, $member);
    // query_arg
    $form_action = mgm_get_custom_url('transactions', false, array('action' => 'purchase_another', 'username' => $username));
    //issue 1009
    if (isset($settings['membership_details_url'])) {
        $membership_details_url = $settings['membership_details_url'];
    } else {
        $membership_details_url = get_admin_url() . 'profile.php?page=mgm/profile';
    }
    // cancel
    $cancel_url = $membership_details_url;
    // $cancel_url = mgm_get_custom_url('membership_details');
    // active modules
    $a_payment_modules = $system_obj->get_active_modules('payment');
    // 	selected_subscription
    $selected_subs = mgm_get_selected_subscription($args);
    // second step, after post
    if (isset($_POST['submit'])) {
        // verify selected
        if (!isset($_POST['subs_opt'])) {
            // die
            return sprintf(__('Package not selected, <a href="%s">go back</a>.', 'mgm'), $_POST['form_action']);
            exit;
        }
        // get subs data
        $subs_opt_pack = mgm_decode_package($_POST['subs_opt']);
        extract($subs_opt_pack);
        // check
        $valid = false;
        // loop packs
        foreach ($packs as $pack) {
            // check
            //check pack id as well: issue#: 580
            if ($pack['cost'] == $cost && $pack['duration'] == $duration && $pack['duration_type'] == $duration_type && $membership_type == $pack['membership_type'] && $pack_id == $pack['id']) {
                $valid = true;
                break;
            }
        }
        // error
        if (!$valid) {
            return __('Invalid data passed', 'mgm');
            exit;
        }
        // get object
        $member = new mgm_member($user->ID);
        $temp_membership = $member->_default_fields();
        $temp_membership['membership_type'] = $membership_type;
        $temp_membership['pack_id'] = $pack_id;
        //issue #860
        //if (isset($_POST['mgm_upgrade_field']['autoresponder']) && ($_POST['mgm_upgrade_field']['autoresponder'])=='Y') {
        if (isset($_POST['mgm_upgrade_field']['autoresponder']) && substr($_POST['mgm_upgrade_field']['autoresponder'], 0, 1) == 'Y') {
            $temp_membership['subscribed'] = 'Y';
            $temp_membership['autoresponder'] = $system_obj->active_modules['autoresponder'];
        }
        //issue #1236
        if (isset($_POST['mgm_upgrade_field']['coupon']) && !empty($_POST['mgm_upgrade_field']['coupon'])) {
            //issue #1250 - Coupon validation
            if (!empty($_POST['form_action'])) {
                // check if its a valid coupon
                if (!($coupon = mgm_get_coupon_data($_POST['mgm_upgrade_field']['coupon']))) {
                    //redirect back to the form
                    $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'error_field_value' => $_POST['mgm_upgrade_field']['coupon']);
                    $redirect = add_query_arg($q_arg, $_POST['form_action']);
                    // redirect
                    mgm_redirect($redirect);
                    exit;
                } else {
                    // membership type check
                    // get subs
                    if ($subs_pack = mgm_decode_package(mgm_post_var('subs_opt'))) {
                        // values
                        $coupon_values = mgm_get_coupon_values(NULL, $coupon['value'], true);
                        // check
                        if (isset($coupon_values['new_membership_type']) && $coupon_values['new_membership_type'] != $subs_pack['membership_type']) {
                            $new_membership_type = mgm_get_membership_type_name($coupon_values['new_membership_type']);
                            $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'membership_type' => $coupon_values['new_membership_type'], 'error_field_value' => $_POST['mgm_upgrade_field']['coupon']);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            // redirect
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                }
            }
        }
        //inserted an incomplete entry for the selected subscription type
        mgm_save_another_membership_fields($temp_membership, $user->ID);
        // save coupon fields and update member object
        $member = mgm_save_partial_fields_purchase_more($user->ID, $membership_type, $cost);
        // coupon
        $purchase_another_coupon = false;
        // array
        if (isset($member->upgrade)) {
            if (is_array($member->upgrade) && isset($member->upgrade['coupon']['id'])) {
                $purchase_another_coupon = $member->upgrade['coupon'];
            } elseif (is_object($member->upgrade) && isset($member->upgrade->coupon->id)) {
                $purchase_another_coupon = mgm_object2array($member->upgrade->coupon);
            }
            // coupon
            mgm_get_purchase_another_coupon_pack($purchase_another_coupon, $pack);
        }
        //save custom fields -issue #1285
        if (isset($_POST['mgm_upgrade_field']) && !empty($_POST['mgm_upgrade_field'])) {
            //member
            $cf_member = mgm_get_member($user->ID);
            //upgrade custom fileds
            $cfu_fileds = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_multiple_membership_level_purchase' => true)));
            //loop fields
            foreach ($cfu_fileds as $cf_filed) {
                //skip coupon and autoresponder
                if (in_array($cf_filed['name'], array('coupon', 'autoresponder'))) {
                    continue;
                }
                //check
                if (isset($_POST['mgm_upgrade_field'][$cf_filed['name']])) {
                    // check upgrae and required
                    if ((bool) $cf_filed['attributes']['required'] === true) {
                        if (empty($_POST['mgm_upgrade_field'][$cf_filed['name']])) {
                            //redirect back to the form
                            $q_arg = array('error_field' => $cf_filed['label'], 'error_type' => 'empty', 'error_field_value' => $_POST['mgm_upgrade_field'][$cf_filed['name']]);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                    //appending custom fields
                    if (isset($cf_member->custom_fields->{$cf_filed}['name'])) {
                        $cf_member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                    } else {
                        $cf_member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                    }
                }
            }
            $cf_member->save();
        }
        // start html
        $html = '<div>';
        // free
        if (($pack['cost'] == 0 || $membership_type == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->is_enabled()) {
            $html .= sprintf('<div>%s - %s</div>', __('Create a free account ', 'mgm'), ucwords($membership_type));
            $module = 'mgm_free';
            // payments url
            $payments_url = mgm_get_custom_url('transactions');
            // if tril module selected and cost is 0 and free moduleis not active
            if ($membership_type == 'trial') {
                if (in_array('mgm_trial', $a_payment_modules)) {
                    $module = 'mgm_trial';
                }
            }
            //Purchase Another Membership Level problem : issue #: 752
            $redirect = add_query_arg(array('method' => 'payment_return', 'module' => $module, 'custom' => $user->ID . '_' . $duration . '_' . $duration_type . '_' . $pack_id . '_Y', 'redirector' => $redirector), $payments_url);
            // redirect
            if (!headers_sent()) {
                @header('location: ' . $redirect);
                exit;
            }
            // js redirect
            $html .= sprintf('<script type="text/javascript">window.location = "%s";</script><div>%s</div>', $redirect, $packs_obj->get_pack_desc($pack));
        } else {
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $packs_obj->get_pack_desc($pack));
            // coupon
            if (isset($purchase_another_coupon['id'])) {
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', sprintf(__('Using Coupon "%s" - %s', 'mgm'), $purchase_another_coupon['name'], $purchase_another_coupon['description']));
            }
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('Please Select from Available Payment Gateways', 'mgm'));
        }
        //bypass if payment gateway field is selected -issue #1764
        if ((double) $pack['cost'] > 0 && isset($_POST['mgm_payment_gateways']) && !empty($_POST['mgm_payment_gateways'])) {
            //init
            $tran_id = 0;
            if (!$tran_id) {
                $tran_id = mgm_add_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
            }
            // module
            $mod_obj = mgm_get_module($_POST['mgm_payment_gateways'], 'payment');
            // module end point
            $redirect = $mod_obj->_get_endpoint('html_redirect', false);
            // encode id:
            //encode transaction id
            $encode_tran_id = mgm_encode_id($tran_id);
            //args
            $redirect = add_query_arg(array('tran_id' => $encode_tran_id), $redirect);
            // do the redirect to payment
            mgm_redirect($redirect);
        }
        // init
        $payment_modules = array();
        // when active
        if ($a_payment_modules) {
            // loop
            foreach ($a_payment_modules as $payment_module) {
                // not trial
                if (in_array($payment_module, array('mgm_free', 'mgm_trial'))) {
                    continue;
                }
                //consider only the modules assigned to pack
                if (isset($pack['modules']) && !in_array($payment_module, (array) $pack['modules'])) {
                    continue;
                }
                // store
                $payment_modules[] = $payment_module;
            }
        }
        // loop payment mods if not free
        if (count($payment_modules) && $cost) {
            // transaction
            $tran_id = 0;
            // loop
            foreach ($payment_modules as $module) {
                // module
                $mod_obj = mgm_get_module($module, 'payment');
                // create transaction
                // if(!$tran_id) $tran_id = $mod_obj->_create_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
                if (!$tran_id) {
                    $tran_id = mgm_add_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
                }
                // button
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $mod_obj->get_button_subscribe(array('pack' => $pack, 'tran_id' => $tran_id)));
            }
        } else {
            if ($cost) {
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('There are no payment gateways available at this time.', 'mgm'));
            }
        }
        // html
        $html .= '</div>';
    } else {
        // first step show upgrade options
        // html
        $html = sprintf('<p class="message register">%s</p>', __('Please Select from Available Membership Packages', 'mgm'));
        // upgrade_packages
        $upgrade_packages = '';
        // pack to modules
        $pack_modules = array();
        // loop
        foreach ($packs as $pack) {
            // default
            $checked = '';
            // skip already purchased packs
            if (in_array($pack['id'], $pack_ids)) {
                continue;
            }
            //skip same membership level subscriptions
            if (in_array($pack['membership_type'], $pack_membership_types)) {
                continue;
            }
            // do not show trial or free as upgradre
            if ($pack['membership_type'] == 'trial' || $pack['membership_type'] == 'free') {
                continue;
            }
            // reset
            $checked = mgm_select_subscription($pack, $selected_subs);
            // skip other when a package sent as selected
            if ($selected_subs !== false) {
                if (empty($checked)) {
                    continue;
                }
            }
            // checked
            if (!$checked) {
                $checked = (int) $pack['default'] == 1 ? ' checked="checked"' : '';
            }
            // duration
            if ($pack['duration'] == 1) {
                $dur_str = rtrim($duration_str[$pack['duration_type']], 's');
            } else {
                $dur_str = $duration_str[$pack['duration_type']];
            }
            $css_group = mgm_get_css_group();
            // encode pack
            $subs_opt_enc = mgm_encode_package($pack);
            // set
            $pack_modules[$subs_opt_enc] = $pack['modules'];
            //issue #867
            if ($css_group != 'none') {
                //expand this if needed
                $css_link_format = '<link rel="stylesheet" href="%s" type="text/css" media="all" />';
                $css_file = MGM_ASSETS_URL . 'css/' . $css_group . '/mgm.form.fields.css';
                $upgrade_packages .= sprintf($css_link_format, $css_file);
            }
            // free
            if (($pack['cost'] == 0 || strtolower($pack['membership_type']) == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->enabled == 'Y') {
                // input
                $input = sprintf('<input type="radio" %s class="checkbox" name="subs_opt" value="%s" rel="mgm_subscription_options"/>', $checked, $subs_opt_enc);
                // html
                $upgrade_packages .= '  
							<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
								<div class="mgm_subs_option ' . $pack['membership_type'] . '">
									' . $input . '
								</div>
								<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
									' . $packs_obj->get_pack_desc($pack) . '
								</div>
								 <div class="clearfix"></div>
								 <div class="mgm_subs_desc ' . $pack['membership_type'] . '">
									' . mgm_stripslashes_deep($pack['description']) . '
								 </div>
							</div>';
            } else {
                // input
                $input = sprintf('<input type="radio" %s class="checkbox" name="subs_opt" value="%s" rel="mgm_subscription_options"/>', $checked, $subs_opt_enc);
                // html
                $upgrade_packages .= '  
							<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
								<div class="mgm_subs_option ' . $pack['membership_type'] . '">
									' . $input . '
								</div>
								<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
									' . $packs_obj->get_pack_desc($pack) . '
								</div>
								 <div class="clearfix"></div>
								 <div class="mgm_subs_desc ' . $pack['membership_type'] . '">
									' . mgm_stripslashes_deep($pack['description']) . '
								 </div>
							</div>';
            }
        }
        // add pack_modules as json data, may consider jquery data later
        if (!empty($pack_modules)) {
            $html .= sprintf('<script language="javascript">var mgm_pack_modules = %s</script>', json_encode($pack_modules));
        }
        // show error
        if (!$upgrade_packages) {
            // html
            $html .= '<div class="mgm_subs_wrapper">
						<div class="mgm_subs_pack_desc">
							' . __('Sorry, no packages available.', 'mgm') . '
						</div>
					 </div>
					 <p>						
						<input type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '" class="button-primary" />&nbsp;					
					 </p>';
        } else {
            /*			$error_field = mgm_request_var('error_field'); 
            			if(!empty($error_field)) {
            				$errors = new WP_Error();
            				switch (mgm_request_var('error_type')) {
            					case 'empty':
            						$error_string = 'You must provide a ';
            						break;
            					case 'invalid':
            						$error_string = 'Invalid ';
            						break;	
            				}				
            				//issue #703
            				$errors->add( $error_field, __( '<strong>ERROR</strong>: '.$error_string, 'mgm' ).$error_field );
            				$html .= mgm_set_errors($errors, true);					
            			}*/
            // check errors if any:
            $html .= mgm_subscription_purchase_errors();
            // form
            $html .= '<form action="' . $form_action . '" method="post" class="mgm_form"><div class="mgm_get_pack_form_container">';
            $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
            $html .= $upgrade_packages;
            //issue #1285
            $html .= mgm_get_custom_fields($user->ID, array('on_multiple_membership_level_purchase' => true), 'mgm_upgrade_field');
            // html
            $html .= '<input type="hidden" name="ref" value="' . md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type) . '" />';
            // set
            $html .= '<p>						
						<input class="button" type="submit" name="submit" value="' . __('Next', 'mgm') . '" />&nbsp;&nbsp;
						<input class="button" type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '"/>&nbsp;					
					  </p>';
            // html
            $html .= '</div></form>';
        }
    }
    // return
    return $html;
}
/**
 * check membership rebill status
 * @todo should only run on users who are using a payment module with rebill support
 * add _mgm_module_has_rebill_status_check='Y' in usermeta
 */
function mgm_check_membership_rebill_status()
{
    global $wpdb;
    // flag
    $paged_fetch = false;
    // check user with meta only
    // if( ($a_users = mgm_get_users_with_meta('_mgm_module_has_rebill_status_check','Y')) === FALSE ){
    // 		// old fetch
    // 		// $a_users = mgm_get_users_for_rebill_status_check('fetch');
    // 		$a_users = mgm_get_users_for_cron_check('fetch', 'rebill_status');
    // 		// flag
    // 		$paged_fetch = true;
    // 	}
    // fetch on meta, with rebill check module only
    $a_users = mgm_get_users_with_meta('_mgm_module_has_rebill_status_check', 'Y');
    // current time
    $current_date = mgm_get_current_datetime('Y-m-d H:i:s');
    // with time part #1023 issue
    // log
    // mgm_log($a_users, __FUNCTION__);
    // loop
    if ($a_users) {
        // objects
        $spacks_obj = mgm_get_class('subscription_packs');
        // $mtypes_obj = mgm_get_class('membership_types');
        $duration_exprs = $spacks_obj->get_duration_exprs();
        $checked = $offset = 0;
        // define
        if (!defined('DOING_QUERY_REBILL_STATUS')) {
            define('DOING_QUERY_REBILL_STATUS', 'cron');
        }
        // loop
        foreach ($a_users as $user) {
            // set limit
            @set_time_limit(300);
            //300s
            @ini_set('memory_limit', 134217728);
            // 128M
            // get member
            $member = mgm_get_member($user->ID);
            // get rebill cycle
            if ((int) $member->pack_id > 0) {
                // get member subscribed  pack
                $pack = $spacks_obj->get_pack($member->pack_id);
                // member pack cycle
                $num_cycles = isset($member->active_num_cycles) && !empty($member->active_num_cycles) ? (int) $member->active_num_cycles : (int) $pack['num_cycles'];
                // lifetime ongoing/fixed cycle ongoing
                if ($num_cycles == 0 || $num_cycles > 1 && (int) $member->rebilled < (int) $num_cycles) {
                    // 100 to dynamic
                    // when current date is later than expire date, we will run rebill check after expire date, not before
                    // payment status available after scheduled transaction date
                    if (strtotime($current_date['date']) > strtotime($member->expire_date)) {
                        // check already run
                        if (!isset($member->last_payment_check_date) || isset($member->last_payment_check_date) && $current_date['date'] != $member->last_payment_check_date) {
                            // apply rebill filter
                            if (apply_filters('mgm_module_rebill_status', $user->ID, $member)) {
                                // success
                                $checked++;
                            }
                        }
                        // update type
                        mgm_update_payment_check_state($user->ID, 'cron');
                    }
                }
            }
            // unset
            unset($member);
            // increase $offset
            $offset++;
        }
    }
    // update
    if ($paged_fetch) {
        // mgm_get_users_for_rebill_status_check('update', $offset);
        mgm_get_users_for_cron_check('update', 'rebill_status', $offset);
    }
}
 /**
  * Cancel Recurring Subscription
  *
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $subscr_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
 {
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             $subscr_id = null;
             if (!empty($member->payment_info->subscr_id)) {
                 $subscr_id = $member->payment_info->subscr_id;
             } elseif (!empty($member->pack_id)) {
                 //check the pack is recurring
                 $s_packs = mgm_get_class('subscription_packs');
                 $sel_pack = $s_packs->get_pack($member->pack_id);
                 if ($sel_pack['num_cycles'] != 1) {
                     $subscr_id = 0;
                 }
                 // 0 stands for a lost subscription id
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 // mgm_log('RECALLing '. $member->payment_info->module .': cancel_recurring_subscription FROM: ' . $this->code);
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     }
     //ony for subscription_purchase
     if ($subscr_id) {
         $user = get_userdata($user_id);
         $format = mgm_get_date_format('date_format');
         // compose post body
         $post_data = array('USER' => $this->setting['username'], 'PWD' => $this->setting['password'], 'SIGNATURE' => $this->setting['signature'], 'VERSION' => '64.0', 'METHOD' => 'ManageRecurringPaymentsProfileStatus', 'PROFILEID' => $subscr_id, 'ACTION' => 'Cancel', 'NOTE' => sprintf('Cancellation selected by member on UPGRADE: "%s", ID: %d on: %s', $user->user_email, $user->ID, date($format)));
         // end point url
         $end_point = $this->_get_endpoint();
         //issue #1508
         $url_parsed = parse_url($end_point);
         // domain/host
         $domain = $url_parsed['host'];
         // headers
         $http_headers = array('POST /cgi-bin/webscr HTTP/1.1\\r\\n', 'Content-Type: application/x-www-form-urlencoded\\r\\n', 'Host: ' . $domain . '\\r\\n', 'Connection: close\\r\\n\\r\\n');
         // post
         $http_response = mgm_remote_post($end_point, $post_data, array('headers' => $http_headers, 'timeout' => 30, 'sslverify' => false));
         // log
         mgm_log($http_response, __FUNCTION__);
         // fields
         // $fields = mgm_http_build_query($post_data);
         // post
         // $response = $this->_curl_post($endpoint, $fields, '', false);
         // sleep
         sleep(1);
         // parse
         $this->response = array();
         // parse to array
         parse_str($http_response, $this->response);
         // log
         mgm_log($this->response, __FUNCTION__);
         // cancel
         return isset($this->response['ACK']) && $this->response['ACK'] == 'Success' ? true : false;
     } elseif ($subscr_id === 0) {
         //send email to admin if subscription Id is absent
         $system_obj = mgm_get_class('system');
         $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
         //send email only if setting enabled
         if (!$dge) {
             // blog
             $blogname = get_option('blogname');
             // user
             $user = get_userdata($user_id);
             // notify admin
             mgm_notify_admin_membership_cancellation_manual_removal_required($blogname, $user, $member);
         }
         return true;
     }
     return false;
 }
Exemplo n.º 18
0
 function _buy_membership()
 {
     // system
     $system_obj = mgm_get_class('system');
     $s_packs = mgm_get_class('subscription_packs');
     $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
     $dpne = bool_from_yn($system_obj->get_setting('disable_payment_notify_emails'));
     // get passthrough, stop further process if fails to parse
     $custom = $this->_get_transaction_passthrough($_POST['custom']);
     // local var
     extract($custom);
     // currency
     if (!$currency) {
         $currency = $system_obj->get_setting('currency');
     }
     // find user
     $user = get_userdata($user_id);
     //another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // Get the current AC join date
     if (!($join_date = $member->join_date)) {
         $member->join_date = time();
     }
     // Set current AC join date
     // if there is no duration set in the user object then run the following code
     if (empty($duration_type)) {
         //if there is no duration type then use Months
         $duration_type = 'm';
     }
     // membership type default
     if (empty($membership_type)) {
         //if there is no account type in the custom string then use the existing type
         $membership_type = md5($member->membership_type);
     }
     // validate parent method
     $membership_type_verified = $this->_validate_membership_type($membership_type, 'md5|plain');
     // verified
     if (!$membership_type_verified) {
         if (strtolower($member->membership_type) != 'free') {
             // notify admin, only if gateway emails on
             if (!$dge) {
                 mgm_notify_admin_membership_verification_failed($this->name);
             }
             // abort
             return;
         } else {
             $membership_type_verified = $member->membership_type;
         }
     }
     // set
     $membership_type = $membership_type_verified;
     // sub pack
     $subs_pack = $s_packs->get_pack($pack_id);
     // if trial on
     if ($subs_pack['trial_on']) {
         $member->trial_on = $subs_pack['trial_on'];
         $member->trial_cost = $subs_pack['trial_cost'];
         $member->trial_duration = $subs_pack['trial_duration'];
         $member->trial_duration_type = $subs_pack['trial_duration_type'];
         $member->trial_num_cycles = $subs_pack['trial_num_cycles'];
     }
     //pack currency over rides genral setting currency - issue #1602
     if (isset($subs_pack['currency']) && $subs_pack['currency'] != $currency) {
         $currency = $subs_pack['currency'];
     }
     // duration
     $member->duration = $duration;
     $member->duration_type = strtolower($duration_type);
     $member->amount = $amount;
     $member->currency = $currency;
     $member->membership_type = $membership_type;
     $member->pack_id = $pack_id;
     // $member->payment_type = 'subscription';
     $member->active_num_cycles = isset($num_cycles) && !empty($num_cycles) ? $num_cycles : $subs_pack['num_cycles'];
     $member->payment_type = (int) $member->active_num_cycles == 1 ? 'one-time' : 'subscription';
     // payment info for unsubscribe
     $member->payment_info = new stdClass();
     $member->payment_info->module = $this->code;
     // transaction type
     $member->payment_info->txn_type = 'subscription';
     // subscriber id
     $member->payment_info->subscr_id = '';
     // refer id
     $member->payment_info->txn_id = '';
     // mgm transaction id
     $member->transaction_id = $_POST['custom'];
     // process response
     $new_status = $update_role = false;
     // process
     $process = 'Success';
     // status
     switch ($process) {
         case 'Success':
             // set pending status
             $new_status = MGM_STATUS_PENDING;
             // starus string
             $member->status_str = __('Last payment is pending', 'mgm');
             $time = time();
             $last_pay_date = isset($member->last_pay_date) ? $member->last_pay_date : null;
             $member->last_pay_date = date('Y-m-d', $time);
             // for upgrading
             if ($member->status == MGM_STATUS_ACTIVE) {
                 // mark for later status reset
                 $member->status_reset_on = date('Y-m-d', strtotime($member->expire_date));
             }
             // check subscription_option
             if (isset($subscription_option)) {
                 // on option
                 switch ($subscription_option) {
                     // @ToDo, apply expire date login
                     case 'create':
                         // expire date will be based on current time
                     // expire date will be based on current time
                     case 'upgrade':
                         // expire date will be based on current time
                         // already on top
                         break;
                     case 'downgrade':
                         // expire date will be based on expire_date if exists, current time other wise
                     // expire date will be based on expire_date if exists, current time other wise
                     case 'extend':
                         // expire date will be based on expire_date if exists, current time other wise
                         // extend/expire date
                         // calc expiry	- issue #1226
                         // membership extend functionality broken if we try to extend the same day so removed && $last_pay_date != date('Y-m-d', $time) check
                         if (!empty($member->expire_date)) {
                             $expiry = strtotime($member->expire_date);
                             if ($expiry > 0 && $expiry > $time) {
                                 $time = $expiry;
                             }
                         }
                         break;
                 }
             }
             // type expanded
             $duration_exprs = $s_packs->get_duration_exprs();
             // if not lifetime/date range
             if (in_array($member->duration_type, array_keys($duration_exprs))) {
                 // take only date exprs
                 //consider trial duration if trial period is applicable
                 if (isset($trial_on) && $trial_on == 1) {
                     //Do it only once
                     if (!isset($member->rebilled) && isset($member->active_num_cycles) && $member->active_num_cycles != 1) {
                         $time = strtotime("+{$trial_duration} {$duration_exprs[$trial_duration_type]}", $time);
                     }
                 } else {
                     // time - issue #1068
                     $time = strtotime("+{$member->duration} {$duration_exprs[$member->duration_type]}", $time);
                 }
                 // formatted
                 $time_str = date('Y-m-d', $time);
                 // date extended
                 if (!$member->expire_date || strtotime($time_str) > strtotime($member->expire_date)) {
                     $member->expire_date = $time_str;
                 }
             } else {
                 //if lifetime:
                 if ($member->duration_type == 'l') {
                     // el = lifetime
                     $member->expire_date = '';
                 }
                 //issue #1096
                 if ($member->duration_type == 'dr') {
                     // el = /date range
                     $member->expire_date = $duration_range_end_dt;
                 }
             }
             //update rebill: issue #: 489
             if ($member->active_num_cycles != 1 && (int) $member->rebilled < (int) $member->active_num_cycles) {
                 // rebill
                 $member->rebilled = !$member->rebilled ? 1 : (int) $member->rebilled + 1;
             }
             // role update
             if ($role) {
                 $update_role = true;
             }
             // transaction_id
             $transaction_id = $this->_get_transaction_id();
             // hook args
             $args = array('user_id' => $user_id, 'transaction_id' => $transaction_id);
             // another membership
             if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
                 $args['another_membership'] = $custom['membership_type'];
             }
             // after succesful payment hook
             do_action('mgm_membership_transaction_success', $args);
             // backward compatibility
             do_action('mgm_subscription_purchase_payment_success', $args);
             // new organized name
             do_action('mgm_return_subscription_payment_' . $this->module, $args);
             // autoresponder
             break;
         case 'Denied':
             $new_status = MGM_STATUS_NULL;
             $member->status_str = __('Last payment was refunded or denied', 'mgm');
             break;
         case 'Pending':
             $new_status = MGM_STATUS_PENDING;
             $reason = 'Unknown';
             $member->status_str = sprintf(__('Last payment is pending. Reason: %s', 'mgm'), $reason);
             break;
         default:
             $new_status = MGM_STATUS_ERROR;
             $member->status_str = sprintf(__('Last payment status: %s', 'mgm'), $_POST['payment_status']);
             break;
     }
     // old status
     $old_status = $member->status;
     // set new status
     $member->status = $new_status;
     // whether to acknowledge the user - This should happen only once
     $acknowledge_user = $this->send_payment_email($_POST['custom']);
     // whether to subscriber the user to Autoresponder - This should happen only once
     $acknowledge_ar = mgm_subscribe_to_autoresponder($member, $_POST['custom']);
     //another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         //issue #1227
         if ($subs_pack['hide_old_content']) {
             $member->hide_old_content = $subs_pack['hide_old_content'];
         }
         mgm_save_another_membership_fields($member, $user_id);
         // Multiple membership upgrade: first time
         if (isset($member->transaction_id) && isset($custom['multiple_upgrade_prev_packid']) && is_numeric($custom['multiple_upgrade_prev_packid'])) {
             mgm_multiple_upgrade_save_memberobject($custom, $member->transaction_id);
         }
     } else {
         $member->save();
     }
     // status change event
     do_action('mgm_user_status_change', $user_id, $new_status, $old_status, 'module_' . $this->module, $member->pack_id);
     //update coupon usage
     do_action('mgm_update_coupon_usage', array('user_id' => $user_id));
     // role
     if ($update_role) {
         $obj_role = new mgm_roles();
         $obj_role->add_user_role($user_id, $role);
     }
     // update transaction
     if (is_numeric($member->transaction_id)) {
         mgm_update_transaction(array('module' => $this->module, 'status' => $member->status, 'status_text' => $member->status_str), $member->transaction_id);
     }
     // return action
     do_action('mgm_return_' . $this->module, array('user_id' => $user_id));
     // backward compatibility
     do_action('mgm_return_subscription_payment_' . $this->module, array('user_id' => $user_id));
     // new , individual
     do_action('mgm_return_subscription_payment', array('user_id' => $user_id, 'acknowledge_ar' => $acknowledge_ar, 'mgm_member' => $member));
     // new, global
     // read member again for internal updates if any
     // another_subscription modification
     if (isset($custom['is_another_membership_purchase']) && bool_from_yn($custom['is_another_membership_purchase'])) {
         $member = mgm_get_member_another_purchase($user_id, $custom['membership_type']);
     } else {
         $member = mgm_get_member($user_id);
     }
     // send email notification to client
     $blogname = get_option('blogname');
     // notify
     if ($acknowledge_user) {
         // notify user, only if gateway emails on
         if (!$dpne) {
             // notify
             if (mgm_notify_user_membership_purchase($blogname, $user, $member, $custom, $subs_pack, $s_packs, $system_obj)) {
                 // update as email sent
                 $this->update_paymentemail_sent($alt_tran_id);
             }
         }
         // notify admin, only if gateway emails on
         if (!$dge) {
             // pack duration
             $pack_duration = $s_packs->get_pack_duration($subs_pack);
             // notify admin,
             mgm_notify_admin_membership_purchase($blogname, $user, $member, $pack_duration);
         }
     }
 }
Exemplo n.º 19
0
 function _expire_membership($user_id)
 {
     // member
     $member = mgm_get_member($user_id);
     // old status
     $old_status = $member->status;
     // set new status
     $member->status = $new_status = MGM_STATUS_EXPIRED;
     // status string
     $member->status_str = __('Last payment cycle expired', 'mgm');
     // save
     $member->save();
     // action
     do_action('mgm_user_status_change', $user_id, $new_status, $old_status, 'module_' . $this->module, $member->pack_id);
 }
Exemplo n.º 20
0
 function _do_import_users()
 {
     //test
     global $wpdb;
     // extract
     extract($_POST);
     // import f*g
     define('MGM_DOING_USERS_IMPORT', TRUE);
     // parese
     $i_response = $this->_parse_import_file();
     // log
     // mgm_log($response, __FUNCTION__);
     // stop
     // $response['status'] = 'error';
     // process data:
     if ($i_response['status'] == 'success' && in_array('user_email', $i_response['header'])) {
         // success
         // extract
         $i_users = $i_response['users'];
         $i_header = $i_response['header'];
         // object
         $mgm_packs = mgm_get_class('mgm_subscription_packs');
         $mgm_roles = mgm_get_class('mgm_roles');
         // types
         $membership_types = mgm_get_class('membership_types')->get_membership_types();
         $memtypes = mgm_get_class('membership_types');
         // check users
         if (!empty($i_users)) {
             // users found
             // init
             $row_count = count($i_users);
             $col_count = count($i_header);
             // limits
             $row_limit = 2000;
             $user_count = 0;
             // log
             // mgm_log(sprintf('Rows: [%d] Cols: [%d]',$row_count, $col_count), __FUNCTION__);
             // user fields
             $user_fields = array('first_name', 'last_name', 'user_nicename', 'user_url', 'display_name', 'nickname', 'user_firstname', 'user_lastname', 'user_description', 'user_registered');
             // flag
             $update_count = $user_count = 0;
             // new users
             $new_users = array();
             $specialchars = array(',', '\'', '"', "\n\r", "\n", '\\', '/', '$', '`', '(', ')', ' ', " ");
             // custom fields
             $cf_register_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true, 'on_profile' => true)));
             // count
             $cf_count = count($cf_register_page);
             // exclude
             $cf_exclude_names = array('subscription_introduction', 'subscription_options', 'terms_conditions', 'privacy_policy', 'description', 'payment_gateways', 'password_conf', 'autoresponder');
             // types
             $cf_exclude_types = array('html', 'label', 'captcha');
             // loop
             foreach ($i_users as $i_user) {
                 // init
                 $update_user = $insert_user = $is_membership_update = $is_multiple_membership_update = $multiple_membership_exists = $update_role = false;
                 // pack
                 $pack = array();
                 // increment
                 $user_count++;
                 // remove N/A ?
                 // $i_user = str_ireplace('N/A', '', $i_user);
                 // init
                 // id
                 $id = isset($i_user['ID']) && is_numeric($i_user['ID']) ? $i_user['ID'] : '';
                 $email = str_replace($specialchars, '', sanitize_email($i_user['user_email']));
                 $user_login = str_replace($specialchars, '', sanitize_user($i_user['user_login']));
                 $user_password = isset($i_user['user_password']) ? $i_user['user_password'] : '';
                 // Issue #1559: Standardize membership type name to use machine name
                 $membership_type = $memtypes->get_type_code($i_user['membership_type']);
                 $pack_id = isset($i_user['pack_id']) ? sanitize_user($i_user['pack_id']) : '';
                 // log
                 // mgm_log(sprintf('step 1: user_count: [%d] id: [%s] email: [%s] user_login: [%s] user_password: [%s]', $user_count, $id, $email, $user_login, $user_password), __FUNCTION__);
                 // user id not valid
                 if (!is_numeric($id)) {
                     // check login/email
                     if (!empty($user_login) && !empty($email)) {
                         // user
                         $_user = get_user_by('login', $user_login);
                         // if update and different email
                         if (isset($_user->ID) && $_user->user_email != $email) {
                             // log
                             // mgm_log(sprintf('step 2: %s %s', $_user->user_email, $email), __FUNCTION__);
                             // continue
                             continue;
                         }
                         // fresh insert/registration:
                         if (!$_user) {
                             // password
                             $user_password = !empty($user_password) ? $user_password : wp_generate_password();
                             $user_password = str_replace($specialchars, '', $user_password);
                             // trim
                             $user_password = trim($user_password);
                             // log
                             // mgm_log('step 2.1 user_password: '******'step 3: %s, %s ', $user_password, $id), __FUNCTION__);
                             // check error
                             if (is_wp_error($id)) {
                                 // log
                                 // mgm_log(sprintf('step 4: %s', print_r($id->get_error_messages(),1)), __FUNCTION__);
                                 // unset
                                 unset($id);
                                 // continue
                                 continue;
                             }
                             // set new user
                             $new_users[$id]['email'] = $email;
                             $new_users[$id]['user_login'] = $user_login;
                             // update option
                             update_user_option($id, 'default_password_nag', true, true);
                             // flag
                             $insert_user = true;
                         } else {
                             // set id to user
                             $id = $_user->ID;
                         }
                         // unset
                         unset($_user);
                     } else {
                         // login/email not present
                         // log
                         // mgm_log(sprintf('step 5: %s, %s ', $user_login, $email), __FUNCTION__);
                         // continue
                         continue;
                         //skip the record
                     }
                 } else {
                     // update
                     $update_user = true;
                 }
                 // get User object:
                 $user = new WP_user($id);
                 // log
                 // mgm_log(sprintf('step 6: %s ', print_r($user,1)), __FUNCTION__);
                 //issue #700
                 $format = mgm_get_date_format('date_format_short');
                 // ------------------------------------------
                 // user to mgm member
                 if (isset($user->ID) && $user->ID > 0) {
                     // get mgm object:
                     $member = mgm_get_member($user->ID);
                     // update custom fields:
                     if (!empty($member)) {
                         // update pack id if not supplied and already exists
                         // This is to make pack_id optional: issue#: 807
                         if (!is_numeric($pack_id) && isset($member->pack_id) && $member->pack_id > 0) {
                             $pack_id = $member->pack_id;
                         }
                         // update misc fields:
                         if (!isset($member->rss_token) || isset($member->rss_token) && empty($member->rss_token)) {
                             $member->rss_token = mgm_create_rss_token();
                         }
                         // init
                         $user_password_enc = mgm_encrypt_password($user_password, $user->ID, $member->rss_token);
                         // mgm_log($user_password_enc, __FUNCTION__);
                         // check
                         if ($cf_count > 0) {
                             // loop custom fields
                             foreach ($cf_register_page as $field) {
                                 // key
                                 $key = $field['name'];
                                 // mgm_log($key, __FUNCTION__);
                                 // skip unwanted fields
                                 if (in_array($field['name'], $cf_exclude_names) || in_array($field['type'], $cf_exclude_types)) {
                                     // log
                                     // mgm_log(sprintf('step 7: %s ', $field['name']), __FUNCTION__);
                                     // continue
                                     continue;
                                 }
                                 // init
                                 $val = '';
                                 //issue #700
                                 // check
                                 if (isset($i_user[$key]) && !empty($i_user[$key]) && preg_match('/date/i', $key)) {
                                     // validate date
                                     if (mgm_is_valid_date($i_user[$key]) && mgm_format_inputdate_to_mysql($i_user[$key], $format)) {
                                         $val = $i_user[$key];
                                     }
                                 } elseif ($key == 'email') {
                                     // email and username custom fields
                                     $val = $email;
                                 } elseif ($key == 'username') {
                                     // username
                                     $val = $user_login;
                                 } elseif ($key == 'password') {
                                     // password
                                     if (!empty($user_password_enc)) {
                                         // set
                                         $val = $user_password_enc;
                                         // log
                                         // mgm_log(sprintf('step 7.1: %s ', $user_password_enc), __FUNCTION__);
                                     }
                                 } else {
                                     $val = isset($i_user[$key]) ? $i_user[$key] : '';
                                 }
                                 // If checkbox, then serialize the value: Issue #1070
                                 if ($field['type'] == 'checkbox' && !empty($val)) {
                                     $val = serialize(explode("|", $val));
                                 }
                                 // update fields:
                                 if (!empty($val) || !isset($member->custom_fields->{$key})) {
                                     // set
                                     $member->custom_fields->{$key} = $val;
                                 }
                                 // unset
                                 unset($field, $val);
                             }
                         }
                         // custom fields updated
                         // log
                         // mgm_log(sprintf('step 8: %s ', print_r($member,1)), __FUNCTION__);
                         // update membership: main mgm_member object
                         if (!empty($membership_type) && is_numeric($pack_id)) {
                             // pack
                             if ($pack = $mgm_packs->get_pack($pack_id)) {
                                 // valid pack
                                 $member->pack_id = $pack_id;
                             } else {
                                 // log
                                 // mgm_log(sprintf('step 9: %s ', print_r($pack,1)), __FUNCTION__);
                                 // error:
                                 continue;
                             }
                             // membership types:
                             $sel_type = '';
                             // loop
                             foreach ($membership_types as $key => $type) {
                                 // check
                                 if ($membership_type == $key || $membership_type == $type) {
                                     // match
                                     $sel_type = $key;
                                     break;
                                 }
                             }
                             // check
                             if (!empty($sel_type)) {
                                 $membership_type = $sel_type;
                             } else {
                                 // log
                                 // mgm_log(sprintf('step 10: %s ', $sel_type), __FUNCTION__);
                                 // continue
                                 continue;
                             }
                             // to distinguish between primary membership and other membership(Y/N)
                             if (!isset($i_user['other_membership']) || isset($i_user['other_membership']) && $i_user['other_membership'] != 'Y') {
                                 // set
                                 $member->membership_type = $membership_type;
                                 // update current membership:
                                 $_response = $this->_update_member_object($member, $pack, $i_user);
                                 // check
                                 if (!$_response['status']) {
                                     // log
                                     // mgm_log(sprintf('step 11: %s ', print_r($_response,1)), __FUNCTION__);
                                     // skip the row
                                     continue;
                                 }
                                 // set
                                 $member = $_response['mgm_member'];
                                 // check guest
                                 if (strtolower($member->membership_type) == 'guest') {
                                     // default
                                     $member->other_membership_types = array();
                                 } else {
                                     // flag
                                     $update_role = true;
                                 }
                             } else {
                                 // init
                                 $multiple_updated = false;
                                 // if multiple mgm_member object:
                                 if (isset($member->other_membership_types) && !empty($member->other_membership_types)) {
                                     // loop
                                     foreach ((array) $member->other_membership_types as $key => $member) {
                                         // convert
                                         $member = mgm_convert_array_to_memberobj($member, $user->ID);
                                         // type
                                         if ($member->membership_type == $membership_type) {
                                             // check
                                             $_response = $this->_update_member_object($member, $pack, $i_user);
                                             // check
                                             if (!$_response['status']) {
                                                 // log
                                                 // mgm_log(sprintf('step 12: %s ', print_r($_response,1)), __FUNCTION__);
                                                 // skip the row:
                                                 continue;
                                             }
                                             // make sure array is saved:
                                             $_response['mgm_member'] = mgm_convert_memberobj_to_array($_response['mgm_member']);
                                             // set
                                             $member->other_membership_types[$key] = $_response['mgm_member'];
                                             // flag
                                             $multiple_updated = true;
                                             // break
                                             break;
                                         }
                                     }
                                 }
                                 //else {mgm_log('skip other_memberships 3', __FUNCTION__);}
                                 // add new to mother_membership_types object:
                                 if (!$multiple_updated) {
                                     // update
                                     $_response = $this->_update_member_object(new stdClass(), $pack, $i_user);
                                     // check
                                     if (!$_response['status']) {
                                         // log
                                         // mgm_log(sprintf('step 13: %s ', print_r($_response,1)), __FUNCTION__);
                                         // skip the row:
                                         continue;
                                     }
                                     // set
                                     $_response['mgm_member'] = mgm_convert_memberobj_to_array($_response['mgm_member']);
                                     // set
                                     $member->other_membership_types[] = $_response['mgm_member'];
                                     // flag
                                     $update_role = true;
                                 }
                             }
                         }
                         // payment type:
                         if (!isset($member->payment_type) || isset($member->payment_type) && empty($member->payment_type)) {
                             $member->payment_type = 'subscription';
                         }
                         // update password:
                         if (!empty($user_password)) {
                             // issue#: 672
                             // generate iss#688
                             /*if(empty($user_password_enc)) {
                             			// set
                             			$user_password_enc = mgm_encrypt_password($user_password, $user->ID);
                             			// log
                             			// mgm_log(sprintf('step 7.2: regenarete password: %s ', $user_password_enc), __FUNCTION__);
                             		}*/
                             // set
                             $member->user_password = $user_password_enc;
                             // md5
                             // $user_password_md5 = wp_hash_password($user_password);
                             //mgm_log($wpdb->prepare("UPDATE ".$wpdb->users." SET user_pass = %s WHERE ID = %d", $user_password_md5, $user->ID), __FUNCTION__);
                             // db update
                             //$wpdb->query( $wpdb->prepare("UPDATE ".$wpdb->users." SET user_pass = %s WHERE ID = %d", $user_password_md5, $user->ID) );
                             // new user
                             if ($insert_user) {
                                 $new_users[$id]['user_password'] = $user_password;
                             }
                         }
                         // save mgm_member object:
                         $member->save();
                         // update role:
                         if ($update_role) {
                             // update role/change order
                             $mgm_roles->add_user_role($user->ID, $pack['role']);
                         }
                         // log
                         // mgm_log(sprintf('step 14: %s ', print_r($member,1)), __FUNCTION__);
                     }
                     // update other user fields:
                     $user_extra = array();
                     if (!empty($user_password)) {
                         $user_extra['user_pass'] = $user_password;
                     }
                     // loop
                     foreach ($i_user as $key => $value) {
                         // check
                         if (in_array($key, $user_fields) && !empty($value)) {
                             if ($key == 'user_registered') {
                                 if (mgm_is_valid_date($value) && ($mysql_date = mgm_format_inputdate_to_mysql($value))) {
                                     $user_extra[$key] = $mysql_date;
                                 }
                             } else {
                                 // set
                                 $user_extra[$key] = $value;
                             }
                         }
                     }
                     // update
                     if (!empty($user_extra)) {
                         // set
                         $user_extra['ID'] = $user->ID;
                         // update
                         wp_update_user($user_extra);
                     }
                     // update
                     $update_count++;
                     // check here:
                     unset($member, $user, $user_extra);
                 }
                 // check limit reached:
                 if ($user_count >= $row_limit) {
                     // check
                     if ($row_count > $row_limit) {
                         // set
                         $response['message'] = sprintf(__('( Import stopped at: %s as limit( %d ) reached. )', 'mgm'), $email, $row_limit);
                     }
                     // break;
                     break;
                 }
                 // ------------------------------------------
                 // unset
                 unset($i_user);
                 // debug
                 // if(function_exists('gc_collect_cycles')) gc_collect_cycles();
                 // wait
                 if (!($user_count % 25)) {
                     sleep(1);
                 }
             }
             // end imported users loop
             //	mgm_log('IMPORT MEMORY PEAK2.5: ' . memory_get_peak_usage(true)/(1024*1024));
             // free unwanted resources
             unset($cf_register_page, $cf_exclude_names, $user_fields, $mgm_packs, $mgm_roles, $user_count);
             // debug
             // if(function_exists('gc_collect_cycles')) gc_collect_cycles();
             // done importing, mail and notify
             if ($update_count) {
                 // unset
                 unset($update_count);
                 // set response
                 $response['status'] = true;
                 $response['users_count'] = count($new_users);
                 // send admin notification:
                 // send to admin
                 if (!empty($new_users)) {
                     $system_obj = mgm_get_class('system');
                     // message
                     $message = sprintf('(%d) %s  %s: <br/><br/>', count($new_users), __('New user registration on your blog', 'mgm'), get_option('blogname'));
                     // loop
                     foreach ($new_users as $user_id => $n_user) {
                         // set
                         $message .= sprintf('%s: %s <br/>', __('Username', 'mgm'), $n_user['user_login']);
                         $message .= sprintf('%s: %s <br/>', __('E-mail', 'mgm'), $n_user['email']);
                         $message .= "-----------------------------------<br/><br/>";
                         // unset
                         unset($n_user);
                         // send email to the user:
                         // mgm_new_user_notification($user_id, $new['user_password'],false);
                     }
                     // unset
                     unset($new_users);
                     // check
                     if (isset($response['message'])) {
                         // set
                         $message .= $response['message'];
                         $message .= "-----------------------------------<br/><br/>";
                     }
                     // admin email:
                     @mgm_mail(get_option('admin_email'), sprintf('[%s] %s', __('New User Registration', 'mgm'), get_option('blogname')), $message);
                     // unset
                     unset($message);
                     // debug
                     // if(function_exists('gc_collect_cycles')) gc_collect_cycles();
                 }
             } else {
                 // none updated
                 $response['error'] = __('No users imported', 'mgm');
             }
         } else {
             // no users
             $response['error'] = __('Empty records', 'mgm');
         }
     } else {
         // no users
         $response['error'] = __('Error in processing users', 'mgm');
     }
     // mgm_log('IMPORT MEMORY PEAK3: ' . memory_get_peak_usage(true)/(1024*1024));
     // mgm_log('$response:' . mgm_array_dump($response, true));
     // return
     return $response;
 }
Exemplo n.º 21
0
 /**
  * Cancel Recurring Subscription
  * This is not a private function
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $subscr_id	
  * @param int $pack_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
 {
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module)) {
             if (isset($member->payment_info->subscr_id)) {
                 $subscr_id = $member->payment_info->subscr_id;
             } else {
                 //check pack is recurring:
                 $pid = $pack_id ? $pack_id : $member->pack_id;
                 if ($pid) {
                     $s_packs = mgm_get_class('subscription_packs');
                     $sel_pack = $s_packs->get_pack($pid);
                     if ($sel_pack['num_cycles'] != 1) {
                         $subscr_id = 0;
                     }
                 }
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 mgm_log('RECALLing ' . $member->payment_info->module . ': cancel_recurring_subscription FROM: ' . $this->code);
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     }
     //send email only if setting enabled
     if (!empty($subscr_id) || $subscr_id === 0) {
         $system_obj = mgm_get_class('system');
         $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
         //send email only if setting enabled
         if (!$dge) {
             // blog
             $blogname = get_option('blogname');
             // user
             $user = get_userdata($user_id);
             // notify admin
             mgm_notify_admin_membership_cancellation_manual_removal_required($blogname, $user, $member);
         }
         return true;
     }
     return false;
 }
Exemplo n.º 22
0
 /**
  * Cancel Recurring Subscription
  * This is not a private function
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $subscr_id	
  * @param int $pack_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
 {
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             if (isset($member->payment_info->subscr_id)) {
                 $subscr_id = $member->payment_info->subscr_id;
             } else {
                 //check pack is recurring:
                 $pid = $pack_id ? $pack_id : $member->pack_id;
                 if ($pid) {
                     $s_packs = mgm_get_class('subscription_packs');
                     $sel_pack = $s_packs->get_pack($pid);
                     if ($sel_pack['num_cycles'] != 1) {
                         $subscr_id = 0;
                     }
                 }
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 mgm_log('RECALLing ' . $member->payment_info->module . ': cancel_recurring_subscription FROM: ' . $this->code);
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         if ($this->setting['aquirer'] != 'sisow') {
             // skip sisow
             return false;
             //skip as trans reff will need to be passed always
         }
     }
     //only for subscription_purchase
     if ($this->setting['aquirer'] == 'sisow') {
         if (!isset($member)) {
             $member = mgm_get_member($user_id);
         }
         $txn_id = $member->payment_info->txn_id;
         //mgm_pr($member);
         // endpoint
         $endpoint = $this->_get_endpoint();
         // set
         $endpoint = str_replace('[action]', 'CancelReservationRequest', $endpoint);
         // keys
         $compute_keys = array($txn_id, $this->setting['merchant_id'], $this->setting['secret_key']);
         $compute_sha1 = sha1(implode('', $compute_keys));
         $post_data = array('trxid' => $txn_id, 'merchantid' => $this->setting['merchant_id'], 'sha1' => $compute_sha1);
         // headers
         $http_headers = array();
         //array('Content-Type' => 'text/xml');
         //mgm_pr($post_data); die;
         // create curl post
         $http_response = mgm_remote_post($endpoint, $post_data, array('headers' => $http_headers, 'timeout' => 30, 'sslverify' => false));
         mgm_log($http_response, __FUNCTION__);
         // parse
         if ($xml = @simplexml_load_string($http_response)) {
             mgm_log($xml, __FUNCTION__);
             // redirect to issuer
             if (isset($xml->reservation->status)) {
                 return (string) $xml->reservation->status == 'Cancelled' ? true : false;
             } else {
                 return false;
             }
         }
     }
     //send email only if setting enabled
     if (!empty($subscr_id) || $subscr_id === 0) {
         $system_obj = mgm_get_class('system');
         $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
         //send email only if setting enabled
         if (!$dge) {
             // blog
             $blogname = get_option('blogname');
             // user
             $user = get_userdata($user_id);
             // notify admin
             mgm_notify_admin_membership_cancellation_manual_removal_required($blogname, $user, $member);
         }
         return true;
     }
     return false;
 }
Exemplo n.º 23
0
 /**
  * Cancel Recurring Subscription
  * Cancellation includes 2 webservice calls
  * 	1. delete Rebill Event on eWay
  *  2. delete Rebill Customer on eWay
  * This is not a private function
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $rebill_id	
  * @param int $pack_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $rebill = null, $pack_id = null)
 {
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             if (isset($member->payment_info->subscr_id)) {
                 $rebill['rebill_id'] = $member->payment_info->subscr_id;
                 $rebill['rebill_customer_id'] = $member->payment_info->rebill_customerid;
             } else {
                 //check pack is recurring:
                 $pid = $pack_id ? $pack_id : $member->pack_id;
                 if ($pid) {
                     $s_packs = mgm_get_class('subscription_packs');
                     $sel_pack = $s_packs->get_pack($pid);
                     if ($sel_pack['num_cycles'] != 1) {
                         $rebill['rebill_id'] = 0;
                     }
                     // 0 stands for a lost subscription id
                 }
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 // log
                 mgm_log('RECALLing ' . $member->payment_info->module . ': cancel_recurring_subscription FROM: ' . $this->module, $this->module . '_cancel');
                 // return
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     }
     //if valid rebill data is found and settings are set
     if (!empty($rebill['rebill_id']) && !empty($rebill['rebill_customer_id']) && !empty($this->setting['customer_id']) && !empty($this->setting['username']) && !empty($this->setting['password'])) {
         $gateway_method = 'webservice';
         $secure = array('CustomerID' => $this->setting['customer_id'], 'Username' => $this->setting['username'], 'Password' => $this->setting['password']);
         //data to post
         //Delete Rebill Event
         $post_data = array('webservice_action' => 'DeleteRebillEvent', 'RebillCustomerID' => $rebill['rebill_customer_id'], 'RebillID' => $rebill['rebill_id']);
         $post_data = array_merge($post_data, $secure);
         // filter post data and create soap xml
         $post_string = $this->_filter_postdata($gateway_method, $post_data);
         // endpoint
         $endpoint = $this->_get_endpoint($this->status . '_' . $gateway_method);
         // test_webservice / live_webservice
         // headers
         $http_headers = $this->_get_http_headers($gateway_method, $post_data['webservice_action']);
         // log
         mgm_log('Request Headers [' . $post_data['webservice_action'] . ']' . mgm_pr($http_headers, true), __FUNCTION__);
         // log
         mgm_log('Request [' . $post_data['webservice_action'] . ']' . $post_string, __FUNCTION__);
         // create curl post
         $http_response = mgm_remote_post($endpoint, $post_string, array('headers' => $http_headers, 'timeout' => 30, 'sslverify' => false));
         // log
         mgm_log('Response [' . $post_data['webservice_action'] . ']' . $http_response, __FUNCTION__);
         /*$http_header = array('User-Agent: NuSOAP/0.9.5 (1.123)', 'Content-Type: text/xml; charset=ISO-8859-1', 
           sprintf('SOAPAction: "http://www.eway.com.au/gateway/rebill/manageRebill/%s"', $post_data['webservice_action']));*/
         // post soap data
         // $buffer = $this->_curl_post($endpoint, $post_string, $http_header);
         // parse response
         $this->_process_response($gateway_method, $http_response, $post_data['webservice_action']);
         // log
         mgm_log('Response Parsed [' . $post_data['webservice_action'] . ']' . mgm_pr($this->response, true), __FUNCTION__);
         //if rebill event is deleted, delete rebill customer
         if (isset($this->response['response_status']) && $this->response['response_status'] == 1) {
             //delete rebill customer:
             $post_data['webservice_action'] = 'DeleteRebillCustomer';
             // filter post data and create soap xml
             $post_string = $this->_filter_postdata($gateway_method, $post_data);
             // soap_action
             $soap_action = sprintf('http://www.eway.com.au/gateway/rebill/manageRebill/%s', $post_data['webservice_action']);
             // http_headers
             $http_headers = array_merge($http_headers, array('SOAPAction' => $soap_action));
             // log
             mgm_log('Request Headers [' . $post_data['webservice_action'] . ']' . mgm_pr($http_headers, true), __FUNCTION__);
             // log
             mgm_log('Request [' . $post_data['webservice_action'] . ']' . $post_string, __FUNCTION__);
             // create curl post
             $http_response = mgm_remote_post($endpoint, $post_string, array('headers' => $http_headers, 'timeout' => 30, 'sslverify' => false));
             // log
             mgm_log('Response [' . $post_data['webservice_action'] . ']' . $http_response, __FUNCTION__);
             /*$http_header = array('User-Agent: NuSOAP/0.9.5 (1.123)', 'Content-Type: text/xml; charset=ISO-8859-1', 
               sprintf('SOAPAction: "http://www.eway.com.au/gateway/rebill/manageRebill/%s"', $post_data['webservice_action']));*/
             // post soap data
             // $buffer = $this->_curl_post($endpoint, $post_string, $http_header);
             // parse response
             $this->_process_response($gateway_method, $http_response, $post_data['webservice_action']);
             // log
             mgm_log('Response Parsed [' . $post_data['webservice_action'] . ']' . mgm_pr($this->response, true), __FUNCTION__);
             // check
             if (isset($this->response['response_status']) && $this->response['response_status'] == 1) {
                 //done
                 return true;
             }
         }
     } elseif ($rebill['rebill_id'] === 0) {
         $system_obj = mgm_get_class('system');
         $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
         //send email only if setting enabled
         if (!$dge) {
             $user = get_userdata($user_id);
             //send notification email to admin:
             $message = __('The User: '******'mgm') . $user->user_email . ' (' . $user_id . ') ' . __('has upgraded/cancelled subscription.', 'mgm');
             $message .= "<br/>" . __('Please unsubscribe the user from Gateway Merchant panel.', 'mgm');
             if (!empty($rebill['rebill_customer_id'])) {
                 $message .= "<br/><br/>" . __('Customer Rebill Id: ', 'mgm') . $rebill['rebill_customer_id'];
             }
             if (!empty($rebill['rebill_id'])) {
                 $message .= "<br/><br/>" . __('Rebill Id: ', 'mgm') . $rebill['rebill_id'];
             }
             if (isset($member->transaction_id)) {
                 $message .= "<br/>" . __('MGM Transaction Id:', 'mgm') . $member->transaction_id;
             }
             //admin email:
             if (!empty($system_obj->setting['admin_email'])) {
                 @mgm_mail($system_obj->setting['admin_email'], sprintf(__('[%s] User Subscription Cancellation', 'mgm'), get_option('blogname')), $message);
             }
         }
         //treat as done
         return true;
     }
     return false;
 }
/**
 * user unsubscribe
 */
function mgm_user_unsubscribe_info($user_id = NULL, $args = array())
{
    // current user
    if (!$user_id) {
        $user = wp_get_current_user();
    } else {
        // by user id
        $user = get_userdata($user_id);
    }
    // return when no user
    if (!isset($user->ID) || isset($user->ID) && (int) $user->ID == 0) {
        return sprintf(__('Please <a href="%s">login</a> to see your unsubscribe button.', 'mgm'), mgm_get_custom_url('login'));
    }
    // member
    $member = mgm_get_member($user->ID);
    // init
    $html = '';
    // button
    $html .= mgm_get_unsubscribe_status_button($member, $user);
    //other members count
    $subs_count = 0;
    // check
    if (isset($member->other_membership_types) && !empty($member->other_membership_types)) {
        // loop
        foreach ($member->other_membership_types as $key => $other_member) {
            //check
            if (!empty($other_member)) {
                //check
                if (is_array($other_member)) {
                    $other_member = mgm_convert_array_to_memberobj($other_member, $user->ID);
                }
                // status button
                $html .= mgm_get_other_unsubscribe_status_button($other_member, $user, $subs_count);
                //check
                if ($subs_count == 0) {
                    $subs_count++;
                }
            }
        }
    }
    //return
    return $html;
}
Exemplo n.º 25
0
 /** 
  * get posts accessible to member by user id
  *
  * @param int user id
  * @return posts 
  * @verb GET
  * @action all 	
  * @url <site>/mgmapi/members/posts.<format>
  */
 public function posts($id)
 {
     global $wpdb;
     // int
     $id = (int) $id;
     // posts
     $posts = array();
     $total_rows = 0;
     // get member
     if ($member = mgm_get_member($id)) {
         // get all subscribed membership types
         $membership_types = mgm_get_subscribed_membershiptypes($id, $member);
         // accessible posts
         $accessible = mgm_get_membership_contents($membership_types, 'accessible', $id);
         // purchased posts
         $purchased = mgm_get_purchased_posts($id);
         // purchasable posts
         $purchasable = mgm_get_membership_contents($membership_types, 'purchasable', $id);
         // total rows
         $total_rows = $accessible['total_posts'] + $purchased['total_posts'] + $purchasable['total_posts'];
         // posts
         $posts = array('accessible' => array('contents' => $this->_clean_content($accessible['posts'])), 'purchased' => array('contents' => $this->_clean_content($purchased['posts'])), 'purchasable' => array('contents' => $this->_clean_content($purchasable['posts'])));
     }
     // response
     $response = array('status' => 'success', 'message' => sprintf(__('Get posts accessible to member by member id#%d response', 'mgm'), $id), 'data' => array('total_rows' => $total_rows, 'posts' => $posts));
     // return
     return array($response, 200);
 }
function mgm_replace_message_tags($message, $user_id = NULL)
{
    // get user
    if (!$user_id) {
        // cusrrent user
        $current_user = wp_get_current_user();
        // set
        $user_id = $current_user->ID;
    }
    // int
    $logged_in = isset($current_user) && $current_user->ID > 0 ? true : false;
    // user
    if ($user_id > 0) {
        // get user
        $user = get_userdata($user_id);
        // mgm member
        $member = mgm_get_member($user_id);
        // set
        $username = $user->user_login;
        $name = mgm_str_concat($user->first_name, $user->last_name);
        $email = $user->user_email;
        $url = $user->user_url;
        $display_name = $user->display_name;
        $first_name = $user->first_name;
        $last_name = $user->last_name;
        $description = $user->description;
        $nickname = $user->nickname;
        // get active custom fields
        $custom_fields = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true, 'on_profile' => true, 'on_public_profile' => true)));
        // init
        $custom_field_tags = array();
        // loop
        foreach ($custom_fields as $custom_field) {
            // if already set skip it
            if (!isset(${$custom_field['name']}) || isset(${$custom_field['name']}) && empty(${$custom_field['name']})) {
                // check
                if (isset($member->custom_fields->{$custom_field}['name'])) {
                    // skip password always
                    if ($custom_field['name'] == 'password') {
                        continue;
                    }
                    // value
                    $value = $member->custom_fields->{$custom_field}['name'];
                    // country
                    if ($custom_field['name'] == 'country') {
                        $value = mgm_country_from_code($value);
                    }
                    // set
                    $custom_field_tags[$custom_field['name']] = $value;
                }
            }
        }
    } else {
        // get active custom fields
        $custom_fields = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true, 'on_profile' => true, 'on_public_profile' => true)));
        // init
        $custom_field_tags = array();
        // loop
        foreach ($custom_fields as $custom_field) {
            // set
            $custom_field_tags[$custom_field['name']] = '';
        }
    }
    /*
     * [[purchase_cost]] = Cost and currency of a purchasable post
     * [[login_register]] = Login or register form
     * [[login_register_links]] = Links for login and register
     * [[login_link]] = Login link only
     * [[facebook_login_button]] = Facebook login button	 
     * [[register_link]] = Register link only
     * [[membership_types]] = A list of membership levels that can see this post/page
     * [[duration]] = number of days that the user will have access for
     * [[username]] = username
     * [[name]] = name / username
     * [[register]] = register form
     */
    // post
    $post_id = get_the_ID();
    // vars
    $system_obj = mgm_get_class('system');
    $currency = $system_obj->setting['currency'];
    $post_obj = mgm_get_post($post_id);
    $duration = $post_obj->get_access_duration();
    if (!$duration) {
        $duration = __('unlimited', 'mgm');
    }
    $purchase_cost = $post_obj->purchase_cost;
    $currency_sign = mgm_get_currency_symbols($system_obj->setting['currency']);
    // these function calls are called repeadtedly as filter is used in multiple places
    // call only when tag present in message
    // [login_register_links]
    if (preg_match('/[[login_register_links]]/', $message)) {
        $login_register_links = !$logged_in ? mgm_get_login_register_links() : '';
    }
    // [login_link]
    if (preg_match('/[[login_link]]/', $message)) {
        $login_link = !$logged_in ? mgm_get_login_link() : '';
    }
    // [facebook_login_button]
    if (preg_match('/[[facebook_login_button]]/', $message)) {
        $facebook_login_button = !$logged_in ? mgm_generate_facebook_login() : '';
    }
    // [register_link]
    if (preg_match('/[[register_link]]/', $message)) {
        $register_link = !$logged_in ? mgm_get_register_link() : '';
    }
    // [login_register]
    if (preg_match('/[[login_register]]/', $message)) {
        $login_register = !$logged_in ? mgm_sidebar_user_login_form(__('Register', 'mgm')) : '';
    }
    // [register]
    if (preg_match('/[[register]]/', $message)) {
        $register = !$logged_in ? mgm_user_register_form() : '';
    }
    // membership type
    if (!($membership_types = $post_obj->get_access_membership_types())) {
        // purchasble
        if (mgm_post_is_purchasable($post_id)) {
            $membership_types = 'Purchasable Only';
        } else {
            // access
            $membership_types = 'No access';
        }
    } else {
        // get object
        $membership_types_obj = mgm_get_class('membership_types');
        // init array
        $ms_types_array = array();
        // loop
        foreach ($membership_types as $membership_type) {
            // set
            if (isset($membership_types_obj->membership_types[$membership_type])) {
                $ms_types_array[] = $membership_types_obj->membership_types[$membership_type];
            }
        }
        // reset
        $membership_types = implode(', ', $ms_types_array);
        // unset
        unset($ms_types_array);
    }
    // loop defined
    $tags = array('purchase_cost', 'login_register', 'login_register_links', 'login_link', 'register_link', 'membership_types', 'duration', 'register', 'username', 'name', 'email', 'url', 'display_name', 'first_name', 'last_name', 'description', 'nickname', 'facebook_login_button', 'currency_sign');
    // loop
    foreach ($tags as $tag) {
        // check
        if (!isset(${$tag})) {
            ${$tag} = '';
        }
        // set
        $message = str_replace('[[' . $tag . ']]', ${$tag}, $message);
    }
    // custom_field_tags
    if (is_array($custom_field_tags)) {
        // loop
        foreach ($custom_field_tags as $tag => $value) {
            // check
            if (!isset($value)) {
                $value = '';
            }
            // set
            $message = str_replace('[[' . $tag . ']]', $value, $message);
        }
    }
    // return
    return $message;
}
Exemplo n.º 27
0
 /**
  * Cancel Recurring Subscription
  * This is not a private function
  * @param int/string $trans_ref	
  * @param int $user_id	
  * @param int/string $subscr_id	
  * @param int $pack_id	
  * @return boolean
  */
 function cancel_recurring_subscription($trans_ref = null, $user_id = null, $subscr_id = null, $pack_id = null)
 {
     //if coming form process return after a subscription payment
     if (!empty($trans_ref)) {
         $transdata = $this->_get_transaction_passthrough($trans_ref);
         if ($transdata['payment_type'] != 'subscription_purchase') {
             return false;
         }
         $user_id = $transdata['user_id'];
         if (isset($transdata['is_another_membership_purchase']) && $transdata['is_another_membership_purchase'] == 'Y') {
             $member = mgm_get_member_another_purchase($user_id, $transdata['membership_type']);
         } else {
             $member = mgm_get_member($user_id);
         }
         if (isset($member->payment_info->module) && !empty($member->payment_info->module)) {
             if (isset($member->payment_info->subscr_id)) {
                 $subscr_id = $member->payment_info->subscr_id;
             } else {
                 //check pack is recurring:
                 $pid = $pack_id ? $pack_id : $member->pack_id;
                 if ($pid) {
                     $s_packs = mgm_get_class('subscription_packs');
                     $sel_pack = $s_packs->get_pack($pid);
                     if ($sel_pack['num_cycles'] != 1) {
                         $subscr_id = 0;
                     }
                     // 0 stands for a lost subscription id
                 }
             }
             //check for same module: if not call the same function of the applicale module.
             if (str_replace('mgm_', '', $member->payment_info->module) != str_replace('mgm_', '', $this->code)) {
                 mgm_log('RECALLing ' . $member->payment_info->module . ': cancel_recurring_subscription FROM: ' . $this->code);
                 return mgm_get_module($member->payment_info->module, 'payment')->cancel_recurring_subscription($trans_ref, null, null, $pack_id);
             }
             //skip if same pack is updated
             if (empty($member->pack_id) || is_numeric($pack_id) && $pack_id == $member->pack_id) {
                 return false;
             }
         } else {
             return false;
         }
     }
     $system_obj = mgm_get_class('system');
     $dge = bool_from_yn($system_obj->get_setting('disable_gateway_emails'));
     //send email only if setting enabled
     if ((!empty($subscr_id) || $subscr_id === 0) && !$dge) {
         $user = get_userdata($user_id);
         //send notification email to admin:
         $message = __('The User: '******'mgm') . $user->user_email . ' (' . $user_id . ') ' . __('has upgraded/cancelled subscription.', 'mgm');
         $message .= "<br/>" . __('Please unsubscribe the user from Gateway Merchant panel.', 'mgm');
         if ($subscr_id) {
             $message .= "<br/><br/>" . __('Pay Id: ', 'mgm') . $subscr_id;
         }
         if (isset($member->transaction_id)) {
             $message .= "<br/>" . __('MGM Transaction Id:', 'mgm') . $member->transaction_id;
         }
         //admin email:
         if (!empty($system_obj->setting['admin_email'])) {
             @mgm_mail($system_obj->setting['admin_email'], sprintf(__('[%s] User Subscription Cancellation', 'mgm'), get_option('blogname')), $message);
         }
     }
     return true;
 }
function mgm_get_cached_object($class_name, $type, $id = false)
{
    // on type
    switch ($type) {
        case 'payment':
        case 'autoresponder':
            return mgm_get_module($class_name, $type, true);
            break;
        case 'member':
            return mgm_get_member($id, true);
            // cached from db
            break;
        case 'post':
            return mgm_get_post($id, true);
            // cached from db
            break;
        case 'class':
        default:
            return mgm_get_option($class_name);
            break;
    }
    // error
    return false;
}
Exemplo n.º 29
0
/**
 * status widget : multiple instance
 * front end instance
 *
 * @param array $args
 * @param array $widget_args
 * @return void
 * @since 1.0
 */
function mgm_sidebar_widget_status($args, $widget_args = 1)
{
    global $wpdb, $user_ID, $current_user, $mgm_sidebar_widget;
    extract($args, EXTR_SKIP);
    if (is_numeric($widget_args)) {
        $widget_args = array('number' => $widget_args);
    }
    $widget_args = wp_parse_args($widget_args, array('number' => -1));
    extract($widget_args, EXTR_SKIP);
    $options = $mgm_sidebar_widget->status_widget;
    if (!isset($options[$number])) {
        return;
    }
    $title = isset($options[$number]['title']) ? $options[$number]['title'] : __('Magic Members', 'mgm');
    $logged_out_intro = isset($options[$number]['logged_out_intro']) ? stripslashes($options[$number]['logged_out_intro']) : $mgm_sidebar_widget->default_text['logged_out_intro'];
    $hide_logged_out = isset($options[$number]['hide_logged_out']) ? stripslashes($options[$number]['hide_logged_out']) : false;
    // packs -issue#: 714
    $packs = mgm_get_class('subscription_packs');
    if ($user_ID) {
        echo $before_widget;
        if (trim($title)) {
            echo $before_title . $title . $after_title;
        }
        //issue#: 539
        $member = mgm_get_member($user_ID);
        // check pack - issue#: 714
        $subs_pack = null;
        if ($member->pack_id) {
            $subs_pack = $packs->get_pack($member->pack_id);
        }
        $uat = $member->membership_type;
        if (!$uat) {
            $uat = 'free';
        }
        $user_status = $member->status;
        if ($user_status != MGM_STATUS_ACTIVE || strtolower($uat) == 'free') {
            $inactive_intro = isset($options[$number]['inactive_intro']) ? $options[$number]['inactive_intro'] : $mgm_sidebar_widget->default_text['inactive_intro'];
            echo $inactive_intro;
            mgm_sidebar_register_links();
        } else {
            if ($expiry = $member->expire_date) {
                //issue#: 692
                $sformat = mgm_get_date_format('date_format_short');
                $expiry = date($sformat, strtotime($expiry));
                //$date = explode('-', $expiry);
                //$expiry = date(get_option('date_format'), mktime(0,0,0,$date[1], $date[2], $date[0]));
            } else {
                $expiry = __('None', 'mgm');
            }
            $active_intro = $mgm_sidebar_widget->default_text['active_intro'];
            if (isset($options[$number]['active_intro'])) {
                $active_intro = $options[$number]['active_intro'];
            }
            $active_intro = str_replace('[membership_type]', mgm_get_class('membership_types')->get_type_name($uat), $active_intro);
            $active_intro = str_replace('[expiry_date]', $expiry, $active_intro);
            // check hidden subscription pack - issue#: 714
            if (isset($subs_pack['hidden']) && $subs_pack['hidden'] != 1 || !isset($subs_pack['hidden'])) {
                echo $active_intro;
            }
            mgm_render_my_purchased_posts($user_ID);
        }
        echo $after_widget;
    } else {
        if (!$hide_logged_out) {
            echo $before_widget;
            if (trim($title)) {
                echo $before_title . $title . $after_title;
            }
            echo $logged_out_intro;
            echo mgm_get_login_register_links();
            echo $after_widget;
        }
    }
}
 /**
  * API helper method get userdata
  *
  * @param int $user_id
  * @return array $userdata
  */
 function _get_userdata($user_id)
 {
     // get userdata
     $user = mgm_get_userdata($user_id);
     // user data
     $email = stripslashes($user->user_email);
     $first_name = !empty($user->first_name) ? stripslashes($user->first_name) : '';
     $last_name = !empty($user->last_name) ? stripslashes($user->last_name) : '';
     $full_name = !empty($first_name) ? mgm_str_concat($first_name, $last_name) : $user->display_name;
     // return
     $userdata = array('email' => $email, 'full_name' => $full_name, 'first_name' => $first_name, 'last_name' => $last_name);
     // member
     $member = mgm_get_member($user_id);
     // custom fields
     if ($member->custom_fields) {
         // get vars
         $custom_fields = get_object_vars($member->custom_fields);
         // check
         if (count($custom_fields) > 0) {
             // loop
             foreach ($custom_fields as $custom_field => $value) {
                 // check
                 if (!isset($userdata[$custom_field])) {
                     // ensure fields already set are not overwritten
                     $userdata[$custom_field] = $value;
                 }
             }
         }
     }
     //other membership types -issue #1073
     if ($member->other_membership_types) {
         $other_membership_types = array();
         foreach ($member->other_membership_types as $o_membership_type) {
             if (!empty($o_membership_type)) {
                 $other_membership_types[] = $o_membership_type['membership_type'];
             }
         }
         $userdata['other_membership_types'] = $other_membership_types;
     }
     // membership type
     if ($member->membership_type) {
         $userdata['membership_type'] = $member->membership_type;
     }
     // return
     return $userdata;
 }