function _update_member_object($member, $pack, $data, $insert = true)
 {
     $arr_resp = array('status' => true);
     $duration_exprs = mgm_get_class('subscription_packs')->get_duration_exprs();
     $arr_status = array(MGM_STATUS_NULL, MGM_STATUS_ACTIVE, MGM_STATUS_EXPIRED, MGM_STATUS_PENDING, MGM_STATUS_TRIAL_EXPIRED, MGM_STATUS_CANCELLED, MGM_STATUS_ERROR, MGM_STATUS_AWAITING_CANCEL);
     // if trial on
     if ($pack['trial_on']) {
         $member->trial_on = !empty($data['trial_on']) ? $data['trial_on'] : (isset($member->trial_on) && $member->trial_on ? $member->trial_on : $pack['trial_on']);
         $member->trial_cost = !empty($data['trial_cost']) ? $data['trial_cost'] : (isset($member->trial_cost) && $member->trial_cost ? $member->trial_cost : $pack['trial_cost']);
         $member->trial_duration = !empty($data['trial_duration']) ? $data['trial_duration'] : (isset($member->trial_duration) && $member->trial_duration ? $member->trial_duration : $pack['trial_duration']);
         $member->trial_duration_type = !empty($data['trial_duration_type']) ? $data['trial_duration_type'] : (isset($member->trial_duration_type) && $member->trial_duration_type ? $member->trial_duration_type : $pack['trial_duration_type']);
         $member->trial_num_cycles = !empty($data['trial_num_cycles']) ? $data['trial_num_cycles'] : (isset($member->trial_num_cycles) ? $member->trial_num_cycles : $pack['trial_num_cycles']);
     }
     // duration
     if (!empty($data['duration'])) {
         if (is_numeric($data['duration'])) {
             $member->duration = $data['duration'];
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Duration', 'mgm');
         }
     } elseif ($insert) {
         $member->duration = $pack['duration'];
     }
     //duration type:
     if (!empty($data['duration_type'])) {
         if (in_array($data['duration_type'], array('d', 'w', 'm', 'y', 'l', 'dr'))) {
             $member->duration_type = $data['duration_type'];
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Duration Type', 'mgm');
         }
     } elseif ($insert) {
         $member->duration_type = $pack['duration_type'];
     }
     //duration type:
     if (!empty($data['amount'])) {
         if (is_numeric($data['amount'])) {
             $member->amount = number_format($data['amount'], 2, '.', '');
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Amount', 'mgm');
         }
     } elseif ($insert) {
         $member->amount = $pack['cost'];
     }
     //amount:
     if (!empty($data['hide_old_content'])) {
         $member->hide_old_content = $data['hide_old_content'];
     } elseif ($insert) {
         $member->hide_old_content = $pack['hide_old_content'];
     }
     //$member->currency        = (!empty($data['currency'])) ? $data['currency'] : $system_obj->setting['currency'];
     $member->membership_type = $data['membership_type'];
     //status
     if (!empty($data['status'])) {
         if (in_array($data['status'], $arr_status)) {
             $member->status = $data['status'];
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Status', 'mgm');
         }
     } elseif ($insert) {
         //to prevent updating active/expired user status
         //if(isset($member->status) && !in_array($member->status, array(MGM_STATUS_ACTIVE, MGM_STATUS_EXPIRED)))
         $member->status = MGM_STATUS_ACTIVE;
     }
     if (!empty($data['status_str'])) {
         $member->status_str = $data['status_str'];
     } elseif ($insert) {
         $member->status_str = __('Last payment was successful', 'mgm');
     }
     //join date:
     if (!empty($data['join_date'])) {
         if (mgm_is_valid_date($data['join_date']) && ($mysql_date = mgm_format_inputdate_to_mysql($data['join_date']))) {
             $member->join_date = strtotime($mysql_date);
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Joining Date', 'mgm');
         }
     } elseif ($insert) {
         // do not overwrite if already set
         if (empty($member->join_date)) {
             $member->join_date = strtotime('now');
         }
     }
     //last pay date:
     if (!empty($data['last_pay_date'])) {
         if (mgm_is_valid_date($data['last_pay_date']) && ($mysql_date = mgm_format_inputdate_to_mysql($data['last_pay_date']))) {
             $member->last_pay_date = $mysql_date;
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Last Pay Date', 'mgm');
         }
     } elseif ($insert) {
         // do not overwrite if already set
         if (empty($member->last_pay_date)) {
             $member->last_pay_date = date('Y-m-d');
         }
     }
     //expiry date:
     if (!empty($data['expire_date'])) {
         if (mgm_is_valid_date($data['expire_date']) && ($mysql_date = mgm_format_inputdate_to_mysql($data['expire_date']))) {
             $member->expire_date = $mysql_date;
         } else {
             $arr_resp['status'] = false;
             $arr_resp['error'][] = __('Invalid Last Expiry Date', 'mgm');
         }
     } elseif ($insert) {
         $time = strtotime('now');
         //if not lifetime:
         // if($pack['duration_type'] != 'l') {
         if (in_array($pack['duration_type'], array_keys($duration_exprs))) {
             // take only date exprs
             $time = strtotime("+{$pack['duration']} {$duration_exprs[$pack['duration_type']]}", $time);
             // formatted
             $member->expire_date = date('Y-m-d', $time);
         } else {
             $member->expire_date = '';
         }
     }
     //if lifetime:
     if ($pack['duration_type'] == 'l' && $member->status == MGM_STATUS_ACTIVE) {
         $member->expire_date = '';
         if (isset($member->status_reset_on)) {
             unset($member->status_reset_on);
         }
         if (isset($member->status_reset_as)) {
             unset($member->status_reset_as);
         }
     }
     //active number of cycles:
     if (isset($data['active_num_cycles']) && !empty($data['active_num_cycles'])) {
         $member->active_num_cycles = $data['active_num_cycles'];
     }
     //autoresponder subscription:
     if (isset($data['autoresponder']) && !empty($data['autoresponder'])) {
         $member->autoresponder = $data['autoresponder'];
         $member->subscribed = 'Y';
     }
     //payment_info
     //module:
     if (isset($data['payment_info_module']) && !empty($data['payment_info_module'])) {
         if (!isset($member->payment_info)) {
             $member->payment_info = new stdClass();
         }
         $member->payment_info->module = $data['payment_info_module'];
     }
     //subscr_id
     if (isset($data['payment_info_subscr_id']) && !empty($data['payment_info_subscr_id'])) {
         if (!isset($member->payment_info)) {
             $member->payment_info = new stdClass();
         }
         $member->payment_info->subscr_id = $data['payment_info_subscr_id'];
     }
     //txn_type
     if (isset($data['payment_info_txn_type']) && !empty($data['payment_info_txn_type'])) {
         if (!isset($member->payment_info)) {
             $member->payment_info = new stdClass();
         }
         $member->payment_info->txn_type = $data['payment_info_txn_type'];
     }
     //txn_id
     if (isset($data['payment_info_txn_id']) && !empty($data['payment_info_txn_id'])) {
         if (!isset($member->payment_info)) {
             $member->payment_info = new stdClass();
         }
         $member->payment_info->txn_id = $data['payment_info_txn_id'];
     }
     if ($arr_resp['status']) {
         $arr_resp['mgm_member'] = $member;
     }
     //object fields:
     //		$member->code = 'mgm_member';
     //		$member->name = 'Member Lib';
     //		$member->description = 'Member Lib';
     //check this:
     $duration_exprs = null;
     unset($duration_exprs);
     $arr_status = null;
     unset($arr_status);
     if (function_exists('gc_collect_cycles')) {
         gc_collect_cycles();
     }
     return $arr_resp;
 }
 function edit()
 {
     global $wpdb;
     // trim
     array_map('trim', $_POST);
     // extract
     extract($_POST);
     // system
     $system_obj = mgm_get_class('system');
     // save
     if (isset($submit_download)) {
         // response
         $response = array('status' => 'error', 'message' => sprintf(__('Error while updating download <b>%s</b>!', 'mgm'), $title));
         // check duplicate
         if (mgm_is_duplicate(TBL_MGM_DOWNLOAD, array('title'), "id <> '{$id}'")) {
             $response['message'] = sprintf(__('Error while updating download <b>%s</b>, title exists!', 'mgm'), $title);
         } else {
             // set vars
             $members_only = isset($members_only) ? 'Y' : 'N';
             // set vars
             $restrict_acces_ip = isset($restrict_acces_ip) ? 'Y' : 'N';
             // is_s3_torrent
             $is_s3_torrent = isset($is_s3_torrent) ? 'Y' : 'N';
             // filename
             $filename = isset($download_file_new) ? $download_file_new : $direct_url;
             // real name
             $real_filename = isset($download_file_new_realname) ? $download_file_new_realname : basename($filename);
             // filesize
             $filesize = mgm_file_get_size($filename);
             // post vars
             $post_date = date('Y-m-d H:i:s');
             // user
             $current_user = wp_get_current_user();
             // data
             $data = array('title' => $title, 'filename' => $filename, 'real_filename' => $real_filename, 'filesize' => $filesize, 'post_date' => $post_date, 'restrict_acces_ip' => $restrict_acces_ip, 'user_id' => $current_user->ID, 'members_only' => $members_only, 'is_s3_torrent' => $is_s3_torrent);
             // null
             $null_columns = array();
             // download limit
             if (isset($download_limit) && (int) $download_limit > 0) {
                 $data['download_limit'] = (int) $download_limit;
             } else {
                 $null_columns[] = "`download_limit` = NULL ";
             }
             // expire date
             if (isset($expire_dt) && !empty($expire_dt)) {
                 $data['expire_dt'] = mgm_format_inputdate_to_mysql($expire_dt);
             } else {
                 $null_columns[] = "`expire_dt` = NULL ";
             }
             // code
             if (!isset($code) || isset($code) && empty($code)) {
                 $data['code'] = uniqid();
             }
             // update
             if ($wpdb->update(TBL_MGM_DOWNLOAD, $data, array('id' => $id))) {
                 // update null
                 if (count($null_columns) > 0) {
                     // join
                     $set_string = implode(',', $null_columns);
                     // clear old
                     $wpdb->query($wpdb->prepare('UPDATE `' . TBL_MGM_DOWNLOAD . '` SET ' . $set_string . ' WHERE `id` = %d', $id));
                 }
                 // clear old
                 $wpdb->query($wpdb->prepare('DELETE FROM `' . TBL_MGM_DOWNLOAD_POST_ASSOC . '` WHERE `download_id` = %d', $id));
                 // save
                 if (bool_from_yn($members_only)) {
                     if (isset($link_to_post_id)) {
                         // loop
                         foreach ($link_to_post_id as $post_id) {
                             // insert
                             $wpdb->insert(TBL_MGM_DOWNLOAD_POST_ASSOC, array('download_id' => $id, 'post_id' => $post_id));
                         }
                     }
                 }
                 // set message
                 $response['message'] = sprintf(__('Download updated successfully <b>%s</b>', 'mgm'), $title);
                 $response['status'] = 'success';
             } else {
                 $response['message'] = sprintf(__('Error while updating download <b>%s</b> Or nothing updated!', 'mgm'), $title);
             }
         }
         // return response
         echo json_encode($response);
         exit;
     }
     // data
     $data = array();
     // download
     $data['download'] = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . TBL_MGM_DOWNLOAD . "` WHERE id = %d", $id));
     // download_posts
     $data['download_posts'] = mgm_get_download_post_ids($id);
     // get all post types
     $post_types = mgm_get_post_types();
     //get all published posts - issue #1034
     $all_posts = mgm_field_values($wpdb->posts, 'ID', 'SUBSTR(post_title,1, 100) AS post_title', "AND `post_status` ='publish' AND `post_type` IN ({$post_types})", 'post_title');
     //get all scheduled posts
     $scheduled_posts = mgm_field_values($wpdb->posts, 'ID', 'SUBSTR(post_title,1, 100) AS post_title', "AND `post_status` ='future' AND `post_type` IN ({$post_types})", 'post_title');
     foreach ($scheduled_posts as $k => $scheduled_post) {
         $all_posts[$k] = $scheduled_post . '(S)';
     }
     //get all draft posts
     $draft_posts = mgm_field_values($wpdb->posts, 'ID', 'SUBSTR(post_title,1, 100) AS post_title', "AND `post_status` ='draft' AND `post_type` IN ({$post_types})", 'post_title');
     foreach ($draft_posts as $k => $draft_post) {
         $all_posts[$k] = $draft_post . '(D)';
     }
     //sort by post name
     asort($all_posts);
     //all posts
     $data['posts'] = $all_posts;
     // hook
     $data['download_hook'] = $system_obj->get_setting('download_hook', 'download');
     // slug
     $data['download_slug'] = $system_obj->get_setting('download_slug', 'download');
     // load template view
     $this->load->template('downloads/edit', array('data' => $data));
 }
