/** 
  * get gifted contents
  *
  * @verb GET
  * @action all 	
  * @url <site>/mgmapi/contents/gifted.<format>  -- list all post types
  * @url <site>/mgmapi/contents/gifted/:(posts|pages|custom_post_type).<format> -- list only specified post type
  * @url <site>/mgmapi/contents/gifted/:(posts|pages|custom_post_type)/:id.<format> -- list specified post type by post id
  *	
  * @param string $post_type
  * @param int $id
  * @since 1.0
  */
 public function gifted_get($post_type = '', $id = NULL)
 {
     global $wpdb;
     // get vars
     $get_vars = $this->request->data['get'];
     // start
     $start = isset($get_vars['start']) ? (int) $get_vars['start'] : 0;
     // rows
     $rows = isset($get_vars['rows']) ? (int) $get_vars['rows'] : 100;
     // status
     $status = 'success';
     $message = '';
     // registered post types
     $post_types = mgm_get_post_types(false);
     // all post types
     if (empty($post_type)) {
         // get
         $contents = $this->_get_purchased_contents($post_types, $id, $start, $rows, true);
         // content type
         $content_type = 'all post types';
     } else {
         // post/page
         if (in_array($post_type, array('posts', 'pages'))) {
             $post_type = mgm_singular($post_type);
         }
         // validate
         if (!in_array($post_type, $post_types)) {
             // error
             $status = 'error';
             $message = sprintf(__('Specified post type - %s is invalid, try with a valid post type only', 'mgm'), $post_type);
         } else {
             // get
             $contents = $this->_get_purchased_contents($post_type, $id, $start, $rows, true);
             // content type
             $content_type = $post_type;
         }
     }
     // name
     $content_type_name = 'contents';
     // data when contents found
     if (isset($contents)) {
         // total rows
         $total_rows = count($contents);
         // base
         $data = array('total_rows' => $total_rows);
         // by id
         if (isset($id) && (int) $id > 0) {
             // message
             $message = sprintf(__('Get gifted - %s dy id#%d response', 'mgm'), $content_type, $id);
             // data
             if ($total_rows > 0) {
                 $data = $data + array(mgm_singular($content_type_name) => array_shift($contents));
             }
         } else {
             // all
             // message
             $message = sprintf(__('Get gifted - %s response - %d %s found', 'mgm'), $content_type, $total_rows, $content_type);
             // data
             if ($total_rows > 0) {
                 $data = $data + array($content_type_name => $contents);
             }
         }
     }
     // response
     $response = array('status' => $status, 'message' => $message);
     // data
     if (isset($data)) {
         $response = $response + array('data' => $data);
     }
     // return
     return array($response, 200);
 }
 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 mgm_get_purchasable_posts($exclude = false)
{
    global $wpdb;
    // exclude
    $exclude_sql = '';
    if (is_array($exclude) && count($exclude) > 0) {
        $exclude_sql = "AND A.ID NOT IN (" . implode(',', $exclude) . ")";
    }
    // get types
    $post_types_in = mgm_get_post_types(true);
    // update to include both _mgm_post_options and _mgm_post for old and new option name
    // sql
    $sql = "SELECT DISTINCT(A.ID) AS id, A.post_title AS post_title FROM " . $wpdb->posts . " A\tJOIN " . $wpdb->postmeta . " B \r\r\n\t        ON (A.ID = B.post_id AND B.meta_key LIKE '_mgm_post%' ) WHERE A.post_status = 'publish' \r\r\n\t\t\tAND A.post_type IN ({$post_types_in}) {$exclude_sql} ORDER BY A.post_title";
    // fetch
    $rows = $wpdb->get_results($sql);
    // init
    $purchasable_posts = array();
    // captured
    if ($rows) {
        // loop
        foreach ($rows as $row) {
            // get post object
            $post_obj = mgm_get_post($row->id);
            // in array
            if ($post_obj->purchasable == 'Y') {
                $purchasable_posts[$row->id] = $row->post_title;
            }
            // unset
            unset($post_obj);
        }
    }
    // return
    return $purchasable_posts;
}
 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 mgm_get_posts_for_level($membership_type = '', $show_all = true)
{
    global $wpdb, $post;
    if (!empty($membership_type)) {
        if (!is_array($membership_type)) {
            $membership_type = array(0 => $membership_type);
        }
        // get post types
        $post_types_in = mgm_get_post_types(true);
        // id
        $post_id_notin = is_numeric($post->ID) ? $post->ID : 0;
        // sql
        $limit = 50;
        $per_page = 10;
        $sql = "SELECT DISTINCT(ID), post_title, post_date, post_content\r\r\n\t\t\t\tFROM " . $wpdb->posts . " A JOIN " . $wpdb->postmeta . " B ON (A.ID = B.post_id ) \r\r\n\t\t\t\tWHERE post_status = 'publish' AND B.meta_key LIKE '_mgm_post%' \r\r\n\t\t\t\tAND post_type IN ({$post_types_in}) AND A.id NOT IN({$post_id_notin}) \r\r\n\t\t\t\tORDER BY post_date DESC LIMIT 0," . $limit;
        // get posts
        $results = $wpdb->get_results($sql);
        // chk
        if (count($results) > 0) {
            // set counter
            $total = 0;
            // loop
            foreach ($results as $id => $obj) {
                // post
                $post_obj = mgm_get_post($obj->ID);
                $access_types = $post_obj->get_access_membership_types();
                $found = false;
                if (!empty($access_types)) {
                    foreach ($access_types as $type) {
                        if (in_array($type, $membership_type)) {
                            $membership = mgm_get_class('membership_types');
                            $obj->access_membership_type = $membership->get_type_name($type);
                            $found = true;
                            $total++;
                            break;
                        }
                    }
                    if ($found && (isset($_GET['show']) && $_GET['show'] == 'all' || $show_all || $total <= $per_page)) {
                        $posts[] = $obj;
                    }
                }
                // branch
            }
            return array('posts' => $posts, 'total' => $total);
        }
    }
    return array();
}
/**
 * get post data by post name
 * @since 1.8.34
 */
function mgm_get_post_data_by_name($post_name = false)
{
    global $wpdb;
    // types
    $post_types = mgm_get_post_types();
    // sql
    $sql = "SELECT * FROM `{$wpdb->posts}` WHERE `post_status` = 'publish' AND `post_type` IN ({$post_types}) AND `post_name`='{$post_name}'";
    // return
    return $wpdb->get_row($sql);
}