function _get_purchased_contents($post_types, $id, $start, $rows, $gifted = false)
 {
     global $wpdb;
     // array or string
     if (!is_array($post_types)) {
         $post_types = array($post_types);
     }
     // impode
     $post_types_in = mgm_map_for_in($post_types);
     // gifted
     $gifted_sql = $gifted ? "AND is_gift = 'Y'" : "AND is_gift = 'N'";
     // from
     $sql_from = " FROM " . $wpdb->posts . " A JOIN " . TBL_MGM_POST_PURCHASES . " B ON(A.ID = B.post_id) \r\r\n\t\t\t\t\t  WHERE post_status = 'publish' AND post_type IN ( {$post_types_in} ) {$gifted_sql}";
     // sql
     $sql = "SELECT DISTINCT(A.ID), post_type, post_title, post_date, post_content, user_id,guest_token {$sql_from} \r\r\n\t\t        ORDER BY post_date DESC LIMIT {$start},{$rows}";
     // get posts
     $results = $wpdb->get_results($sql);
     // init
     $posts = array();
     // check
     if ($results) {
         // loop
         foreach ($results as $post) {
             // get object
             $post_obj = mgm_get_post($post->ID);
             // check
             if (mgm_post_is_purchasable($post->ID, $post_obj)) {
                 // stip short code
                 $post->post_content = mgm_strip_shortcode($post->post_content);
                 // access type
                 $access_types = $post_obj->get_access_membership_types();
                 // access delay
                 $access_delays = $post_obj->get_access_delay();
                 // init
                 $access_settings = array();
                 // loop
                 foreach ($access_types as $access_type) {
                     // delay
                     $delay = isset($access_delays[$access_type]) ? (int) $access_delays[$access_type] : 0;
                     // set
                     $access_settings[] = array('membership_type' => array('code' => $access_type, 'name' => mgm_get_membership_type_name($access_type)), 'access_delay' => sprintf(__('%d day', 'mgm'), $delay));
                 }
                 // access
                 $post->access_settings = $access_settings;
                 // user
                 if ((int) $post->user_id > 0) {
                     // user
                     $user = get_userdata($post->user_id);
                     $user_info = array('by' => 'user', 'id' => $post->user_id, 'username' => $user->user_login, 'email' => $user->user_email);
                     // gifted
                     if ($gifted) {
                         $post->gift = array_slice($user_info, 1);
                     } else {
                         $post->purchase = $user_info;
                     }
                 } else {
                     $post->purchase = array('by' => 'guest', 'token' => $post->guest_token);
                 }
                 // unset
                 unset($post->guest_token, $post->user_id);
                 // set
                 $posts[] = $post;
             }
         }
     }
     // return
     return $posts;
 }
 private function _delete_multiple()
 {
     global $wpdb;
     extract($_POST);
     // init
     $affected = 0;
     $response = array('status' => 'error', 'message' => __('No downloads selected to delete', 'mgm'));
     // downloads
     if (isset($downloads)) {
         // in
         $downloads_in = mgm_map_for_in($downloads);
         // sql
         $affected = $wpdb->query("DELETE FROM `" . TBL_MGM_DOWNLOAD . "` WHERE `id` IN ({$downloads_in})");
         // execute
         if ($affected) {
             // post assoc
             $wpdb->query("DELETE FROM `" . TBL_MGM_DOWNLOAD_POST_ASSOC . "` WHERE `download_id` IN ({$downloads_in})");
             // limit assoc
             $wpdb->query("DELETE FROM `" . TBL_MGM_DOWNLOAD_LIMIT_ASSOC . "` WHERE `download_id` IN ({$downloads_in})");
             // attributes
             // $wpdb->query("DELETE FROM `" . TBL_MGM_DOWNLOAD_ATTRIBUTE . "` WHERE `download_id` IN ($downloads_in)");
             // attribute types
             // $wpdb->query("DELETE FROM `" . TBL_MGM_DOWNLOAD_ATTRIBUTE_TYPE . "` WHERE `download_id` IN ($downloads_in)");
             // response
             $response['status'] = 'success';
             $response['message'] = sprintf('%d %s', $affected, _n('Download successfully deleted.', 'Downloads successfully deleted.', $affected, 'mgm'));
         } else {
             $response['message'] = _n('Error while deleting selected download.', 'Error while deleting selected download.', count($downloads), 'mgm');
         }
     }
     // return
     return $response;
 }
 public function get_options_only($addon_option_ids = array())
 {
     global $wpdb;
     // init
     $options_list = array();
     // check
     if (!empty($addon_option_ids)) {
         // addon_option_ids
         $addon_option_ids_in = mgm_map_for_in($addon_option_ids);
         // sql
         $sql = "SELECT `id`,`option`,`price` FROM `" . TBL_MGM_ADDON_OPTION . "` \r\r\n\t\t\t\t    WHERE `id` IN ({$addon_option_ids_in}) ORDER BY `price` DESC";
         // row
         $options_results = $wpdb->get_results($sql);
         // reset data
         if ($options_results) {
             foreach ($options_results as $option) {
                 $options_list[$option->id] = array('option' => $option->option, 'price' => $option->price);
             }
         }
     }
     // error
     return $options_list;
 }
 private function _delete_multiple()
 {
     global $wpdb;
     extract($_POST);
     // init
     $affected = 0;
     $response = array('status' => 'error', 'message' => __('No addons selected to delete', 'mgm'));
     // addons
     if (isset($addons)) {
         // in
         $addons_in = mgm_map_for_in($addons);
         // sql
         $affected = $wpdb->query("DELETE FROM `" . TBL_MGM_ADDON . "` WHERE `id` IN ({$addons_in})");
         // execute
         if ($affected) {
             // options
             $wpdb->query("DELETE FROM `" . TBL_MGM_ADDON_OPTION . "` WHERE `addon_id` IN ({$addons_in})");
             // response
             $response['status'] = 'success';
             $response['message'] = sprintf('%d %s', $affected, _n('Addon successfully deleted.', 'Addons successfully deleted.', $affected, 'mgm'));
         } else {
             $response['message'] = _n('Error while deleting selected addon.', 'Error while deleting selected addons.', count($addons), 'mgm');
         }
     }
     // return
     return $response;
 }
 private function _delete_multiple()
 {
     global $wpdb;
     extract($_POST);
     // init
     $affected = 0;
     $status = 'error';
     $message = __('No coupons selected to delete', 'mgm');
     // coupons
     if (isset($coupons)) {
         // in
         $coupons_in = mgm_map_for_in($coupons);
         // sql
         $sql = "DELETE FROM `" . TBL_MGM_COUPON . "` WHERE `id` IN ({$coupons_in})";
         // execute
         if ($affected = $wpdb->query($sql)) {
             $status = 'success';
             $message = sprintf('%d %s', $affected, _n('Coupon successfully deleted.', 'Coupons successfully deleted.', $affected, 'mgm'));
         } else {
             $message = _n('Error while deleting selected coupon.', 'Error while deleting selected coupons.', count($coupons), 'mgm');
         }
     }
     // return
     return array('status' => $status, 'message' => $message);
 }