/**
 * post/page meta box data save
 *
 */
function mgm_post_setup_save($post_id)
{
    // donot process ajax
    // if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) return true;
    // update
    if (isset($_POST['mgm_post'])) {
        // check revision
        if ($the_post = wp_is_post_revision($post_id)) {
            $post_id = $the_post;
        }
        // get object
        $post_obj = mgm_get_post($post_id);
        // check object
        if (is_object($post_obj)) {
            // post data
            $post_objdata = $_POST['mgm_post'];
            // access membership types
            if (!isset($post_objdata['access_membership_types'])) {
                $post_objdata['access_membership_types'] = array();
            }
            // access delay
            if (!isset($post_objdata['access_delay'])) {
                $post_objdata['access_delay'] = array();
            }
            // purchase expiry
            if (!empty($post_objdata['purchase_expiry'])) {
                //issue #1424
                $datepickerformat = mgm_get_datepicker_format();
                $post_objdata['purchase_expiry'] = mgm_format_inputdate_to_mysql($post_objdata['purchase_expiry'], $datepickerformat);
            }
            // int
            $post_objdata['access_duration'] = $post_objdata['purchase_duration'] = (int) $post_objdata['access_duration'];
            // int
            $post_objdata['access_view_limit'] = (int) $post_objdata['access_view_limit'];
            // addons
            if (!isset($post_objdata['addons'])) {
                $post_objdata['addons'] = array();
            }
            // allowed_modules
            if (!isset($post_objdata['allowed_modules'])) {
                $post_objdata['allowed_modules'] = array();
            }
            // set new fields
            $post_obj->set_fields($post_objdata);
            // apply filter
            $post_obj = apply_filters('mgm_post_update', $post_obj, $post_id);
            // save meta
            $post_obj->save();
            // log
            // mgm_log($post_obj, __FUNCTION__);
        }
    }
    // return
    return true;
}
 function get_earnings($date_start, $date_end, $member_type)
 {
     // global
     global $wpdb;
     $data = array();
     $curr_date = mgm_get_current_datetime();
     $current_date = $curr_date['timestamp'];
     // preparing query based on dates
     if (!empty($date_start) && !empty($date_end)) {
         /*			$date_end=str_replace('/','-',$date_end);
         			$end_date  = date('Y-m-d', strtotime( $date_end));
         			
         			$date_start=str_replace('/','-',$date_start);	
         			$start_date  = date('Y-m-d',  strtotime( $date_start));	
         */
         //issue #1311
         $sformat = mgm_get_date_format('date_format_short');
         $start_date = mgm_format_inputdate_to_mysql($date_start, $sformat);
         $end_date = mgm_format_inputdate_to_mysql($date_end, $sformat);
         $start_date .= ' 00:00:00';
         $end_date .= ' 23:59:59';
         //Issue #733
         //$condition =" WHERE transaction_dt BETWEEN  '$start_date' AND  '$end_date'";
         $condition = " AND status_text = 'Last payment was successful' AND transaction_dt BETWEEN  '{$start_date}' AND  '{$end_date}'";
     } else {
         //setting the default end date
         if (empty($date_end)) {
             $date_end = $end_date = date('Y-m-d', $current_date);
             $end_date .= ' 23:59:59';
         }
         //setting the default start date
         if (empty($date_start)) {
             $date_start = $start_date = date('Y-m-d', strtotime("{$end_date} - 3 months"));
             $start_date .= ' 00:00:00';
         }
         //$condition =" WHERE transaction_dt BETWEEN  '$start_date' AND  '$end_date'";
         $condition = " AND status_text = 'Last payment was successful' AND transaction_dt BETWEEN  '{$start_date}' AND  '{$end_date}'";
         //Issue #733
         //$condition =" ORDER BY  `transaction_dt` DESC LIMIT 10";
         //$condition = " AND status_text = 'Last payment was successful' ORDER BY  `transaction_dt` DESC LIMIT 10";
     }
     // sql
     $sql = "SELECT * FROM `" . TBL_MGM_TRANSACTION . "` WHERE 1 {$condition}";
     // mgm_log($sql);
     // row
     $rows = $wpdb->get_results($sql);
     // reset data
     $subscription = array();
     $purchase = array();
     $d = array();
     // looping the results
     foreach ($rows as $row) {
         $row->data = json_decode($row->data, true);
         extract($row->data);
         // Storing subscription data to array
         if (trim($row->payment_type) == 'subscription_purchase') {
             $dt = strtok($row->transaction_dt, " ");
             if (isset($subscription[$dt])) {
                 if ($membership_type == $member_type || $member_type == 'all') {
                     $subscription[$dt]['date'] = $dt;
                     //issue #1311
                     if ($trial_on) {
                         $subscription[$dt]['cost'] += $trial_cost;
                     } else {
                         $subscription[$dt]['cost'] += $cost;
                     }
                     //$subscription[$dt]['cost'] +=$cost;
                     $subscription[$dt]['count']++;
                 }
             } else {
                 if ($membership_type == $member_type || $member_type == 'all') {
                     $d[] = $dt;
                     $subscription[$dt]['date'] = $dt;
                     //issue #1311
                     if ($trial_on) {
                         $subscription[$dt]['cost'] += $trial_cost;
                     } else {
                         $subscription[$dt]['cost'] += $cost;
                     }
                     //$subscription[$dt]['cost'] =$cost;
                     $subscription[$dt]['count'] = 1;
                 }
             }
         }
         // Storing pay per post data to array
         if (trim($row->payment_type) == 'post_purchase') {
             $dt = strtok($row->transaction_dt, " ");
             if (isset($purchase[$dt])) {
                 // validating membership type
                 if ($membership_type == $member_type || $member_type == 'all') {
                     $purchase[$dt]['date'] = $dt;
                     $purchase[$dt]['cost'] += $cost;
                     $purchase[$dt]['count']++;
                 }
             } else {
                 // validating membership type
                 if ($membership_type == $member_type || $member_type == 'all') {
                     $d[] = $dt;
                     $purchase[$dt]['date'] = $dt;
                     $purchase[$dt]['cost'] = $cost;
                     $purchase[$dt]['count'] = 1;
                 }
             }
         }
     }
     //getting recurring earnings and dates
     $recurring_data = $this->recurring_earnings($date_start, $date_end, $member_type);
     $d = array_unique($d);
     $md = array_merge($d, $recurring_data['dates']);
     $d = array_unique($md);
     sort($d);
     $recurring = $recurring_data['recurring'];
     $dcount = count($d);
     $data[0]['date_start'] = $date_start;
     $data[0]['date_end'] = $date_end;
     $data[0]['member_type'] = $member_type;
     // Migrating the pay per post,recurring and subscription data to array
     for ($i = 0; $i < $dcount; $i++) {
         $udt = $d[$i];
         if (!empty($udt)) {
             $data[$i]['date'] = $udt;
             if (array_key_exists($udt, $purchase)) {
                 $data[$i]['purchase'] = $purchase[$udt]['cost'];
             } else {
                 $data[$i]['purchase'] = 0;
             }
             if (array_key_exists($udt, $subscription)) {
                 $data[$i]['subscription'] = $subscription[$udt]['cost'];
             } else {
                 $data[$i]['subscription'] = 0;
             }
             if (isset($recurring) && array_key_exists($udt, $recurring)) {
                 $data[$i]['recurring'] = $recurring[$udt]['cost'];
             } else {
                 $data[$i]['recurring'] = 0;
             }
         }
     }
     return $data;
 }
 function edit()
 {
     global $wpdb;
     extract($_POST);
     // save
     if (isset($save_coupon)) {
         // response
         $response = array('status' => 'error', 'message' => __('Coupon update failed, Unknown error!', 'mgm'));
         // check duplicate
         if (mgm_is_duplicate(TBL_MGM_COUPON, array('name'), "id <> '{$id}'")) {
             $response['message'] = sprintf(__('Error while updating coupon: %s, same code exists!', 'mgm'), $name);
         } else {
             // fields
             $fields = array('name', 'value', 'description', 'use_limit', 'used_count', 'product', 'expire_dt');
             // colums
             $column_data = $column_null_data = array();
             // create value
             $value = $this->_set_value();
             // use limit
             if (isset($use_limit) && is_numeric($use_limit)) {
                 $use_limit = (int) $use_limit;
             } else {
                 $use_limit = NULL;
             }
             // product
             if (isset($product)) {
                 $product = json_encode($product);
             } else {
                 $product = NULL;
             }
             // expire dt format
             if (isset($expire_dt) && !empty($expire_dt)) {
                 $expire_dt = date('Y-m-d H:i:s', strtotime(mgm_format_inputdate_to_mysql($expire_dt, mgm_get_date_format('date_format_short'))));
             } else {
                 $expire_dt = NULL;
             }
             // loop
             foreach ($fields as $field) {
                 // check
                 if (isset(${$field}) && !is_null(${$field})) {
                     $column_data[$field] = trim(${$field});
                 } else {
                     $column_null_data[$field] = 'NULL';
                     // need string to track
                 }
             }
             // affected
             $affected = 0;
             // update
             if ($wpdb->update(TBL_MGM_COUPON, $column_data, array('id' => $id))) {
                 $affected++;
             }
             // null
             if (!empty($column_null_data)) {
                 // column_data2
                 $column_data2_a = mgm_implode_a(',', array_keys($column_null_data), array_values($column_null_data));
                 // update
                 if ($wpdb->query("UPDATE `" . TBL_MGM_COUPON . "` SET {$column_data2_a} WHERE id='{$id}' ")) {
                     $affected++;
                 }
             }
             // save
             if ($affected) {
                 $response = array('status' => 'success', 'message' => sprintf(__('Successfully updated coupon: "%s"', 'mgm'), $name));
             } else {
                 $response = array('status' => 'error', 'message' => sprintf(__('Error while updating coupon: "%s"', 'mgm'), $name));
             }
         }
         // return response
         echo json_encode($response);
         exit;
     }
     // data
     $data = array();
     // coupon
     $data['coupon'] = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . TBL_MGM_COUPON . "` WHERE id=%d", $id));
     // parse
     $data['value_is'] = $this->_get_value($data['coupon']->value);
     // currency
     $data['currency'] = mgm_get_class('system')->setting['currency'];
     // load template view
     $this->load->template('coupons/edit', array('data' => $data));
 }
