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));
 }
 function pages()
 {
     global $wpdb;
     extract($_POST);
     // set
     if (isset($update) && !empty($update)) {
         // get system object
         $system_obj = mgm_get_class('system');
         // update
         $system_obj->setting['excluded_pages'] = $_POST['excluded_pages'];
         // save
         $system_obj->save();
         // update
         $message = __('Page exclusion settings successfully updated.', 'mgm');
         $status = 'success';
         // return response
         echo json_encode(array('status' => $status, 'message' => $message));
         exit;
     }
     // data
     $data = array();
     // all pages
     $data['pages'] = mgm_field_values($wpdb->posts, 'ID', 'post_title', "AND post_status = 'publish' AND post_type IN ('page')", 'post_title');
     // excluded pages
     $data['pages_excluded'] = mgm_get_class('system')->get_setting('excluded_pages', array());
     // load template view
     $this->load->template('contents/pages', array('data' => $data));
 }
 function posts()
 {
     global $wpdb;
     // local
     extract($_POST);
     // update
     if (isset($post_setup_save) && !empty($post_setup_save)) {
         // init updatd
         $updated = 0;
         // get system object
         $system_obj = mgm_get_class('system');
         //$setting['enable_facebook']= $system_obj->setting['enable_facebook'];
         // content protection
         $content_protection = $system_obj->setting['content_protection'];
         //Issue #720
         if (isset($add_private_tags)) {
             if ($add_private_tags == 'Y') {
                 $system_obj->setting['add_private_tags'] = 'Y';
                 $system_obj->save();
             }
         } else {
             $system_obj->setting['add_private_tags'] = 'N';
             $system_obj->save();
         }
         // membership types
         if (is_array($access_membership_types)) {
             $membership_types = json_encode($access_membership_types);
         } else {
             $membership_types = json_encode(array());
         }
         // init posts
         $wp_posts = array();
         // posts
         if (isset($posts)) {
             $wp_posts = array_merge($wp_posts, $posts);
         }
         // pages
         if (isset($pages)) {
             $wp_posts = array_merge($wp_posts, $pages);
         }
         // custom post types
         if (isset($custom_post_types)) {
             $wp_posts = array_merge($wp_posts, $custom_post_types);
         }
         // add direct urls
         if ($direct_urls) {
             // loop
             foreach ($direct_urls as $direct_url_id => $direct_url) {
                 // affected
                 $affected = false;
                 // insert
                 if (!empty($direct_url)) {
                     // check duplicate
                     if (!mgm_is_duplicate(TBL_MGM_POST_PROTECTED_URL, array('url'), '', array('url' => $direct_url))) {
                         // add
                         $affected = $wpdb->insert(TBL_MGM_POST_PROTECTED_URL, array('url' => $direct_url, 'membership_types' => $membership_types));
                     }
                 }
                 // update counter
                 if ($affected) {
                     $updated++;
                 }
             }
         }
         // check
         if ($wp_posts) {
             // loop
             foreach ($wp_posts as $post_id) {
                 // get object
                 $post_obj = mgm_get_post($post_id);
                 //Issue #838
                 if (isset($purchasable) == 'Y') {
                     // set
                     $post_obj->purchasable = $purchasable;
                 }
                 // check
                 if (isset($purchase_cost) && isset($purchasable) == 'Y') {
                     // check
                     if (!empty($purchase_cost) && $purchase_cost > 0) {
                         // set
                         $post_obj->purchase_cost = $purchase_cost;
                     }
                 }
                 // apply filter
                 $post_obj = apply_filters('mgm_post_update', $post_obj, $post_id);
                 // save meta
                 $post_obj->save();
                 // if access set
                 if (is_array($access_membership_types)) {
                     // set
                     $post_obj->access_membership_types = $access_membership_types;
                     // apply filter
                     $post_obj = apply_filters('mgm_post_update', $post_obj, $post_id);
                     // save meta
                     $post_obj->save();
                     // unset
                     unset($post_obj);
                     // check duplicate
                     if (!mgm_is_duplicate(TBL_MGM_POST_PROTECTED_URL, array('post_id'), '', array('post_id' => $post_id))) {
                         // add
                         $affected = $wpdb->insert(TBL_MGM_POST_PROTECTED_URL, array('url' => get_permalink($post_id), 'post_id' => $post_id, 'membership_types' => $membership_types));
                     } else {
                         $affected = $wpdb->update(TBL_MGM_POST_PROTECTED_URL, array('membership_types' => $membership_types), array('post_id' => $post_id));
                     }
                 }
                 // make private, add [private] tag
                 if (mgm_protect_content($content_protection)) {
                     // get post
                     $wp_post = wp_get_single_post($post_id);
                     // Check private tag on/off Issue #720
                     if (bool_from_yn($system_obj->setting['add_private_tags'])) {
                         // double check, not already added
                         if (preg_match('/\\[private\\](.*)\\[\\/private\\]/', $wp_post->post_content) == FALSE) {
                             // make content private
                             $post_content = sprintf('[private]%s[/private]', $wp_post->post_content);
                             // update
                             wp_update_post(array('post_content' => $post_content, 'ID' => $wp_post->ID));
                         }
                     }
                 }
                 // update counter
                 $updated++;
             }
         }
         // response
         if ($updated) {
             $response = array('status' => 'success', 'message' => sprintf(__('Post protection successfully updated. %d Post/Page(s) updated.', 'mgm'), $updated));
         } else {
             $response = array('status' => 'error', 'message' => sprintf(__('Post protection failed. %d Post/Page(s) selected.', 'mgm'), $updated));
         }
         // print
         echo json_encode($response);
         // return
         return;
     }
     // data
     $data = array();
     // member types
     $arr_membershiptypes = array();
     // loop
     foreach (mgm_get_class('membership_types')->membership_types as $code => $name) {
         $arr_membershiptypes[$code] = mgm_stripslashes_deep($name);
     }
     // set
     $data['membership_types'] = $arr_membershiptypes;
     // posts
     $data['posts'] = mgm_field_values($wpdb->posts, 'ID', 'post_title', "AND (post_content NOT LIKE '%[private]%' OR post_content LIKE '[private]%') AND post_type = 'post' AND post_status = 'publish'");
     // pages
     $data['pages'] = mgm_field_values($wpdb->posts, 'ID', 'post_title', "AND (post_content NOT LIKE '%[private]%' OR post_content LIKE '[private]%') AND post_type = 'page' AND post_status = 'publish'");
     // custom post types
     if ($post_types = mgm_get_post_types(true, array('page', 'post'))) {
         $data['custom_post_types'] = mgm_field_values($wpdb->posts, 'ID', "CONCAT(post_title, ' ( ', post_type, ' )') AS post_title", "AND (post_content NOT LIKE '%[private]%' OR post_content LIKE '[private]%') AND post_type IN ({$post_types}) AND post_status = 'publish'", 'post_title');
     } else {
         $data['custom_post_types'] = array();
     }
     // posts access
     $data['posts_access'] = $wpdb->get_results(sprintf("SELECT * FROM %s WHERE `post_id` IS NOT NULL ORDER BY id ASC", TBL_MGM_POST_PROTECTED_URL));
     // direct urls access
     $data['direct_urls_access'] = $wpdb->get_results(sprintf("SELECT * FROM %s WHERE `post_id` IS NULL ORDER BY id ASC", TBL_MGM_POST_PROTECTED_URL));
     // load template view
     $this->load->template('settings/posts', array('data' => $data));
 }
 function field_country_callback($field, $name, $value)
 {
     // options
     $options = mgm_field_values(TBL_MGM_COUNTRY, 'code', 'name');
     // default
     if (empty($field['value'])) {
         $field['value'] = 'US';
     }
     // read only
     if ($field['attributes']['readonly']) {
         $options = array($value => $options[$value]);
     }
     // return
     return $this->field_type_select($field, $name, $value, $options, MGM_KEY_VALUE);
 }