/**
 * get taxonomies
 *
 * @param bool $join for sql
 * @param array $exclude exclude 
 * @return mixed array or string
 */
function mgm_get_taxonomies($join = true, $exclude = array())
{
    // get taxonomies
    $taxonomies = get_taxonomies(array('public' => true), 'names');
    // default
    if (!$taxonomies) {
        $taxonomies = array('category');
    }
    // init
    $_taxonomies = array();
    // internal
    $exclude = array_merge(array('post_tag', 'post_format'), $exclude);
    // filter out un needed
    foreach ($taxonomies as $taxonomy) {
        // check
        if (in_array($taxonomy, $exclude)) {
            continue;
        }
        // set
        $_taxonomies[] = $taxonomy;
    }
    // return
    return $join ? mgm_map_for_in($_taxonomies) : $_taxonomies;
}
/**
 * fetch authorizenet missing txn id
 *
 * @param object $authorizenet
 * @param array $user_ids 
 * @return void
 * @since 2.7 
 */
function mgm_fetch_authorizenet_missing_txn_id($authorizenet, $user_ids = null)
{
    // db
    global $wpdb;
    // for
    $where = "AND B.option_value = ''";
    // users
    if (is_null($user_ids)) {
        // fetch first 10
        $and_where = $where . " ORDER BY transaction_dt DESC LIMIT 0, 10";
    } elseif (is_array($user_ids) && !empty($user_ids)) {
        // fetch as requested
        $and_where = $where . " AND `user_id` IN(" . mgm_map_for_in($user_ids) . ")";
    } elseif ((int) $user_ids > 0) {
        // fetch one
        $and_where = "AND `user_id` = '" . (int) $user_ids . "'";
    }
    // sql
    $sql = "SELECT `A`.`id`,user_id,data,transaction_dt,`B`.`id` AS `option_id`,`B`.`option_name`,`B`.`option_value` \r\r\n\t\t\tFROM `" . TBL_MGM_TRANSACTION . "` A JOIN `" . TBL_MGM_TRANSACTION_OPTION . "` B ON(A.id=B.transaction_id)\r\r\n\t        WHERE 1 AND `user_id` IS NOT NULL AND module ='authorizenet' \r\r\n\t        AND B.option_name ='authorizenet_transaction_id' {$and_where}";
    // log
    mgm_log($sql, __FUNCTION__);
    // return
    $authorizenet_transaction_id = false;
    //  check missing user_id
    if ($an_transactions = $wpdb->get_results($sql)) {
        // jus use the settings
        // authorize.net specific
        $an_loginid = $authorizenet->setting['loginid'];
        $an_tran_key = $authorizenet->setting['tran_key'];
        // types
        $duration2days = array('d' => 'DAY', 'm' => 'MONTH', 'w' => 'WEEK', 'y' => 'YEAR');
        // log
        mgm_log($an_transactions, __FUNCTION__);
        // this will only miss when pack with trial cost 0.00
        // loop
        foreach ($an_transactions as $transaction) {
            // pack
            $pack = json_decode($transaction->data, true);
            // log
            mgm_log($pack, __FUNCTION__);
            // check
            if (isset($pack['trial_on']) && (int) $pack['trial_on'] == 1 && (double) $pack['trial_cost'] == 0.0) {
                $trial_duration_type = $pack['trial_duration_type'];
                $trial_duration = (int) $pack['trial_duration'];
                $trial_num_cycles = (int) $pack['trial_num_cycles'];
                // calc
                $trial_length = $trial_num_cycles * $trial_duration;
                // 1 * 10
                $trial_days = $duration2days[$trial_duration_type];
                // DAY,MONTH
                // first transaction
                $an_transaction_dt = $transaction->transaction_dt;
                // billing start date
                $an_billing_start_dt = date('Y-m-d H:i:s', strtotime("+{$trial_length} {$trial_days}", strtotime($transaction->transaction_dt)));
            } else {
                $duration_type = $pack['duration_type'];
                $duration = (int) $pack['duration'];
                $num_cycles = (int) $pack['num_cycles'];
                // calc
                $length = $num_cycles == 0 ? $duration : $num_cycles * $duration;
                // 1 * 10
                $days = $duration2days[$duration_type];
                // DAY,MONTH
                // first transaction
                $an_transaction_dt = $transaction->transaction_dt;
                // billing start date
                $an_billing_start_dt = date('Y-m-d H:i:s', strtotime("+{$length} {$days}", strtotime($an_transaction_dt)));
                // log
                mgm_log("+{$length} {$days}", __FUNCTION__);
                // test
                if (strtotime($an_billing_start_dt) < time()) {
                    // temp
                    $temp_an_billing_start_dt = $an_billing_start_dt;
                    // loop
                    while (strtotime($temp_an_billing_start_dt) < time()) {
                        $temp_an_billing_start_dt = date('Y-m-d H:i:s', strtotime("+{$length} {$days}", strtotime($temp_an_billing_start_dt)));
                    }
                    // reduce one unit if next date fetched
                    if (strtotime($temp_an_billing_start_dt) > time()) {
                        $temp_an_billing_start_dt = date('Y-m-d H:i:s', strtotime("-{$length} {$days}", strtotime($temp_an_billing_start_dt)));
                    }
                    // log
                    mgm_log('temp_an_billing_start_dt: ' . $temp_an_billing_start_dt, __FUNCTION__);
                    // copy
                    $an_billing_start_dt = $temp_an_billing_start_dt;
                }
            }
            // log
            mgm_log($an_transaction_dt . ' ' . $an_billing_start_dt, __FUNCTION__);
            // fetch
            $transactions = $authorizenet->get_settled_transactions($an_billing_start_dt);
            // log
            // mgm_log('transactions: '. mgm_pr($transactions, true), __FUNCTION__);
            // check
            if (in_array($transaction->id, array_keys($transactions))) {
                // log
                mgm_log($transaction->id . ' => ' . $transactions[$transaction->id], __FUNCTION__);
                // update
                $wpdb->update(TBL_MGM_TRANSACTION_OPTION, array('option_value' => $transactions[$transaction->id]), array('id' => $transaction->option_id));
                // log
                mgm_log($wpdb->last_query, __FUNCTION__);
                // return
                $authorizenet_transaction_id = $transactions[$transaction->id];
            }
        }
    }
    // return
    return $authorizenet_transaction_id;
}
/**
 * membership accessible/purchasable contents 
 * 
 * @since 2.6.0
 *
 * @param array|string $membership_types
 * @param string $type ( accessible|purchasable )
 * @param int $user_id
 * @param string $posttype ( post|page|custom_post_type )
 * @param int $limit
 * @return array
 */