/**
 * validate and save profile data
 *
 * @param int user id
 * @return int user id
 */
function mgm_user_profile_update($user_id)
{
    global $wpdb;
    // get user
    if ($user_id > 0) {
        $user_data = get_userdata($user_id);
    }
    // error
    if (!$user_data->ID) {
        return $user_id;
    }
    // flag to control callback re calling via hooks clash, iss#705
    define('MGM_DOING_USERS_PROFILE_UPDATE', TRUE);
    // set aside member object
    $member = mgm_get_member($user_id);
    // create empty user
    $user = new stdClass();
    // set id
    $user->ID = $user_data->ID;
    // sanitize user login
    if (isset($_POST['user_login'])) {
        $user->user_login = sanitize_user($_POST['user_login'], true);
    }
    // asnitize email and copy
    if (isset($_POST['user_email'])) {
        $user->user_email = sanitize_text_field($_POST['user_email']);
    }
    // urls
    if (isset($_POST['mgm_profile_field']['url'])) {
        if (empty($_POST['mgm_profile_field']['url']) || $_POST['mgm_profile_field']['url'] == 'http://') {
            $user->user_url = '';
        } else {
            $user->user_url = esc_url_raw($_POST['mgm_profile_field']['url']);
            $user->user_url = preg_match('/^(https?|ftps?|mailto|news|irc|gopher|nntp|feed|telnet):/is', $user->user_url) ? $user->user_url : 'http://' . $user->user_url;
        }
    }
    if (isset($_POST['mgm_profile_field']['first_name'])) {
        $user->first_name = sanitize_text_field($_POST['mgm_profile_field']['first_name']);
    }
    if (isset($_POST['mgm_profile_field']['last_name'])) {
        $user->last_name = sanitize_text_field($_POST['mgm_profile_field']['last_name']);
    }
    if (isset($_POST['mgm_profile_field']['nickname'])) {
        $user->nickname = sanitize_text_field($_POST['mgm_profile_field']['nickname']);
    }
    if (isset($_POST['mgm_profile_field']['display_name'])) {
        $user->display_name = sanitize_text_field($_POST['mgm_profile_field']['display_name']);
    }
    if (isset($_POST['mgm_profile_field']['description'])) {
        $user->description = trim($_POST['mgm_profile_field']['description']);
    }
    // init errors
    $errors = new WP_Error();
    // check user login
    if (isset($_POST['user_login']) && !validate_username($_POST['user_login'])) {
        $errors->add('user_login', __('<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.', 'mgm'));
    }
    // user login duplicate
    if (($owner_id = username_exists($user->user_login)) && $owner_id != $user->ID) {
        $errors->add('user_login', __('<strong>ERROR</strong>: This username is already registered. Please choose another one.', 'mgm'));
    }
    // nickname
    //!isset( $_POST['mgm_profile_field']['nickname'] ) || - issue #1207
    if (isset($_POST['mgm_profile_field']['nickname']) && empty($_POST['mgm_profile_field']['nickname'])) {
        $errors->add('nickname', __('<strong>ERROR</strong>: You must provide a Nick Name.', 'mgm'));
    }
    // email - issue #1207
    if (isset($_POST['user_email']) && empty($user->user_email)) {
        $errors->add('empty_email', __('<strong>ERROR</strong>: Please enter an e-mail address.', 'mgm'), array('form-field' => 'email'));
    } elseif (isset($_POST['user_email']) && !is_email($user->user_email)) {
        $errors->add('invalid_email', __('<strong>ERROR</strong>: The e-mail address isn&#8217;t correct.', 'mgm'), array('form-field' => 'email'));
    } elseif (isset($_POST['user_email']) && ($owner_id = email_exists($user->user_email)) && $owner_id != $user->ID) {
        $errors->add('email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.', 'mgm'), array('form-field' => 'email'));
    }
    // password:
    $pass1 = $pass2 = '';
    if (isset($_POST['user_password'])) {
        $pass1 = sanitize_text_field($_POST['user_password']);
    }
    if (isset($_POST['user_password_conf'])) {
        $pass2 = sanitize_text_field($_POST['user_password_conf']);
    }
    /* checking the password has been typed twice */
    do_action_ref_array('check_passwords', array($user->user_login, &$pass1, &$pass2));
    //issue #1207
    if (isset($_POST['user_password']) && isset($_POST['user_password_conf'])) {
        if (empty($pass1) && !empty($pass2)) {
            $errors->add('pass', __('<strong>ERROR</strong>: You entered your new password only once.', 'mgm'), array('form-field' => 'pass1'));
        } elseif (!empty($pass1) && empty($pass2)) {
            $errors->add('pass', __('<strong>ERROR</strong>: You entered your new password only once.', 'mgm'), array('form-field' => 'pass2'));
        }
    }
    /* Check for "\" in password */
    //issue #1207
    if (isset($_POST['user_password']) && isset($_POST['user_password_conf'])) {
        if (false !== strpos(stripslashes($pass1), "\\")) {
            $errors->add('pass', __('<strong>ERROR</strong>: Passwords may not contain the character "\\".', 'mgm'), array('form-field' => 'pass1'));
        }
    }
    // get default fields
    $profile_fields = mgm_get_config('default_profile_fields', array());
    // get active custom fields on profile page
    $cf_profile_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_profile' => true)));
    //init - issue #1573
    $show_membership_fields_arr = array();
    if (isset($_REQUEST['membership']) && !empty($_REQUEST['membership'])) {
        // membership
        $membership = $_REQUEST['membership'];
        // get active custom fields on register
        $cf_profile_by_membership_types = mgm_get_class('member_custom_fields')->get_fields_where(array('attributes' => array('profile_by_membership_types' => true)));
        //mgm_pr($cf_profile_by_membership_types);
        //check
        if (!empty($cf_profile_by_membership_types)) {
            //loop
            foreach ($cf_profile_by_membership_types as $cf_profile_by_membership_type) {
                //membership_type
                $membership_types_string = $cf_profile_by_membership_type['attributes']['profile_membership_types_field_alias'];
                //check
                if (preg_match('/\\b' . $membership . '\\b/', $membership_types_string)) {
                    $show_fields_arr[] = $cf_profile_by_membership_type['name'];
                    $show_membership_fields_arr[] = $cf_profile_by_membership_type;
                    if ($cf_profile_by_membership_type['name'] == 'password') {
                        foreach ($cf_profile_by_membership_types as $cf_profile_by_membership) {
                            if ($cf_profile_by_membership['name'] == 'password_conf') {
                                $show_membership_fields_arr[] = $cf_profile_by_membership;
                            }
                        }
                    }
                }
            }
        }
    }
    //merge - issue #1573
    if (isset($show_membership_fields_arr) && is_array($show_membership_fields_arr) && !empty($show_membership_fields_arr)) {
        $cf_profile_page = array_merge($cf_profile_page, $show_membership_fields_arr);
    }
    //Profile page password filed is default .#issue 799
    $falg = 0;
    $pass_field = '';
    foreach ($cf_profile_page as $field) {
        if ($field['name'] == 'password') {
            $falg = 1;
            //issue #973
            $pass_field = $field;
        }
    }
    if ($falg == 0) {
        $cf_profile_page[] = array('name' => 'password', 'label' => 'Password', 'type' => 'password', 'system' => 1);
    }
    //issue #973 & issue #1207
    if (isset($_POST['user_password']) && isset($_POST['user_password_conf']) && !empty($pass1) && !empty($pass2) && (isset($pass_field['attributes']['password_min_length']) && $pass_field['attributes']['password_min_length'] == true) || isset($pass_field['attributes']['password_max_length']) && $pass_field['attributes']['password_max_length'] == true) {
        if (strlen($pass1) < $pass_field['attributes']['password_min_length_field_alias'] || strlen($pass2) < $pass_field['attributes']['password_min_length_field_alias']) {
            $errors->add('pass', sprintf(__('<strong>ERROR</strong>:Password is too short, minimum %d characters.', 'mgm'), $pass_field['attributes']['password_min_length_field_alias']), array('form-field' => 'pass1'));
        } elseif (strlen($pass1) > $pass_field['attributes']['password_max_length_field_alias'] || strlen($pass2) > $pass_field['attributes']['password_max_length_field_alias']) {
            $errors->add('pass', sprintf(__('<strong>ERROR</strong>:Password is too long, minimum %d characters.', 'mgm'), $pass_field['attributes']['password_max_length_field_alias']), array('form-field' => 'pass1'));
        } elseif ($pass1 != $pass2) {
            $errors->add('pass', __('<strong>ERROR</strong>: Please enter the same password in the two password fields.', 'mgm'), array('form-field' => 'pass1'));
        }
    } elseif (isset($_POST['user_password']) && isset($_POST['user_password_conf']) && $pass1 != $pass2) {
        $errors->add('pass', __('<strong>ERROR</strong>: Please enter the same password in the two password fields.', 'mgm'), array('form-field' => 'pass1'));
    }
    // confirm email - issue #1315
    if (isset($_POST['user_email_conf']) && empty($_POST['user_email_conf'])) {
        $errors->add($field['name'], __('<strong>ERROR</strong>: Please type your confirm e-mail address.', 'mgm'));
    } elseif (isset($_POST['user_email_conf']) && !is_email($_POST['user_email_conf'])) {
        $errors->add('invalid_email_conf', __('<strong>ERROR</strong>: The confirm email address isn&#8217;t correct.', 'mgm'));
    } elseif (isset($_POST['user_email_conf']) && is_email($_POST['user_email']) && $_POST['user_email_conf'] != $_POST['user_email']) {
        $errors->add($field['name'], __('<strong>ERROR</strong>: E-mail does not match. Please re-type.', 'mgm'));
    }
    //issue #1207
    $m_pass = '';
    // set
    if (!empty($pass1) || !empty($pass2)) {
        if (!empty($pass1) && !empty($pass2)) {
            $user->user_pass = wp_hash_password($pass1);
            $m_pass = $pass1;
        } elseif (!empty($pass1)) {
            $user->user_pass = wp_hash_password($pass1);
            $m_pass = $pass1;
        } else {
            $user->user_pass = wp_hash_password($pass2);
            $m_pass = $pass2;
        }
        //issue #703
        //$user->user_pass = $pass1;
        $member->user_password = mgm_encrypt_password($m_pass, $user->ID);
    }
    // loop
    foreach ($cf_profile_page as $field) {
        // skip default fields, validated already
        if (in_array($field['name'], array('username', 'email', 'password', 'password_conf', 'email_conf'))) {
            continue;
        }
        // skip html
        if ($field['type'] == 'html' || $field['type'] == 'label') {
            continue;
        }
        // check register and required
        if ((bool) $field['attributes']['required'] === true) {
            // error
            $error_codes = $errors->get_error_codes();
            // validate other
            if (!isset($_POST['mgm_profile_field'][$field['name']]) || empty($_POST['mgm_profile_field'][$field['name']])) {
                //issue #703
                $errors->add($field['name'], __('<strong>ERROR</strong>: You must provide a ', 'mgm') . mgm_stripslashes_deep($field['label']) . '.');
            }
        }
    }
    // Allow plugins to return their own errors.
    do_action_ref_array('user_profile_update_errors', array(&$errors, $update, &$user));
    // error
    if ($errors->get_error_codes()) {
        return $errors;
    }
    // init pass
    $user_password = '';
    // system - issue #1237
    $system_obj = mgm_get_class('system');
    $short_format = !empty($system_obj->setting['date_format_short']) ? $system_obj->setting['date_format_short'] : MGM_DATE_FORMAT_SHORT;
    // update custom fields values:
    if (isset($_POST['mgm_profile_field'])) {
        // loop fields
        foreach ($cf_profile_page as $field) {
            // skip html
            if ($field['type'] == 'html' || $field['type'] == 'label' || $field['name'] == 'password_conf') {
                continue;
            }
            // set
            if (isset($_POST['mgm_profile_field'][$field['name']])) {
                // value
                $value = $_POST['mgm_profile_field'][$field['name']];
                // birthdate
                if ($field['name'] == 'birthdate') {
                    //convert to mysql date format(to standardise the date format) -issue #1237
                    $value = mgm_format_inputdate_to_mysql($value, $short_format);
                } elseif ($field['name'] == 'password') {
                    // pass iss#705
                    $user_password = $value;
                    // issue#: 672
                    $value = mgm_encrypt_password($value, $user_id);
                } elseif ($field['type'] == 'checkbox' && is_array($value)) {
                    //$value = implode(" ", $value);
                    //issue #1070
                    $value = serialize($value);
                }
                // set
                $member->custom_fields->{$field}['name'] = $value;
            } elseif (isset($_POST[$field['name']])) {
                // value
                $value = $_POST[$field['name']];
                // birthdate
                if ($field['name'] == 'birthdate') {
                    // convert to mysql date format(to standardise the date format) - issue #1237
                    $value = mgm_format_inputdate_to_mysql($value, $short_format);
                } elseif ($field['name'] == 'password') {
                    // pass iss#705
                    $user_password = $value;
                    //issue#: 672
                    $value = mgm_encrypt_password($value, $user_id);
                } elseif ($field['type'] == 'checkbox' && is_array($value)) {
                    //issue #1070
                    $value = serialize($value);
                    //$value = implode(" ", $value);
                }
                // set
                $member->custom_fields->{$field}['name'] = $value;
            } elseif ($field['name'] == 'password' && !empty($pass1)) {
                // pass iss#705
                $user_password = $pass1;
                // value
                $value = mgm_encrypt_password($pass1, $user_id);
                // set
                $member->custom_fields->{$field}['name'] = $value;
            } elseif ($field['type'] == 'checkbox' && isset($member->custom_fields->{$field}['name'])) {
                // If no value selected
                $member->custom_fields->{$field}['name'] = '';
            }
        }
    }
    // update
    $member->save();
    //issue #1207
    if (!empty($m_pass)) {
        // pass iss#705
        $user_password = $m_pass;
    }
    // iss#705
    // userdata to update, leave password here
    $userdata = get_object_vars($user);
    // unset encoded password from userdata
    unset($userdata['user_pass']);
    // update password
    if (!empty($user_password)) {
        // set
        $userdata['user_pass'] = $user_password;
    }
    // save main user data & return user id
    return $user_id = wp_update_user($userdata);
}
 function purchase_export()
 {
     global $wpdb;
     // data
     $data = array();
     // filter
     $sql_filter = $data['search_field_name'] = $data['search_field_value'] = '';
     $search_field_name = mgm_post_var('search_field_name');
     // check
     if (!empty($search_field_name)) {
         // post
         $search_field_value = mgm_post_var('search_field_value');
         $search_field_value_two = mgm_post_var('search_field_value_two');
         // view data
         $data['search_field_name'] = $search_field_name;
         // for display
         //issue #1281
         $data['search_field_value'] = htmlentities($search_field_value, ENT_QUOTES, "UTF-8");
         // for display
         $data['search_field_value_two'] = htmlentities($search_field_value_two, ENT_QUOTES, "UTF-8");
         // for display
         //searc value
         $search_field_value = esc_sql($search_field_value);
         // for sql
         // end date value
         $search_field_value_two = esc_sql($search_field_value_two);
         // for sql
         //current date
         $curr_date = mgm_get_current_datetime();
         $current_date = $curr_date['timestamp'];
         // by field
         switch ($search_field_name) {
             case 'user_login':
                 $sql_filter = " AND (`user_login` LIKE '%{$search_field_value}%')";
                 break;
             case 'addon_option':
                 $sql_filter = " AND (`option` LIKE '%{$search_field_value}%')";
                 break;
             case 'purchase_dt':
                 // date start
                 if (empty($search_field_value)) {
                     $search_field_value = date('Y-m-d', $current_date);
                 }
                 // date end
                 if (empty($search_field_value_two)) {
                     $search_field_value_two = date('Y-m-d', $current_date);
                 }
                 // convert
                 $search_field_value = mgm_format_inputdate_to_mysql($search_field_value);
                 $search_field_value_two = mgm_format_inputdate_to_mysql($search_field_value_two);
                 // set
                 $sql_filter = " AND (DATE_FORMAT(`purchase_dt`,'%Y-%m-%d') BETWEEN '{$search_field_value}' AND '{$search_field_value_two}')";
                 break;
         }
     }
     // order
     $sql_order = " ORDER BY `user_login`, `purchase_dt`";
     // sql
     $sql = "SELECT SQL_CALC_FOUND_ROWS A.id, A.purchase_dt, B.option AS addon_option, C.user_login\r\r\n\t\t        FROM `" . TBL_MGM_ADDON_PURCHASES . "` A \r\r\n\t\t\t\tLEFT JOIN " . TBL_MGM_ADDON_OPTION . " B ON (B.id = A.addon_option_id) \r\r\n\t\t\t\tLEFT JOIN " . $wpdb->users . " C ON (C.ID = A.user_id) WHERE 1 \r\r\n\t\t\t\t{$sql_filter} {$sql_order} ";
     // store
     $data['addon_purchases'] = $wpdb->get_results($sql);
     // date format
     $date_format = mgm_get_date_format('date_format');
     // init
     $purchases = array();
     // check
     if (count($data['addon_purchases']) > 0) {
         //purchases
         foreach ($data['addon_purchases'] as $purchase) {
             // int
             $row = new stdClass();
             // export fields
             $row->username = $purchase->user_login;
             $row->addon_option = $purchase->addon_option;
             $row->purchase_date = date($date_format, strtotime($purchase->purchase_dt));
             // cache
             $purchases[] = $row;
             // unset
             unset($row);
         }
     }
     // default response
     $response = array('status' => 'error', 'message' => __('Error while exporting addon purchases.', 'mgm'));
     // check
     if (count($purchases) > 0) {
         // success
         $success = count($purchases);
         // create
         if (mgm_post_var('export_format') == 'csv') {
             $filename = mgm_create_csv_file($purchases, 'addon_purchases');
         } else {
             $filename = mgm_create_xls_file($purchases, 'addon_purchases');
         }
         // src
         $file_src = MGM_FILES_EXPORT_URL . $filename;
         // message
         $message = sprintf(__('Successfully exported %d addon %s.', 'mgm'), $success, $success > 1 ? 'purchases' : 'purchase');
         // init
         $response = array('status' => 'success', 'message' => $message, 'src' => $file_src);
     }
     // return response
     echo json_encode($response);
     exit;
 }