/**
 * edit custom fields
 */
function mgm_edit_custom_fields($user_ID = false, $submit_row = false, $return = false)
{
    // get user
    if (!$user_ID) {
        $user_ID = mgm_get_user_id();
    }
    // get form object
    if (is_object($user_ID)) {
        $user_ID = $user_ID->ID;
    }
    //check logged in user is super admin:
    $is_admin = is_super_admin() ? true : false;
    // system
    $system_obj = mgm_get_class('system');
    // get custom_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)));
    //issue #844 - get active custom fields for profile page
    $cf_profile_pg = mgm_get_class('member_custom_fields');
    $cf_profile_page = 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['display']['on_profile'] || $is_admin)) {
                $cf_profile_page[] = $field;
            }
        }
    }
    $member = mgm_get_member($user_ID);
    //this is a fix for issue#: 589, see the notes for details:
    //This is to read saved coupons as array in order to fix the fatal error on some servers.
    //This will change the object on each users profile view.
    //Also this will avoid using patch for batch update,
    $arr_coupon = array('upgrade', 'extend');
    $oldcoupon_found = 0;
    foreach ($arr_coupon as $cpn_type) {
        if (isset($member->{$cpn_type}['coupon']) && is_object($member->{$cpn_type}['coupon'])) {
            $member->{$cpn_type}['coupon'] = (array) $member->{$cpn_type}['coupon'];
            $oldcoupon_found++;
        }
    }
    if ($oldcoupon_found) {
        $member->save();
    }
    // user
    $user = get_userdata($user_ID);
    // init
    $html = '';
    // capture
    $fields = array();
    //default and readonly fields:
    $default_readonly = array();
    $arr_images = array();
    //issue #844
    $skip_fileds = array('subscription_introduction', 'coupon', 'privacy_policy', 'payment_gateways', 'terms_conditions', 'subscription_options', 'autoresponder', 'captcha', 'show_public_profile');
    // loop fields
    foreach ($cf_profile_page as $field) {
        // issue#: 255
        if (in_array($field['name'], array_keys($profile_fields))) {
            //if custom field = defualt field, is read only
            if ($field['attributes']['readonly'] && !$is_admin) {
                $default_readonly[] = $profile_fields[$field['name']]['id'];
                //email and url id is different than custom fields:
                if (in_array($field['name'], array('email', 'url'))) {
                    $default_readonly[] = $field['name'];
                }
            }
            continue;
        }
        //issue #844
        if (in_array($field['name'], $skip_fileds)) {
            continue;
        }
        // init value
        $value = '';
        //disable readonly for admin user(issue#: 515)
        $ro = $field['attributes']['readonly'] == true && !$is_admin ? 'readonly="readonly"' : false;
        // value
        if (isset($member->custom_fields->{$field}['name'])) {
            $value = $member->custom_fields->{$field}['name'];
        }
        // date
        if ($field['name'] == 'birthdate') {
            if ($value) {
                //convert saved date to input field format
                $value = mgm_get_datepicker_format('date', $value);
            } else {
                $value = '';
            }
            $element = '<input type="text" name="mgm_profile_field[' . $field['name'] . ']" value="' . $value . '" ' . $ro . ' class="text ' . ($ro ? '' : 'mgm_date') . ' mgm_custom_profile_birthdate"/>';
        } else {
            if ($field['name'] == 'country') {
                $countries = mgm_field_values(TBL_MGM_COUNTRY, 'code', 'name');
                if ($ro) {
                    $countries = !empty($value) ? array($value => $countries[$value]) : array(" " => "&nbsp;");
                }
                //issue #1782
                $value = !empty($value) ? $value : 'US';
                $options = mgm_make_combo_options($countries, $value, MGM_KEY_VALUE);
                $element = '<select name="mgm_profile_field[' . $field['name'] . ']" > ' . $options . ' </select>';
            } else {
                if ($field['type'] == 'text') {
                    $element = '<input type="text" name="mgm_profile_field[' . $field['name'] . ']" value="' . $value . '" ' . $ro . ' class="text mgm_custom_profile_password"/>';
                } else {
                    if ($field['type'] == 'password') {
                        continue;
                    } else {
                        if ($field['type'] == 'textarea') {
                            $element = '<textarea name="mgm_profile_field[' . $field['name'] . ']" cols="40" rows="5" ' . $ro . '>' . $value . '</textarea>';
                        } else {
                            if ($field['type'] == 'checkbox') {
                                $options = preg_split('/[;,]/', $field['options']);
                                //$values  = preg_split('/[;,\s]/', $value);
                                $values = @unserialize($value);
                                // pass " " as value to prevent the default value getting selected, if no option is selected
                                $values = empty($values) ? " " : $values;
                                //Issue # 694
                                $element = mgm_make_checkbox_group('mgm_profile_field[' . $field['name'] . '][]', $options, $values, MGM_VALUE_ONLY, '', 'div');
                            } else {
                                if ($field['type'] == 'checkboxg') {
                                    $options = preg_split('/[;,]/', $field['options']);
                                    if (!is_array($value)) {
                                        $values = @unserialize($value);
                                    } else {
                                        $values = $value;
                                    }
                                    $values = empty($values) ? " " : $values;
                                    $element = mgm_make_checkbox_group('mgm_profile_field[' . $field['name'] . '][]', $options, $values, MGM_VALUE_ONLY, '', 'div');
                                } else {
                                    if ($field['type'] == 'radio') {
                                        $options = preg_split('/[;,]/', $field['options']);
                                        $element = mgm_make_radio_group('mgm_profile_field[' . $field['name'] . ']', $options, $value, MGM_VALUE_ONLY);
                                    } else {
                                        if ($field['type'] == 'select') {
                                            $element = '<select name="mgm_profile_field[' . $field['name'] . ']" ' . $ro . '>';
                                            $options = preg_split('/[;,]/', $field['options']);
                                            if ($ro) {
                                                $options = !empty($value) ? array($value => $value) : array(" " => "&nbsp;");
                                            }
                                            $element .= mgm_make_combo_options($options, $value, MGM_VALUE_ONLY);
                                            $element .= '</select>';
                                        } else {
                                            if ($field['type'] == 'selectm') {
                                                $element = '<select name="mgm_profile_field[' . $field['name'] . '][]" ' . $ro . ' multiple>';
                                                $options = preg_split('/[;,]/', $field['options']);
                                                if ($ro) {
                                                    $options = !empty($value) ? array($value => $value) : array(" " => "&nbsp;");
                                                }
                                                $element .= mgm_make_combo_options($options, $value, MGM_VALUE_ONLY);
                                                $element .= '</select>';
                                            } else {
                                                if ($field['type'] == 'html') {
                                                    $element = '';
                                                    $element .= '<div class="mgm_custom_subs_introduction">' . html_entity_decode(mgm_stripslashes_deep($field['value'])) . '</div>';
                                                } else {
                                                    if ($field['type'] == 'image') {
                                                        $form_fields = new mgm_form_fields();
                                                        $element = $form_fields->get_field_element($field, 'mgm_profile_field', $value);
                                                        if (!in_array($field['name'], $arr_images)) {
                                                            $arr_images[] = $field['name'];
                                                        }
                                                        //issue #1258
                                                    } else {
                                                        if ($field['type'] == 'label') {
                                                            $form_fields = new mgm_form_fields();
                                                            $element = $form_fields->get_field_element($field, 'mgm_profile_field', $value);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // set array
        if ($element) {
            $fields[] = array('name' => $field['name'], 'label' => $field['label'], 'field' => $element);
        }
    }
    // if fields - issue #1782
    if (count($fields)) {
        $html .= '<table class="form-table">';
        foreach ($fields as $i => $row) {
            $html .= '<tr><th><label>' . mgm_stripslashes_deep($row['label']) . '</label></th>';
            $html .= '<td>' . $row['field'] . '</td></tr>';
        }
        // button
        if ($submit_row) {
            $html .= '<tr>
				<td colspan="2">
					<input class="button" type="submit" name="submit" value="' . __('Update your profile', 'mgm') . '"/>
					<input type="hidden" name="update_mgm_custom_fields_submit" value="1" />
			</td></tr>';
        }
        $html .= '</table>';
        $html .= mgm_attach_scripts(true, array());
        $yearRange = mgm_get_calendar_year_range();
        //include scripts for image upload:
        if (!empty($arr_images)) {
            $html .= mgm_upload_script_js('your-profile', $arr_images);
        }
        $html .= '<script language="javascript">jQuery(document).ready(function(){try{mgm_date_picker(".mgm_date",false,{yearRange:"' . $yearRange . '", dateFormat: "' . mgm_get_datepicker_format() . '"});}catch(x){}});</script>';
    }
    if (!empty($default_readonly)) {
        $html .= '<script language="javascript">';
        $html .= 'jQuery(document).ready(function(){try{';
        $html .= 'jQuery.each(' . json_encode($default_readonly) . ', function(){jQuery("#"+this).attr("readonly", true)})';
        $html .= '}catch(x){}})';
        $html .= '</script>';
    }
    // return
    if ($return) {
        return $html;
    } else {
        echo $html;
    }
}
 function post_purchase_gift()
 {
     global $wpdb;
     extract($_POST);
     // save
     if (isset($send_gift)) {
         // user data
         $user = get_userdata($user_id);
         $post = get_post($post_id);
         // expire
         if (!isset($is_expire) || empty($is_expire)) {
             $is_expire = 'Y';
         }
         // sql
         $sql = $wpdb->prepare("REPLACE INTO `" . TBL_MGM_POST_PURCHASES . "` SET `user_id`=%d, `post_id`=%d, \r\r\n\t\t\t       \t\t\t\t  `is_gift`=%s,`purchase_dt`=NOW(), `is_expire`=%s", $user_id, $post_id, 'Y', $is_expire);
         // saved
         if ($wpdb->query($sql)) {
             $message = sprintf(__('Successfully gifted post - "%s" to member - "%s".', 'mgm'), $post->post_title, $user->display_name);
             $status = 'success';
         } else {
             $message = sprintf(__('Error while gifting post - "%s" to member - "%s".', 'mgm'), $post->post_title, $user->display_name);
             $status = 'error';
         }
         // return response
         echo json_encode(array('status' => $status, 'message' => $message));
         exit;
     }
     // data
     $data = array();
     // users
     $data['users'] = mgm_field_values($wpdb->users, 'ID', 'user_login', "AND ID<>1", 'user_login');
     // posts
     $data['posts'] = mgm_get_purchasable_posts();
     // load template view
     $this->load->template('payperpost/post_purchases/gift', array('data' => $data));
 }