function mgm_get_membership_contents($membership_types, $type = 'accessible', $user_id = NULL, $post_type = NULL, $limit = NULL)
{
    global $wpdb;
    // issue #920
    $user = wp_get_current_user();
    $temp_member = new stdClass();
    $extended_protection = mgm_get_class('system')->setting['content_hide_by_membership'];
    // membership types
    if (!is_array($membership_types)) {
        $membership_types = array($membership_types);
    }
    // sql per page
    $limit_per_page = 50;
    $limit_clause = '';
    // limit
    if (!$limit || !isset($_GET['section']) || isset($_GET['section']) && $_GET['section'] != $type) {
        $limit_clause = 'LIMIT ' . $limit_per_page;
    }
    // get types
    $post_types_in = $post_type ? mgm_map_for_in(array($post_type)) : mgm_get_post_types(true);
    // from
    $sql_from = " FROM " . $wpdb->posts . " A JOIN " . $wpdb->postmeta . " B ON (A.ID = B.post_id ) \r\r\n\t\t\t      WHERE post_status = 'publish' AND B.meta_key LIKE '_mgm_post%' AND post_type IN ({$post_types_in}) ";
    // get count first
    $total_post_rows = $wpdb->get_var("SELECT COUNT(* ) AS total_post_rows {$sql_from}");
    // update limit if less posts availble
    if (!empty($limit_clause) && $total_post_rows > $limit_per_page) {
        $limit_clause = 'LIMIT ' . $total_post_rows;
    }
    // get posts
    $results = $wpdb->get_results("SELECT DISTINCT(ID), post_name, post_title, post_date, post_content {$sql_from} ORDER BY post_date DESC {$limit_clause}");
    // for purchasable only, get purchased posts
    if ($type == 'purchasable') {
        // sql
        $sql = $wpdb->prepare("SELECT `post_id` FROM `" . TBL_MGM_POST_PURCHASES . "` WHERE `user_id` = %d", $user_id);
        // purchased
        $purchased = $wpdb->get_results($sql);
        // init
        $purchased_posts = array();
        // check
        if (count($purchased) > 0) {
            // loop
            foreach ($purchased as $id => $obj) {
                // set
                $purchased_posts[] = $obj->post_id;
            }
        }
    }
    // init
    $posts = array();
    // store
    if (count($results) > 0) {
        // set counter
        $total_posts = 0;
        // per page
        $posts_per_page = 5;
        // loop
        foreach ($results as $id => $obj) {
            // post object
            $post_obj = mgm_get_post($obj->ID);
            //access delay - issue #920
            $access_delay = $post_obj->access_delay;
            // post access membership types
            $access_membership_types = $post_obj->get_access_membership_types();
            //issue #1376
            $post_category_access_membership_types = mgm_get_post_category_access_membership_types($obj->ID);
            //merging category access/ post accesss
            $access_membership_types = array_merge($access_membership_types, $post_category_access_membership_types);
            //gettign unique access members
            $access_membership_types = array_unique($access_membership_types);
            // branch
            switch ($type) {
                case 'accessible':
                    // multiple membership level purchase(issue#: 400) modification
                    if (array_diff($access_membership_types, $membership_types) != $access_membership_types) {
                        //if any match found
                        // issue #920
                        $access = true;
                        if ($extended_protection == 'Y') {
                            $temp_member->membership_type = $membership_types[0];
                            if (mgm_check_post_access_delay($temp_member, $user, $access_delay)) {
                                //okey
                            } else {
                                $access = false;
                            }
                        }
                        if ($access) {
                            // increment
                            $total_posts++;
                            // store
                            if ($limit != '' && $total_posts <= $posts_per_page || $limit == '') {
                                $posts[] = $obj;
                            }
                        }
                    }
                    break;
                case 'purchasable':
                    // multiple membership level purchase(issue#: 400) modification
                    if (bool_from_yn($post_obj->purchasable) && array_diff($access_membership_types, $membership_types) == $access_membership_types) {
                        //if no match
                        // not purchased
                        if (!in_array($obj->ID, $purchased_posts)) {
                            // issue #920
                            $access = true;
                            if ($extended_protection == 'Y') {
                                $temp_member->membership_type = $membership_types[0];
                                if (mgm_check_post_access_delay($temp_member, $user, $access_delay)) {
                                    //okey
                                } else {
                                    $access = false;
                                }
                            }
                            if ($access) {
                                // increment
                                $total_posts++;
                                // store
                                if ($limit != '' && $total_posts <= $posts_per_page || $limit == '') {
                                    // fetch post price
                                    $obj->purchase_cost = mgm_convert_to_currency($post_obj->purchase_cost);
                                    // store
                                    $posts[] = $obj;
                                }
                            }
                        }
                    }
                    break;
            }
            // unset
            unset($post_obj);
        }
    }
    // reset total
    if (empty($posts)) {
        $total_posts = 0;
    }
    // pager
    $pager = '';
    /*if($total_post_rows > $limit_per_page){	
    		$pager 	= sprintf('<a href="%s">%s</a>', mgm_get_custom_url('membership_contents', false, array('page'=>2)), __('next','mgm'));
    	}*/
    // return
    return array('total_posts' => $total_posts, 'posts' => $posts, 'total_post_rows' => $total_post_rows, 'pager' => $pager);
}
    function member_export()
    {
        global $wpdb;
        // error -- use WP_DEBUG with WP_DEBUG_LOG
        // if(!WP_DEBUG) error_reporting(0);
        // extract
        extract($_POST);
        // log
        // mgm_log($_POST, __FUNCTION__);
        // get format
        $sformat = mgm_get_date_format('date_format_short');
        // process
        if (isset($export_member_info)) {
            // init
            $success = 0;
            // type
            $membership_type = isset($bk_membership_type) ? $bk_membership_type : 'all';
            // status
            $membership_status = isset($bk_membership_status) ? $bk_membership_status : 'all';
            // date
            $date_start = isset($bk_date_start) ? $bk_date_start : '';
            $date_end = isset($bk_date_end) ? $bk_date_end : '';
            // query inut
            $query = '';
            // selected only
            if (isset($bk_only_selected)) {
                // check
                if (isset($bk_selected_members) && is_array($bk_selected_members)) {
                    $query = " AND `id` IN(" . mgm_map_for_in($bk_selected_members) . ")";
                }
            }
            // start date
            if ($date_start) {
                // Issue #700
                // convert to mysql date
                $date_start = strtotime(mgm_format_inputdate_to_mysql($date_start, $sformat));
                // end date
                if ($date_end) {
                    // Issue #700
                    // convert to mysql date
                    $date_end = mgm_format_inputdate_to_mysql($date_end, $sformat);
                    $date_end = strtotime($date_end);
                    // issue#" 492
                    $query .= " AND UNIX_TIMESTAMP(user_registered) >= '{$date_start}' \r\r\n\t\t\t\t\t            AND UNIX_TIMESTAMP(DATE_FORMAT(user_registered, '%Y-%m-%d')) <= '{$date_end}'";
                } else {
                    $query .= " AND UNIX_TIMESTAMP(user_registered) >= '{$date_start}'";
                }
            } else {
                if ($date_end) {
                    // Issue #700
                    // convert to mysql date
                    $date_end = strtotime(mgm_format_inputdate_to_mysql($date_end, $sformat));
                    // query
                    $query .= " AND UNIX_TIMESTAMP(DATE_FORMAT(user_registered, '%Y-%m-%d')) <= '{$date_end}' ";
                }
            }
            // all users
            $sql = 'SELECT ID, user_login, user_email, user_registered, display_name FROM `' . $wpdb->users . '` 
			        WHERE ID <> 1 ' . $query . ' ORDER BY `user_registered` ASC';
            // users
            $users = $wpdb->get_results($sql);
            // filter
            $export_users = array();
            // date
            $current_date = time();
            //issue #844
            $skip_fileds = array('subscription_introduction', 'coupon', 'privacy_policy', 'payment_gateways', 'terms_conditions', 'subscription_options', 'autoresponder', 'captcha');
            // check - issue #1382
            if (isset($bk_users_to_import)) {
                $custom_fields = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true, 'on_profile' => true)));
                $import_user_fileds = array('user_login', 'user_email', 'pack_id', 'membership_type');
                foreach ($custom_fields as $field) {
                    if (!in_array($field['name'], $skip_fileds)) {
                        $import_user_fileds[] = $field['name'];
                    }
                }
            }
            // Custom fields
            $cf_profile_pg = mgm_get_class('member_custom_fields');
            $to_unserialize = array();
            foreach (array_unique($cf_profile_pg->sort_orders) as $id) {
                foreach ($cf_profile_pg->custom_fields as $field) {
                    // issue #954: show the field only if it is enabled for profile page
                    if ($field['id'] == $id && $field['type'] == 'checkbox') {
                        $to_unserialize[] = $field['name'];
                    }
                }
            }
            // loop
            foreach ($users as $user) {
                // user cloned
                $user_obj = clone $user;
                // member
                $member = mgm_get_member($user->ID);
                // check
                if (!isset($bk_inactive)) {
                    $bk_inactive = false;
                }
                // check search parameters:
                if ($this->_get_membership_details($member, $bk_msexp_dur_unit, $bk_msexp_dur, $membership_type, $current_date, $bk_inactive, $membership_status)) {
                    // merge
                    if (method_exists($member, 'merge_fields')) {
                        $user = $member->merge_fields($user);
                    }
                    // log
                    // mgm_log($user, __FUNCTION__);
                    // issue #844
                    foreach ($skip_fileds as $skip_filed) {
                        unset($user->{$skip_filed});
                    }
                    // format dates
                    $user->user_registered = date($sformat, strtotime($user->user_registered));
                    $user->last_pay_date = (int) $user->last_pay_date > 0 ? date($sformat, strtotime($user->last_pay_date)) : 'N/A';
                    $user->expire_date = !empty($user->expire_date) ? date($sformat, strtotime($user->expire_date)) : 'N/A';
                    $user->join_date = (int) $user->join_date > 0 ? date($sformat, $user->join_date) : 'N/A';
                    // issue#: 672
                    // DO not show actual password: #1002
                    // $user->user_password = mgm_decrypt_password($member->user_password, $user->ID);
                    $user->rss_token = $member->rss_token;
                    // unset password
                    unset($user->password, $user->password_conf);
                    // unserialize checkbox values
                    if (count($to_unserialize)) {
                        foreach ($to_unserialize as $chkname) {
                            if (isset($user->{$chkname}) && !empty($user->{$chkname})) {
                                $chk_val = @unserialize($user->{$chkname});
                                if (is_array($chk_val)) {
                                    $user->{$chkname} = implode("|", $chk_val);
                                }
                            }
                        }
                    }
                    // check - issue #1382
                    if (isset($bk_users_to_import)) {
                        $importuser = new stdClass();
                        foreach ($import_user_fileds as $import_user_filed) {
                            if (isset($user->{$import_user_filed})) {
                                $importuser->{$import_user_filed} = $user->{$import_user_filed};
                            }
                            if ($import_user_filed == 'pack_id') {
                                $importuser->{$import_user_filed} = $member->pack_id;
                            }
                        }
                        $export_users[] = $importuser;
                        unset($importuser);
                    } else {
                        $export_users[] = $user;
                    }
                }
                // consider multiple memberships as well:
                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) {
                        // types
                        if (is_array($memtypes)) {
                            $memtypes = mgm_convert_array_to_memberobj($memtypes, $user->ID);
                        }
                        // check search parameters:
                        if ($this->_get_membership_details($memtypes, $bk_msexp_dur_unit, $bk_msexp_dur, $membership_type, $current_date, $bk_inactive, $membership_status)) {
                            // copy
                            $user_mem = clone $user_obj;
                            // add custom fields as well:
                            if (!empty($member->custom_fields)) {
                                // loop
                                foreach ($member->custom_fields as $index => $val) {
                                    // custom field
                                    if ($index == 'birthdate' && !empty($val)) {
                                        // convert saved date to input field format
                                        $val = mgm_get_datepicker_format('date', $val);
                                    }
                                    // set
                                    $user_mem->{$index} = $val;
                                }
                            }
                            // check types
                            if (is_object($memtypes) && method_exists($memtypes, 'merge_fields')) {
                                // merge
                                $user_mem = $memtypes->merge_fields($user_mem);
                            } else {
                                // convert to array
                                $data = mgm_object2array($memtypes);
                                // check payment
                                if (isset($memtypes->payment_info) && count($memtypes->payment_info) > 0) {
                                    // loop payments
                                    foreach ($memtypes->payment_info as $index => $val) {
                                        // set
                                        $data['payment_info_' . $index] = str_replace('mgm_', '', $val);
                                    }
                                }
                                // loop data
                                foreach ($data as $index => $val) {
                                    $user_mem->{$index} = $val;
                                }
                            }
                            //issue #844
                            foreach ($skip_fileds as $skip_filed) {
                                unset($user->{$skip_filed});
                            }
                            // format dates
                            $user_mem->user_registered = date($sformat, strtotime($user_mem->user_registered));
                            $user_mem->last_pay_date = (int) $memtypes->last_pay_date > 0 ? date($sformat, strtotime($memtypes->last_pay_date)) : 'N/A';
                            $user_mem->expire_date = !empty($memtypes->expire_date) ? date($sformat, strtotime($memtypes->expire_date)) : 'N/A';
                            $user_mem->join_date = (int) $memtypes->join_date > 0 ? date($sformat, $memtypes->join_date) : 'N/A';
                            // check - issue #1382
                            if (isset($bk_users_to_import)) {
                                $importuser = new stdClass();
                                foreach ($import_user_fileds as $import_user_filed) {
                                    if ($user_mem->{$import_user_filed}) {
                                        $importuser->{$import_user_filed} = $user_mem->{$import_user_filed};
                                    }
                                    if ($import_user_filed == 'pack_id') {
                                        $importuser->{$import_user_filed} = $memtypes->pack_id;
                                    }
                                }
                                $export_users[] = $importuser;
                                unset($importuser);
                            } else {
                                $export_users[] = $user_mem;
                            }
                            // unset
                            unset($user_mem);
                        }
                    }
                }
            }
            // end for
            mgm_log('export_users : ' . mgm_array_dump($export_users, true));
            // default response
            $response = array('status' => 'error', 'message' => __('Error while exporting members. Could not find any member with requested search parameters.', 'mgm'));
            // check
            if (($expcount = count($export_users)) > 0) {
                // Issue #1559: standardization of Membership type
                for ($k = 0; $k < $expcount; $k++) {
                    if (isset($export_users[$k]->membership_type)) {
                        $export_users[$k]->membership_type = strtolower($export_users[$k]->membership_type);
                    }
                }
                // success
                $success = count($export_users);
                // create
                if ($bk_export_format == 'csv') {
                    $filename = mgm_create_csv_file($export_users, 'export_users');
                } else {
                    $filename = mgm_create_xls_file($export_users, 'export_users');
                }
                // src
                $file_src = MGM_FILES_EXPORT_URL . $filename;
                // message
                $response['message'] = sprintf(__('Successfully exported %d %s.', 'mgm'), $success, $success > 1 ? 'users' : 'user');
                $response['status'] = 'success';
                $response['src'] = $file_src;
                // for download iframe
            }
            // return response
            echo json_encode($response);
            exit;
        }
        // data
        $data = array();
        // load template view
        $this->load->template('members/member/export', array('data' => $data));
    }