/**
 * generate members list - short code content
 */
function mgm_generate_member_list($args = array())
{
    global $wpdb, $post;
    //issue #1327
    $show_level = isset($args['show_level']) ? $args['show_level'] : null;
    $show_level_members = array();
    if (!empty($show_level) && $show_level != null) {
        $show_level = explode(',', $show_level);
        $show_level_count = count($show_level);
        for ($i = 0; $i < $show_level_count; $i++) {
            $level_match_members = mgm_get_members_with('membership_type', $show_level[$i]);
            if (!empty($level_match_members)) {
                $show_level_members = array_merge($show_level_members, $level_match_members);
            }
        }
        if (!empty($show_level_members)) {
            $show_level_members = array_unique($show_level_members);
        }
    }
    // current url
    $current_url = get_permalink($post->ID);
    // append ? why?
    // if( !strpos($current_url,'?') !== false) $current_url = ($current_url . '?');
    // echo $current_url;
    // init pager
    $pager = new mgm_pager();
    // init data
    $data = $custom_search_fields = $custom_sort_fields = $custom_user_list = $user_list = array();
    // css group
    $css_group = mgm_get_css_group();
    // html
    $html = '';
    // check
    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.pages.css';
        $html .= sprintf($css_link_format, $css_file);
    }
    // search fields
    $data['search_fields'] = array('' => __('Select', 'mgm'), 'username' => __('Username', 'mgm'), 'id' => __('User ID', 'mgm'), 'email' => __('User Email', 'mgm'), 'first_name' => __('First Name', 'mgm'), 'last_name' => __('Last Name', 'mgm'), 'membership_type' => __('Membership Type', 'mgm'), 'reg_date' => __('Registration Date', 'mgm'), 'last_payment' => __('Last Payment', 'mgm'), 'expire_date' => __('Expiration Date', 'mgm'), 'fee' => __('Fee', 'mgm'), 'status' => __('Status', 'mgm'));
    // sort fields
    $data['sort_fields'] = array('id' => __('User ID', 'mgm'), 'username' => __('Username', 'mgm'), 'email' => __('User Email', 'mgm'), 'reg_date' => __('Registration Date', 'mgm'));
    // order fields
    $data['order_fields'] = array('desc' => __('DESC', 'mgm'), 'asc' => __('ASC', 'mgm'));
    // custom_fields
    $custom_fields = mgm_get_class('member_custom_fields');
    // getting custom fileds and skip the search fields if allready exists.
    foreach ($custom_fields->custom_fields as $custom_field) {
        if (!array_key_exists($custom_field['name'], $data['search_fields'])) {
            $custom_search_fields[$custom_field['name']] = $custom_field['label'];
        }
    }
    // getting custom fileds and skip the sort fields if allready exists.
    foreach ($custom_fields->custom_fields as $custom_field) {
        if (!array_key_exists($custom_field['name'], $data['sort_fields'])) {
            if ($custom_field['name'] != 'status') {
                $custom_sort_fields[$custom_field['name']] = $custom_field['label'];
            }
        }
    }
    // filter
    $sql_filter = $data['search_field_name'] = $data['search_field_value'] = '';
    // field value
    if (isset($_REQUEST['query'])) {
        $search_field_value = $_REQUEST['query'];
    } else {
        $search_field_value = '';
    }
    // field name
    if (isset($_REQUEST['by'])) {
        $search_field_name = $_REQUEST['by'];
    } else {
        $search_field_name = '';
    }
    // sort field
    if (isset($_REQUEST['sort_field'])) {
        $sort_field_name = $_REQUEST['sort_field'];
    } else {
        $sort_field_name = '';
    }
    // sort order type //order_type
    if (isset($_REQUEST['sort_order'])) {
        $sort_order_type = $_REQUEST['sort_order'];
    } else {
        $sort_order_type = '';
    }
    // members
    $active_members = mgm_get_members_with('status', MGM_STATUS_ACTIVE);
    // wrongly called,use constant
    // check
    if (!empty($search_field_name)) {
        // clean
        $search_field_value = mgm_escape($search_field_value);
        // for sql
        $search_field_name = mgm_escape($search_field_name);
        // for sql
        // view data
        $data['search_field_name'] = $search_field_name;
        $data['search_field_value'] = trim($search_field_value);
        // current date
        $curr_date = mgm_get_current_datetime();
        $current_date = $curr_date['timestamp'];
        // check
        if (array_key_exists($search_field_name, $custom_search_fields)) {
            // members
            $members = mgm_get_members_with_customfiled($search_field_name, $search_field_value);
            //issue #1327
            if (!empty($show_level_members)) {
                $members = array_intersect($show_level_members, $members);
            }
            //check
            $members_in = count($members) == 0 ? 0 : implode(',', $members);
            // set filter
            $sql_filter = " AND `ID` IN ({$members_in})";
        } else {
            // by field
            switch ($search_field_name) {
                case 'username':
                    // issue#: 347(LIKE SEARCH)
                    $filter = " AND `user_login` LIKE '%{$search_field_value}%'";
                    // matched
                    $matched_members = mgm_get_members_with_sql_filter($filter);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'id':
                    // filter
                    $filter = " AND `ID` = '" . (int) $search_field_value . "'";
                    // match
                    $matched_members = mgm_get_members_with_sql_filter($filter);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'email':
                    // issue#: 347(LIKE SEARCH)
                    $filter = " AND `user_email` LIKE '%{$search_field_value}%'";
                    // match
                    $matched_members = mgm_get_members_with_sql_filter($filter);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'membership_type':
                    // match
                    $matched_members = mgm_get_members_with('membership_type', $search_field_value);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'reg_date':
                    // check
                    if (empty($search_field_value)) {
                        $search_field_value = date('Y-m-d', $current_date);
                    }
                    // convert
                    $search_field_value = mgm_format_inputdate_to_mysql($search_field_value);
                    // set filter
                    $filter = " AND DATE_FORMAT(`user_registered`,'%Y-%m-%d') = '{$search_field_value}'";
                    // match
                    $matched_members = mgm_get_members_with_sql_filter($filter);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'last_payment':
                    // check
                    if (empty($search_field_value)) {
                        $search_field_value = date('Y-m-d', $current_date);
                    }
                    // convert
                    $search_field_value = mgm_format_inputdate_to_mysql($search_field_value);
                    // match
                    $matched_members = mgm_get_members_with('last_pay_date', $search_field_value);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'expire_date':
                    // check
                    if (empty($search_field_value)) {
                        $search_field_value = date('Y-m-d', $current_date);
                    }
                    // convert
                    $search_field_value = mgm_format_inputdate_to_mysql($search_field_value);
                    // match
                    $matched_members = mgm_get_members_with('expire_date', $search_field_value);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                case 'fee':
                    // match
                    $matched_members = mgm_get_members_with('amount', $search_field_value);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                    /*				
                    case 'status':
                    	// members
                    	$members    = mgm_get_members_with('status', $search_field_value);
                    	// check
                    	$members_in = (count($members)==0) ? 0 : (implode(',', $members));
                    	// set filter
                    	$sql_filter = " AND `ID` IN ({$members_in})";
                    break;
                    */
                /*				
                case 'status':
                	// members
                	$members    = mgm_get_members_with('status', $search_field_value);
                	// check
                	$members_in = (count($members)==0) ? 0 : (implode(',', $members));
                	// set filter
                	$sql_filter = " AND `ID` IN ({$members_in})";
                break;
                */
                case 'first_name':
                case 'last_name':
                    // members
                    $matched_members = mgm_get_members_with($search_field_name, $search_field_value);
                    //issue #1327
                    if (!empty($show_level_members)) {
                        $matched_members = array_intersect($show_level_members, $matched_members);
                    }
                    // common
                    $members = array_intersect($active_members, $matched_members);
                    // check
                    $members_in = count($members) == 0 ? 0 : implode(',', $members);
                    // set filter
                    $sql_filter = " AND `ID` IN ({$members_in})";
                    break;
            }
        }
    }
    // filters via shortcode args
    $use_field = isset($args['use_field']) ? $args['use_field'] : null;
    $use_filter = isset($args['use_filter']) ? $args['use_filter'] : '';
    $sort_by = isset($args['sort_by']) ? $args['sort_by'] : null;
    $sort_type = isset($args['sort_type']) ? $args['sort_type'] : null;
    // use shortcode field
    if (!empty($use_field)) {
        $use_field = explode(',', $use_field);
    }
    // use shortcode flter
    if (!empty($use_filter)) {
        $use_filter = explode(',', $use_filter);
    }
    // use shortcode sort
    if (!empty($sort_by)) {
        $sort_by = explode(',', $sort_by);
    }
    // use shortcode sort order
    if (!empty($sort_type)) {
        $sort_type = explode(',', $sort_type);
    }
    //setting up the default list fiedls
    if (empty($use_field)) {
        $use_field = array('image', 'first_name', 'last_name', 'email');
    }
    // check length
    $use_field_len = count($use_field);
    //getting user fillter options from short code.
    $arr_filter_search = array();
    if (!empty($use_filter)) {
        $use_filter_len = count($use_filter);
        for ($k = 0; $k < $use_filter_len; $k++) {
            if (array_key_exists($use_filter[$k], $data['search_fields'])) {
                $arr_filter_search[$use_filter[$k]] = $data['search_fields'][$use_filter[$k]];
            } elseif (array_key_exists($use_filter[$k], $custom_search_fields)) {
                $arr_filter_search[$use_filter[$k]] = $custom_search_fields[$use_filter[$k]];
            }
        }
        $data['search_fields'] = $arr_filter_search;
    }
    //getting sort by options from short code.
    $arr_sort_search = array();
    if (!empty($sort_by)) {
        $use_sort_len = count($sort_by);
        for ($k = 0; $k < $use_sort_len; $k++) {
            if (array_key_exists($sort_by[$k], $data['sort_fields'])) {
                $arr_sort_search[$sort_by[$k]] = $data['sort_fields'][$sort_by[$k]];
            } elseif (array_key_exists($sort_by[$k], $custom_sort_fields)) {
                $arr_sort_search[$sort_by[$k]] = $custom_sort_fields[$sort_by[$k]];
            }
        }
        $data['sort_fields'] = $arr_sort_search;
    }
    //getting sort type options from short code.
    $arr_sort_type = array();
    if (!empty($sort_type)) {
        $use_sort_type_len = count($sort_by);
        for ($k = 0; $k < $use_sort_type_len; $k++) {
            if (array_key_exists($sort_type[$k], $data['order_fields'])) {
                $arr_sort_type[$sort_type[$k]] = $data['order_fields'][$sort_type[$k]];
            }
        }
        $data['order_fields'] = $arr_sort_type;
    }
    //issue #1301
    //setting default sort order field as sort fields first value
    if (empty($sort_field_name)) {
        $sort_field_name = array_shift(array_keys($data['sort_fields']));
    }
    //setting default sort order type as sort order fields first value
    if (empty($sort_order_type)) {
        $sort_order_type = array_shift(array_keys($data['order_fields']));
    }
    //setting page limit
    $page_limit = isset($args['page_limit']) ? (int) $args['page_limit'] : 20;
    // page limit
    $data['page_limit'] = isset($_REQUEST['page_limit']) ? (int) $_REQUEST['page_limit'] : $page_limit;
    // page no
    $data['page_no'] = isset($_REQUEST['page_no']) ? (int) $_REQUEST['page_no'] : 1;
    // limit
    $sql_limit = $pager->get_query_limit($data['page_limit']);
    // order
    $sql_order = $data['sort_field'] = $data['sort_type'] = '';
    // sort
    $sort_field_name = mgm_escape($sort_field_name);
    // for sql
    $sort_order_type = mgm_escape($sort_order_type);
    // for sql
    // check
    if (isset($sort_field_name)) {
        // set
        $data['sort_field'] = $sort_field_name;
        $data['sort_type'] = $sort_order_type;
        // init
        $custom_sort = false;
        // check
        if (array_key_exists($sort_field_name, $custom_sort_fields)) {
            $show_level_member = array_intersect($active_members, $show_level_members);
            // members
            $sql_order_by = mgm_userlist_customfield_sort($sort_field_name, $sort_order_type, $sql_filter, $show_level_member);
            // limit
            $lim = str_replace('LIMIT', '', $sql_limit);
            $lim = explode(',', $lim);
            // init
            $temp_array = array();
            // loop
            for ($i = trim($lim[0]); $i < $lim[0] + $lim[1]; $i++) {
                if (!empty($sql_order_by[$i])) {
                    $temp_array[] = $sql_order_by[$i];
                }
            }
            //check for active members
            //$temp_array = array_intersect ($active_members,$temp_array);
            $in_order = count($temp_array) == 0 ? 0 : implode(',', $temp_array);
            // order
            //$in_order = implode(',',$temp_array);
            if (!empty($temp_array)) {
                // set
                $sql_order = " ORDER BY FIELD( ID, {$in_order} ) ";
            } else {
                $sql_order = '';
            }
            // sql
            $sql = "SELECT * FROM `{$wpdb->users}` WHERE ID != 1 AND `ID` IN ({$in_order}) {$sql_order}";
            //  list
            $custom_user_list = $wpdb->get_results($sql);
            // flag
            $custom_sort = true;
        } else {
            // by name
            switch ($sort_field_name) {
                case 'username':
                    $sql_order_by = "user_login";
                    break;
                case 'id':
                    $sql_order_by = "ID";
                    break;
                case 'email':
                    $sql_order_by = "user_email";
                    break;
                case 'membership_type':
                    break;
                case 'reg_date':
                    $sql_order_by = "user_registered";
                    break;
            }
            // set
            if (isset($sql_order_by)) {
                $sql_order = " ORDER BY {$sql_order_by} {$sort_order_type}";
            }
        }
    }
    // default
    if (!isset($sql_order_by)) {
        $sql_order = " ORDER BY ID desc";
    }
    //default active members ids
    if (empty($sql_filter)) {
        //issue #1327
        if (!empty($show_level_members)) {
            // common
            $members = array_intersect($active_members, $show_level_members);
            $members_in = count($members) == 0 ? 0 : implode(',', $members);
        } else {
            $members_in = count($active_members) == 0 ? 0 : implode(',', $active_members);
        }
        // set filter
        $sql_filter = " AND `ID` IN ({$members_in})";
    }
    // get members
    $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM `{$wpdb->users}` WHERE ID != 1 {$sql_filter} {$sql_order} {$sql_limit}";
    // users
    $user_list = $wpdb->get_results($sql);
    // echo $wpdb->last_query;
    // set
    if ($custom_sort) {
        $data['users'] = $custom_user_list;
    } else {
        $data['users'] = $user_list;
    }
    // page url
    $data['page_url'] = add_query_arg(array('query' => $search_field_value, 'by' => $search_field_name, 'sort_field' => $sort_field_name, 'sort_order' => $sort_order_type), $current_url);
    //$url.'query='.$search_field_value.'&by='.$search_field_name.'&sort_field='.$sort_field_name.'&order_type='.$order_type;
    // get page links
    $data['page_links'] = $pager->get_pager_links($data['page_url']);
    // total pages
    $data['page_count'] = $pager->get_page_count();
    // total rows/results
    $data['row_count'] = $pager->get_row_count();
    //sort by filed
    $sort_field_html = sprintf('<select id="sort_field" name="sort_field" class="width100px">%s</select>', mgm_make_combo_options($data['sort_fields'], $data['sort_field'], MGM_KEY_VALUE));
    //order by asc/desc
    $sort_order_html = sprintf('<select id="sort_order" name="sort_order" class="width100px">%s</select>', mgm_make_combo_options($data['order_fields'], $data['sort_type'], MGM_KEY_VALUE));
    //search by
    $search_by_html = sprintf('<select id="by" name="by" class="width100px">%s</select>', mgm_make_combo_options($data['search_fields'], $data['search_field_name'], MGM_KEY_VALUE));
    //search box
    $html = '<div>
				<form method="get" action="' . $current_url . '">
					<h5>' . __('Search Our Members', 'mgm') . ':</h5>
					<input type="text" id="query" name="query" value="' . $data['search_field_value'] . '" /> 
					' . __('in', 'mgm') . ' ' . $search_by_html . ' ' . __('sort by', 'mgm') . ' ' . $sort_field_html . ' ' . $sort_order_html . '					
					<input class="button" type="submit" id="submit" value="' . __('Submit', 'mgm') . '" />
					<input type="hidden" name="search" id="search" value="search" />
				</form>
			</div>';
    $html .= '<div><table><tr>';
    for ($i = 0; $i < $use_field_len; $i++) {
        $html .= sprintf('<th class="th_div mgm_text_align_left mgm_column_%s" id="mgm_column_%s"><label><b>%s</b></label></th>', $use_field[$i], $use_field[$i], ucwords(str_replace('_', ' ', $use_field[$i])));
    }
    $html .= '</tr>';
    $enable_public_profile = mgm_get_class('system')->get_setting('enable_public_profile');
    if (!empty($data['users'])) {
        foreach ($data['users'] as $user) {
            // user object
            $user = get_userdata($user->ID);
            // mgm member object
            $member = mgm_get_member($user->ID);
            $html .= '<tr>';
            for ($i = 0; $i < $use_field_len; $i++) {
                $app_user_filed = 'user_' . $use_field[$i];
                if (isset($member->custom_fields->{$use_field}[$i]) || isset($user->{$use_field}[$i]) || isset($user->{$app_user_filed}) || $use_field[$i] == 'image') {
                    if ($use_field[$i] == 'image') {
                        //is_multisite,network_home_url
                        $html .= sprintf('<td align="left" valign="top" class="mgm_%s_value">', $use_field[$i]);
                        if (bool_from_yn($enable_public_profile)) {
                            //$profile_url = add_query_arg(array('username'=>$user->user_login), site_url('userprofile'));
                            $profile_url = network_site_url() . '/userprofile/?username='******'<a class="tern_wp_member_gravatar" href="%s">%s</a>', $profile_url, get_avatar($user->ID, 60));
                        } else {
                            $html .= sprintf('<a href="javascript://">%s</a>', get_avatar($user->ID, 60));
                        }
                        $html .= '</td>';
                    } else {
                        //getting data from user object
                        if (isset($user->{$use_field}[$i])) {
                            $member->custom_fields->{$use_field}[$i] = $user->{$use_field}[$i];
                        }
                        //getting data from user object
                        if ($use_field[$i] == 'email') {
                            $member->custom_fields->{$use_field}[$i] = $user->{$app_user_filed};
                        }
                        // val unserialize
                        $val = maybe_unserialize($member->custom_fields->{$use_field}[$i]);
                        // array to string
                        if (is_array($val)) {
                            $val = implode(', ', $val);
                        }
                        // set
                        $html .= sprintf('<td align="left" valign="top" class="mgm_%s_value"><b>%s</b></td>', $use_field[$i], $val);
                    }
                }
            }
            $html .= '</tr>';
        }
    } else {
        $html .= '<tr><td colspan="' . $use_field_len . '" align="center">' . __('No members found', 'mgm') . ' ...! </td></tr>';
    }
    $html .= '</table></div><br/>';
    $html .= '<div class="mgm_page_links_div">';
    if ($data['page_links']) {
        $html .= '<div class="pager-wrap">' . $data['page_links'] . '</div><div class="clearfix"></div>';
    }
    $html .= '</div><br/>';
    //issue #1635
    $users_list_html = '<div class="mgm_user_list_container">' . $html . '</div>';
    return $users_list_html;
}
Ejemplo n.º 9
0
/**
 * register post process
 *
 * @param int $user_id 
 * @return void or int $user_id
 */