Example #10
0
    /**
     * Sync Membership data and DataPlus Recurring transactions
     *
     */
    function update_dataplus_transactions()
    {
        // comment the below return once finished:
        // return;
        if (!($epdb = $this->_get_epdb_ref())) {
            return;
        }
        //global $wpdb;
        //skip if table doesn't exist
        if (!count($epdb->get_results("SHOW TABLES LIKE '" . TBL_MGM_EPOCH_TRANS_STATUS . "'"))) {
            return;
        }
        //consider only 'F' : Initial Free Trial Transaction
        //				'I' : Standard Initial Recurring Transaction
        //				'N'	: NonĀ­Initial Recurring Transaction
        $arr_transtypes = array('F' => 'free_trial_transaction', 'I' => 'initial_recurring_transaction', 'N' => 'recurring_transaction');
        // transtypes_in
        $transtypes_in = mgm_map_for_in(array_keys($arr_transtypes));
        // sql;
        $sql = sprintf('SELECT ets_transaction_id, ets_transaction_date, ets_transaction_type, ets_ref_trans_ids, ets_member_idx 
		                 FROM `' . TBL_MGM_EPOCH_TRANS_STATUS . '` WHERE ets_transaction_type IN(%s) 
						 AND (process_status="N" OR process_status IS NULL)
						 ORDER BY ets_transaction_date ASC LIMIT 0,50', $transtypes_in);
        // tran
        $transdata = $epdb->get_results($sql);
        // log
        mgm_log('SQL: ' . $epdb->last_query, __FUNCTION__);
        // log
        mgm_log($transdata, __FUNCTION__);
        // count
        if (count($transdata) > 0) {
            // set
            foreach ($transdata as $tdata) {
                // init
                $data = array();
                //$data['x_custom'] 		= $tdata->ets_ref_trans_ids;
                $data['trans_date'] = $tdata->ets_transaction_date;
                $data['txn_type'] = $arr_transtypes[$tdata->ets_transaction_type];
                $data['transaction_id'] = $tdata->ets_transaction_id;
                // as per Epoch Tech Support, Only Sucsessful Transactions will be inserted to EpochTransStats
                $data['ans'] = 'Y';
                //rewrite if status is dynamic
                $data['order_id'] = $tdata->ets_member_idx;
                // tran
                $tran = mgm_get_transaction_by_option('epoch_order_id', $data['order_id']);
                // verify
                if (isset($tran['id'])) {
                    // set
                    $data['x_custom'] = $tran['id'];
                    // set user
                    if (isset($tran['user_id'])) {
                        $data['user_id'] = $tran['user_id'];
                    }
                    //rewrite global $_REQUEST for parameter compatibility
                    $_REQUEST = $data;
                    // log
                    mgm_log($_REQUEST, __FUNCTION__);
                    // caller
                    $this->set_webhook_called_by('self');
                    //Update membership status
                    $this->process_notify();
                    // $this-process_rebill_status($data['user_id']);// @todo use this
                    // update code
                    // change record status to 'Y' once updated: so next time when the cron runs, current record will be skipped
                    $epdb->update(TBL_MGM_EPOCH_TRANS_STATUS, array('process_status' => 'Y'), array('ets_transaction_id' => $tdata->ets_transaction_id));
                    // log
                    mgm_log('TransStat Update SQL: ' . $epdb->last_query, __FUNCTION__);
                }
            }
        }
    }