function mgm_register($user_id)
{
    global $wpdb, $post;
    // check import in action and skip, tools->import calls mgm_register via "user_register" hook, this will help skip
    if (defined('MGM_DOING_USERS_IMPORT') && MGM_DOING_USERS_IMPORT == TRUE) {
        // return
        return $user_id;
    }
    // get mgm_system
    $system_obj = mgm_get_class('system');
    // hide
    $hide_custom_fields = $system_obj->get_setting('hide_custom_fields');
    // packs
    $packs = mgm_get_class('subscription_packs');
    // members object
    $member = mgm_get_member($user_id);
    // set status
    $member->set_field('status', MGM_STATUS_NULL);
    // get custom fields
    $cf_register_page = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_register' => true)));
    // mgm_subscription
    $mgm_subscription = mgm_post_var('mgm_subscription');
    // get subs
    $subs_pack = mgm_decode_package($mgm_subscription);
    // extract
    extract($subs_pack);
    // payment_gateways if set:
    $mgm_payment_gateways = mgm_post_var('mgm_payment_gateways');
    // Eg: $_POST['mgm_payment_gateways'] = mgm_paypal
    $cf_payment_gateways = !empty($mgm_payment_gateways) ? $mgm_payment_gateways : NULL;
    // init
    $member_custom_fields = array();
    // wordpress register
    $wordpres_form = mgm_check_wordpress_login();
    // system - issue #1237
    $short_format = !empty($system_obj->setting['date_format_short']) ? $system_obj->setting['date_format_short'] : MGM_DATE_FORMAT_SHORT;
    // loop
    foreach ($cf_register_page as $field) {
        // skip custom fields by settings call
        if ($hide_custom_fields == 'Y' || $hide_custom_fields == 'W' && $wordpres_form || $hide_custom_fields == 'C' && !$wordpres_form) {
            // if($hide_custom_fields && $field['name'] != 'subscription_options') continue;
            if (!in_array($field['name'], array('subscription_options', 'payment_gateways'))) {
                continue;
            }
        }
        //skip if payment_gateways custom field
        if ($field['name'] == 'payment_gateways') {
            continue;
        }
        //
        // do not save html
        if ($field['type'] == 'html' || $field['type'] == 'label') {
            continue;
        }
        // save
        switch ($field['name']) {
            case 'username':
                // #739
                if (isset($_POST[$field['attributes']['capture_field_alias']])) {
                    $member_custom_fields[$field['name']] = @$_POST[$field['attributes']['capture_field_alias']];
                } else {
                    $member_custom_fields[$field['name']] = @$_POST['user_login'];
                }
                break;
            case 'email':
                // #739
                if (isset($_POST[$field['attributes']['capture_field_alias']])) {
                    $member_custom_fields[$field['name']] = @$_POST[$field['attributes']['capture_field_alias']];
                } else {
                    $member_custom_fields[$field['name']] = @$_POST['user_email'];
                }
                break;
            case 'password':
                // #739
                // check
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    if (!empty($_POST[$field['attributes']['capture_field_alias']])) {
                        $user_password = @$_POST[$field['attributes']['capture_field_alias']];
                        $member_custom_fields[$field['name']] = mgm_encrypt_password($user_password, $user_id);
                    }
                } else {
                    if (!empty($_POST['user_password'])) {
                        $user_password = $_POST['user_password'];
                        $member_custom_fields[$field['name']] = mgm_encrypt_password($user_password, $user_id);
                    }
                }
                break;
            case 'autoresponder':
                // #739
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    // checked issue #839
                    // if(in_array(strtolower($_POST[$field['attributes']['capture_field_alias']]), array('y','yes'))){
                    if (!empty($_POST[$field['attributes']['capture_field_alias']]) && $_POST['mgm_register_field'][$field['name']] == $field['value']) {
                        $member->subscribed = 'Y';
                        $member->autoresponder = $system_obj->active_modules['autoresponder'];
                    }
                } else {
                    // checked issue #839
                    // if(in_array(strtolower($_POST['mgm_register_field'][$field['name']]), array('y','yes'))){
                    if (!empty($_POST['mgm_register_field'][$field['name']]) && $_POST['mgm_register_field'][$field['name']] == $field['value']) {
                        // set to member, to be used on payment
                        $member->subscribed = 'Y';
                        $member->autoresponder = $system_obj->active_modules['autoresponder'];
                    }
                }
                break;
            case 'coupon':
                // #739
                // check alias
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    // check
                    if (!empty($_POST[$field['attributes']['capture_field_alias']])) {
                        // validate
                        if ($coupon = mgm_validate_coupon($_POST[$field['attributes']['capture_field_alias']], $cost)) {
                            // set
                            $member->coupon = $coupon;
                            // update coupon usage
                            mgm_update_coupon_usage($coupon['id'], 'register');
                        }
                    }
                } else {
                    // check primary
                    if (isset($_POST['mgm_register_field'][$field['name']]) && !empty($_POST['mgm_register_field'][$field['name']])) {
                        // validate
                        if ($coupon = mgm_validate_coupon($_POST['mgm_register_field'][$field['name']], $cost)) {
                            // set
                            $member->coupon = $coupon;
                            // update coupon usage
                            mgm_update_coupon_usage($coupon['id'], 'register');
                        }
                    }
                }
                break;
            case 'birthdate':
                // #739
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    //issue #1237
                    $member_custom_fields[$field['name']] = mgm_format_inputdate_to_mysql($_POST[$field['attributes']['capture_field_alias']], $short_format);
                } else {
                    //convert from short date format to mysql format - issue #1237
                    $member_custom_fields[$field['name']] = mgm_format_inputdate_to_mysql($_POST['mgm_register_field'][$field['name']], $short_format);
                }
                break;
            default:
                // #739
                if (isset($field['attributes']['capture_field_alias']) && isset($_POST[$field['attributes']['capture_field_alias']])) {
                    $member_custom_fields[$field['name']] = @$_POST[$field['attributes']['capture_field_alias']];
                } elseif ($field['type'] == 'checkbox' && is_array(@$_POST['mgm_register_field'][$field['name']])) {
                    //$member_custom_fields[$field['name']] = implode(" ", @$_POST['mgm_register_field'][$field['name']]);
                    //issue #1070
                    $val = @$_POST['mgm_register_field'][$field['name']];
                    $member_custom_fields[$field['name']] = serialize($val);
                } else {
                    $member_custom_fields[$field['name']] = @$_POST['mgm_register_field'][$field['name']];
                }
                break;
        }
    }
    // end fields save
    // user password not provided
    /*
    	if (!isset( $user_password )){
    		$user_password = (isset($_POST['pass1']) && !empty($_POST['pass1'])) ? trim($_POST['pass1']) : substr(md5(uniqid(microtime())), 0, 7);		
    	}*/
    // user password not provided
    if (!isset($user_password)) {
        // take custom password fields, iss#717, consider BP custom password field
        $password_fields = array('pass1', 'signup_password');
        // loop
        foreach ($password_fields as $password_field) {
            // check if set
            if (isset($_POST[$password_field]) && !empty($_POST[$password_field])) {
                $user_password = trim($_POST[$password_field]);
                break;
            }
        }
    }
    // auto generate if still missing
    if (!isset($user_password)) {
        $user_password = substr(md5(uniqid(microtime())), 0, 7);
    }
    //encrypt password and save in
    $member->user_password = mgm_encrypt_password($user_password, $user_id);
    // md5
    $user_password_hash = wp_hash_password($user_password);
    // db update
    $wpdb->query($wpdb->prepare("UPDATE `{$wpdb->users}` SET `user_pass` = %s WHERE ID = %d", $user_password_hash, $user_id));
    // unset label fields
    if (isset($member_custom_fields['password_conf'])) {
        unset($member_custom_fields['password_conf']);
    }
    // set custom
    $member->set_custom_fields($member_custom_fields);
    // set pack
    if ($pack_id) {
        // pack
        $pack = $packs->get_pack($pack_id);
        // set
        $member->amount = $pack['cost'];
        $member->duration = $pack['duration'];
        $member->duration_type = $pack['duration_type'];
        $member->active_num_cycles = $pack['num_cycles'];
        // set membership type
        $member->membership_type = $membership_type;
        // from mgm_subscription
        // set in member
        $member->pack_id = $pack_id;
        // from mgm_subscription
    }
    // set status
    $member->status = MGM_STATUS_NULL;
    // update option
    $member->save();
    // update user firstname/last name
    mgm_update_default_userdata($user_id);
    // admin check
    $is_admin = is_admin();
    //&& current_user_can('manage_options');
    // send
    $notify_user = true;
    // Block registration emails if Buddypress is enabled and disable_registration_email_bp value is Yes
    $block_reg_email = bool_from_yn(mgm_get_class('system')->get_setting('disable_registration_email_bp'));
    // send notification, bp active, do not send password, #739
    if (!isset($_POST['send_password']) && $is_admin || mgm_is_plugin_active('buddypress/bp-loader.php') && $block_reg_email) {
        $notify_user = false;
    }
    // send notification - issue #1468
    if ($system_obj->setting['enable_new_user_email_notifiction_after_user_active'] == 'N') {
        if ($notify_user) {
            mgm_new_user_notification($user_id, $user_password, $is_admin ? false : true);
        }
        $notify_user = false;
    }
    // hook for other plugin who wishes to use default "user_register"
    do_action('mgm_user_register', $user_id);
    // process payment only when registered from site, not when user added by admin
    if ($is_admin) {
        // unset
        unset($_POST['send_password']);
        //prevent sending user email again
        // assign default pack
        do_action('mgm_admin_user_register', $user_id, $notify_user);
        // return id
        return $user_id;
    }
    // if on wordpress page or custompage
    $post_id = get_the_ID();
    // post custom register
    if ($post_id > 0 && $post->post_type == 'post') {
        $redirect = get_permalink($post_id);
    } else {
        $redirect = mgm_get_custom_url('transactions');
    }
    // if buddypress url replace by register url : issue#: 791
    $redirect = apply_filters('mgm_bp_register_url', $redirect);
    // userdata
    $userdata = get_userdata($user_id);
    // note this fix VERY IMPORTANT, needed for PAYPAL PRO CC POST
    $redirect = add_query_arg(array('username' => urlencode($userdata->user_login)), $redirect);
    // add redirect
    if ($redirector = mgm_request_var('mgm_redirector', mgm_request_var('redirect_to', '', true), true)) {
        $redirect = add_query_arg(array('redirector' => $redirector), $redirect);
    }
    // with subscription
    if ($mgm_subscription) {
        $redirect = add_query_arg(array('subs' => $mgm_subscription, 'method' => 'payment_subscribe'), $redirect);
    }
    // bypass step2 if payment gateway is submitted: issue #: 469
    if (!is_null($cf_payment_gateways)) {
        // pack
        $packs_obj = mgm_get_class('subscription_packs');
        // validate
        $pack = $packs_obj->validate_pack($cost, $duration, $duration_type, $membership_type, $pack_id);
        // error
        if ($pack != false) {
            // get pack
            mgm_get_register_coupon_pack($member, $pack);
            // cost
            if ((double) $pack['cost'] > 0) {
                //get an object of the payment gateway:
                $mod_obj = mgm_get_module($cf_payment_gateways, 'payment');
                // tran options
                $tran_options = array('is_registration' => true, 'user_id' => $user_id, 'notify_user' => $notify_user);
                // is register & purchase
                if (isset($_POST['post_id'])) {
                    $tran_options['post_id'] = (int) $_POST['post_id'];
                }
                // is register & purchase postpack
                if (isset($_POST['postpack_post_id']) && isset($_POST['postpack_id'])) {
                    $tran_options['postpack_post_id'] = (int) $_POST['postpack_post_id'];
                    $tran_options['postpack_id'] = (int) $_POST['postpack_id'];
                }
                // create transaction
                // $tran_id = $mod_obj->_create_transaction($pack, $tran_options);
                $tran_id = mgm_add_transaction($pack, $tran_options);
                //bypass directly to process return if manual payment:
                if ($cf_payment_gateways == 'mgm_manualpay') {
                    // set
                    $_POST['custom'] = $tran_id;
                    // direct call to module return function:
                    $mod_obj->process_return();
                    // exit
                    exit;
                }
                // encode id:
                $tran_id = mgm_encode_id($tran_id);
                // redirect - if on wordpress page or custompage - issue #1648
                if ($post_id > 0 && $post->post_type == 'post') {
                    $redirect = $mod_obj->_get_endpoint('html_redirect', true);
                } else {
                    $redirect = $mod_obj->_get_endpoint('html_redirect', false);
                }
                // if buddypress url replace by register url : issue#: 791
                $redirect = add_query_arg(array('tran_id' => $tran_id), apply_filters('mgm_bp_register_url', $redirect));
            } else {
                // issue #1468
                $redirect = add_query_arg(array('notify_user' => $notify_user), $redirect);
            }
        }
    }
    // ends custom payment gateway bypassing
    // is register & purchase
    if (isset($_POST['post_id'])) {
        $redirect = add_query_arg(array('post_id' => (int) $_POST['post_id']), $redirect);
    }
    // is register & purchase postpack
    if (isset($_POST['postpack_post_id']) && isset($_POST['postpack_id'])) {
        $redirect = add_query_arg(array('postpack_id' => (int) $_POST['postpack_id'], 'postpack_post_id' => (int) $_POST['postpack_post_id']), $redirect);
    }
    // redirect filter, returing a false can stop the redirect
    $redirect = apply_filters('mgm_after_regiter_redirect', mgm_site_url($redirect));
    // redirect
    if ($redirect !== FALSE) {
        // do the redirect to payment
        mgm_redirect($redirect);
        // this goes to subscribe, mgm_functions.php/mgm_get_subscription_buttons
        // exit
        exit;
    }
    // default
    return $user_id;
}
    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));
    }
/**
 * Convert MGM_DATE_FORMAT_INPUT to date picker format/date value to input field format(MGM_DATE_FORMAT_INPUT)
 * MGM_DATE_FORMAT_INPUT will always be fixed as we accept only numeric date value from input fields
 *
 */
function mgm_get_datepicker_format($type = 'format', $date = null)
{
    // system
    $system_obj = mgm_get_class('system');
    //Issue # 680
    $short_format = !empty($system_obj->setting['date_format_short']) ? $system_obj->setting['date_format_short'] : MGM_DATE_FORMAT_SHORT;
    $input_format = $short_format;
    if ($type == 'format') {
        //formats supported by jQuery datepicker:
        $delimiters = array(',', '\\/', '-', ' ', ';');
        $delimiter = '/';
        foreach ($delimiters as $d) {
            if (preg_match("/{$d}/", $input_format)) {
                $delimiter = stripslashes($d);
            }
        }
        $format_splitted = explode($delimiter, $input_format);
        foreach ($format_splitted as $key => $fs) {
            $fs = trim($fs);
            switch ($fs) {
                //year
                case 'y':
                    $arr_format[] = $fs;
                    break;
                case 'Y':
                    $arr_format[] = 'yy';
                    break;
                    //month
                //month
                case 'F':
                    $arr_format[] = 'MM';
                    break;
                case 'm':
                    $arr_format[] = 'mm';
                    break;
                case 'M':
                    $arr_format[] = 'M';
                    break;
                case 'n':
                    $arr_format[] = 'm';
                    break;
                    //day
                //day
                case 'd':
                    $arr_format[] = 'dd';
                    break;
                case 'D':
                    $arr_format[] = 'D';
                    break;
                case 'j':
                    $arr_format[] = 'd';
                    break;
                case 'l':
                    $arr_format[] = 'DD';
                    break;
            }
        }
        if (count($arr_format) < 3) {
            $arr_format = array(0 > 'm', 1 => 'd', 2 => 'Y');
        }
        return implode($delimiter, $arr_format);
    } elseif ($type == 'date' && !is_null($date)) {
        if (mgm_is_mysql_dateformat($date)) {
            $conv_date = date($input_format, strtotime($date));
        } else {
            //backward compatibility - convert all the previously saved dates to mysql format
            $date = mgm_format_inputdate_to_mysql($date);
            $conv_date = date($input_format, strtotime($date));
        }
        return $conv_date;
    }
}
 function post_purchase_export()
 {
     global $wpdb;
     // data
     $data = array();
     // filter
     $sql_filter = $data['search_field_name'] = $data['search_field_value'] = '';
     $search_field_name = mgm_post_var('search_field_name');
     // check
     if (!empty($search_field_name)) {
         // post
         $search_field_value = mgm_post_var('search_field_value');
         $search_field_value_two = mgm_post_var('search_field_value_two');
         // view data
         $data['search_field_name'] = $search_field_name;
         // for display
         //issue #1281
         $data['search_field_value'] = htmlentities($search_field_value, ENT_QUOTES, "UTF-8");
         // for display
         $data['search_field_value_two'] = htmlentities($search_field_value_two, ENT_QUOTES, "UTF-8");
         // for display
         //searc value
         $search_field_value = esc_sql($search_field_value);
         // for sql
         // end date value
         $search_field_value_two = esc_sql($search_field_value_two);
         // for sql
         //current date
         $curr_date = mgm_get_current_datetime();
         $current_date = $curr_date['timestamp'];
         // by field
         switch ($search_field_name) {
             case 'user_login':
                 $sql_filter = " AND (`user_login` LIKE '%{$search_field_value}%' OR `guest_token` LIKE '%{$search_field_value}%')";
                 break;
             case 'post_title':
                 $sql_filter = " AND (`post_title` LIKE '%{$search_field_value}%')";
                 break;
             case 'is_gift':
                 $sql_filter = " AND (`is_gift` = '{$search_field_value}')";
                 break;
             case 'purchase_dt':
                 // date start
                 if (empty($search_field_value)) {
                     $search_field_value = date('Y-m-d', $current_date);
                 }
                 // date end
                 if (empty($search_field_value_two)) {
                     $search_field_value_two = date('Y-m-d', $current_date);
                 }
                 // convert
                 $search_field_value = mgm_format_inputdate_to_mysql($search_field_value);
                 $search_field_value_two = mgm_format_inputdate_to_mysql($search_field_value_two);
                 // set
                 $sql_filter = " AND (DATE_FORMAT(`pp`.`purchase_dt`,'%Y-%m-%d') BETWEEN '{$search_field_value}' AND '{$search_field_value_two}')";
                 break;
         }
     }
     // order
     $sql_order = " ORDER BY u.user_login, p.post_title";
     // sql
     $sql = "SELECT SQL_CALC_FOUND_ROWS p.ID AS post_id, p.post_title, pp.purchase_dt, \r\r\n\t\t        IF(user_id IS NULL, CONCAT('guest-', guest_token), u.user_login) AS user_login, pp.id,\r\r\n\t\t        pp.is_gift,pp.is_expire FROM `" . TBL_MGM_POST_PURCHASES . "` pp \r\r\n\t\t\t\tLEFT JOIN " . $wpdb->posts . " p ON (p.id = pp.post_id) \r\r\n\t\t\t\tLEFT JOIN " . $wpdb->users . " u ON (u.ID = pp.user_id) WHERE 1 \r\r\n\t\t\t\t{$sql_filter} {$sql_order} ";
     // log
     // mgm_log($sql);
     // store
     $data['post_purchases'] = $wpdb->get_results($sql);
     // date format
     $date_format = mgm_get_date_format('date_format');
     // init
     $purchases = array();
     // check
     if (count($data['post_purchases']) > 0) {
         //purchases
         foreach ($data['post_purchases'] as $purchase) {
             // int
             $row = new stdClass();
             // type
             $type = $purchase->is_gift == 'Y' ? __('Gift', 'mgm') : __('Purchase', 'mgm');
             // check is_expiry
             if ($purchase->is_expire == 'N') {
                 $expiry = __('Indefinite', 'mgm');
             } else {
                 $expiry = mgm_get_post($purchase->post_id)->get_access_duration();
                 $expiry = !$expiry ? __('Indefinite', 'mgm') : date($date_format, 86400 * $expiry + strtotime($purchase->purchase_dt)) . " (" . $expiry . __(' D', 'mgm') . ")";
             }
             // member name
             if (preg_match('/^guest-/', $purchase->user_login)) {
                 // guest token
                 $guest_token = str_replace('guest-', '', $purchase->user_login);
                 // username
                 $username = __('Guest', 'mgm') . sprintf(' (%s)', $guest_token);
             } else {
                 // username
                 $username = $purchase->user_login;
             }
             //export fields
             $row->username = $username;
             $row->post = $purchase->post_title;
             $row->type = $type;
             $row->expire_date = $expiry;
             $row->purchase_or_gift_date = date($date_format, strtotime($purchase->purchase_dt));
             // cache
             $purchases[] = $row;
             // unset
             unset($row);
         }
     }
     // default response
     $response = array('status' => 'error', 'message' => __('Error while exporting post (purchase/gift)s.', 'mgm'));
     // check
     if (count($purchases) > 0) {
         // success
         $success = count($purchases);
         // create
         if (mgm_post_var('export_format') == 'csv') {
             $filename = mgm_create_csv_file($purchases, 'post_purchases');
         } else {
             $filename = mgm_create_xls_file($purchases, 'post_purchases');
         }
         // src
         $file_src = MGM_FILES_EXPORT_URL . $filename;
         // message
         $message = sprintf(__('Successfully exported %d post %s.', 'mgm'), $success, $success > 1 ? 'purchases' : 'purchase');
         // init
         $response = array('status' => 'success', 'message' => $message, 'src' => $file_src);
     }
     // return response
     echo json_encode($response);
     exit;
 }