/**
  * Saves listing in the database using given information.
  *
  * @since 1.0.0
  * @package GeoDirectory
  * @global object $wpdb WordPress Database object.
  * @global object $post The current post object.
  * @global object $current_user Current user object.
  * @param array $request_info {
  *    Array of request info arguments.
  *
  *    @type string $action                                  Ajax action name.
  *    @type string $geodir_ajax                             Ajax type.
  *    @type string $ajax_action                             Ajax action.
  *    @type string $listing_type                            Listing type.
  *    @type string $pid                                     Default Post ID.
  *    @type string $preview                                 Todo Desc needed.
  *    @type string $add_listing_page_id                     Add listing page ID.
  *    @type string $post_title                              Listing title.
  *    @type string $post_desc                               Listing Description.
  *    @type string $post_tags                               Listing tags.
  *    @type array  $cat_limit                               Category limit.
  *    @type array  $post_category                           Category IDs.
  *    @type array  $post_category_str                       Category string.
  *    @type string $post_default_category                   Default category ID.
  *    @type string $post_address                            Listing address.
  *    @type string $geodir_location_add_listing_country_val Add listing country value.
  *    @type string $post_country                            Listing country.
  *    @type string $geodir_location_add_listing_region_val  Add listing region value.
  *    @type string $post_region                             Listing region.
  *    @type string $geodir_location_add_listing_city_val    Add listing city value.
  *    @type string $post_city                               Listing city.
  *    @type string $post_zip                                Listing zip.
  *    @type string $post_latitude                           Listing latitude.
  *    @type string $post_longitude                          Listing longitude.
  *    @type string $post_mapview                            Listing mapview. Default "ROADMAP".
  *    @type string $post_mapzoom                            Listing mapzoom Default "9".
  *    @type string $geodir_timing                           Business timing info.
  *    @type string $geodir_contact                          Contact number.
  *    @type string $geodir_email                            Business contact email.
  *    @type string $geodir_website                          Business website.
  *    @type string $geodir_twitter                          Twitter link.
  *    @type string $geodir_facebook                         Facebook link.
  *    @type string $geodir_video                            Video link.
  *    @type string $geodir_special_offers                   Speacial offers.
  *    @type string $post_images                             Post image urls.
  *    @type string $post_imagesimage_limit                  Post images limit.
  *    @type string $post_imagestotImg                       Todo Desc needed.
  *    @type string $geodir_accept_term_condition            Has accepted terms and conditions?.
  *    @type string $geodir_spamblocker                      Todo Desc needed.
  *    @type string $geodir_filled_by_spam_bot               Todo Desc needed.
  *
  * }
  * @param bool $dummy Optional. Is this a dummy listing? Default false.
  * @return int|string|WP_Error Created post id.
  */
 function geodir_save_listing($request_info = array(), $dummy = false)
 {
     global $wpdb, $current_user;
     $last_post_id = '';
     if (isset($_SESSION['listing']) && !$dummy) {
         $request_info = array();
         $request_session = unserialize($_SESSION['listing']);
         $request_info = array_merge($_REQUEST, $request_session);
     } else {
         if (!isset($_SESSION['listing']) && !$dummy) {
             global $post;
             $request_info['pid'] = $post->ID;
             $request_info['post_title'] = $request_info['post_title'];
             $request_info['listing_type'] = $post->post_type;
             $request_info['post_desc'] = $request_info['content'];
         } else {
             if (!$dummy) {
                 return false;
             }
         }
     }
     /**
      * Filter the request_info array.
      *
      * You can use this filter to modify request_info array.
      *
      * @since 1.0.0
      * @package GeoDirectory
      * @param array $request_info See {@see geodir_save_listing()} for accepted args.
      */
     $request_info = apply_filters('geodir_action_get_request_info', $request_info);
     // Check if we need to save post location as new location
     $location_result = geodir_get_default_location();
     if ($location_result->location_id > 0) {
         if (isset($request_info['post_city']) && isset($request_info['post_region'])) {
             $request_info['post_location'] = array('city' => $request_info['post_city'], 'region' => isset($request_info['post_region']) ? $request_info['post_region'] : '', 'country' => isset($request_info['post_country']) ? $request_info['post_country'] : '', 'geo_lat' => isset($request_info['post_latitude']) ? $request_info['post_latitude'] : '', 'geo_lng' => isset($request_info['post_longitude']) ? $request_info['post_longitude'] : '');
             $post_location_info = $request_info['post_location'];
             if ($location_id = geodir_add_new_location($post_location_info)) {
                 $post_location_id = $location_id;
             }
         } else {
             $post_location_id = $location_result->location_id;
         }
     } else {
         $post_location_id = $location_result->location_id;
     }
     if ($dummy) {
         $post_status = 'publish';
     } else {
         $post_status = geodir_new_post_default_status();
     }
     if (isset($request_info['pid']) && $request_info['pid'] != '') {
         $post_status = get_post_status($request_info['pid']);
     }
     /* fix change of slug on every title edit */
     if (!isset($request_info['post_name'])) {
         $request_info['post_name'] = $request_info['post_title'];
         if (!empty($request_info['pid'])) {
             $post_info = get_post($request_info['pid']);
             if (!empty($post_info) && isset($post_info->post_name)) {
                 $request_info['post_name'] = $post_info->post_name;
             }
         }
     }
     $post = array('post_content' => $request_info['post_desc'], 'post_status' => $post_status, 'post_title' => $request_info['post_title'], 'post_name' => $request_info['post_name'], 'post_type' => $request_info['listing_type']);
     /**
      * Called before a listing is saved to the database.
      *
      * @since 1.0.0
      * @param object $post The post object.
      */
     do_action_ref_array('geodir_before_save_listing', $post);
     $send_post_submit_mail = false;
     // unhook this function so it doesn't loop infinitely
     remove_action('save_post', 'geodir_post_information_save', 10, 2);
     if (isset($request_info['pid']) && $request_info['pid'] != '') {
         $post['ID'] = $request_info['pid'];
         $last_post_id = wp_update_post($post);
     } else {
         $last_post_id = wp_insert_post($post);
         if (!$dummy && $last_post_id) {
             $send_post_submit_mail = true;
             // we move post_submit email from here so the rest of the variables are added to the db first(was breaking permalink in email)
             //geodir_sendEmail('','',$current_user->user_email,$current_user->display_name,'','',$request_info,'post_submit',$last_post_id,$current_user->ID);
         }
     }
     // re-hook this function
     add_action('save_post', 'geodir_post_information_save', 10, 2);
     $post_tags = '';
     if (!isset($request_info['post_tags'])) {
         $post_type = $request_info['listing_type'];
         $post_tags = implode(",", wp_get_object_terms($last_post_id, $post_type . '_tags', array('fields' => 'names')));
     }
     $gd_post_info = array("post_title" => $request_info['post_title'], "post_tags" => isset($request_info['post_tags']) ? $request_info['post_tags'] : $post_tags, "post_status" => $post_status, "post_location_id" => $post_location_id, "claimed" => isset($request_info['claimed']) ? $request_info['claimed'] : '', "businesses" => isset($request_info['a_businesses']) ? $request_info['a_businesses'] : '', "submit_time" => time(), "submit_ip" => $_SERVER['REMOTE_ADDR']);
     $payment_info = array();
     $package_info = array();
     $package_info = (array) geodir_post_package_info($package_info, $post);
     $post_package_id = geodir_get_post_meta($last_post_id, 'package_id');
     if (!empty($package_info) && !$post_package_id) {
         if (isset($package_info['days']) && $package_info['days'] != 0) {
             $payment_info['expire_date'] = date('Y-m-d', strtotime("+" . $package_info['days'] . " days"));
         } else {
             $payment_info['expire_date'] = 'Never';
         }
         $payment_info['package_id'] = $package_info['pid'];
         $payment_info['alive_days'] = $package_info['days'];
         $payment_info['is_featured'] = $package_info['is_featured'];
         $gd_post_info = array_merge($gd_post_info, $payment_info);
     }
     $custom_metaboxes = geodir_post_custom_fields('', 'all', $request_info['listing_type']);
     foreach ($custom_metaboxes as $key => $val) {
         $name = $val['name'];
         $type = $val['type'];
         $extrafields = $val['extra_fields'];
         if (trim($type) == 'address') {
             $prefix = $name . '_';
             $address = $prefix . 'address';
             if (isset($request_info[$address]) && $request_info[$address] != '') {
                 $gd_post_info[$address] = $request_info[$address];
             }
             if ($extrafields != '') {
                 $extrafields = unserialize($extrafields);
                 if (!isset($request_info[$prefix . 'city']) || $request_info[$prefix . 'city'] == '') {
                     $location_result = geodir_get_default_location();
                     $gd_post_info[$prefix . 'city'] = $location_result->city;
                     $gd_post_info[$prefix . 'region'] = $location_result->region;
                     $gd_post_info[$prefix . 'country'] = $location_result->country;
                     $gd_post_info['post_locations'] = '[' . $location_result->city_slug . '],[' . $location_result->region_slug . '],[' . $location_result->country_slug . ']';
                     // set all overall post location
                 } else {
                     $gd_post_info[$prefix . 'city'] = $request_info[$prefix . 'city'];
                     $gd_post_info[$prefix . 'region'] = $request_info[$prefix . 'region'];
                     $gd_post_info[$prefix . 'country'] = $request_info[$prefix . 'country'];
                     //----------set post locations when import dummy data-------
                     $location_result = geodir_get_default_location();
                     $gd_post_info['post_locations'] = '[' . $location_result->city_slug . '],[' . $location_result->region_slug . '],[' . $location_result->country_slug . ']';
                     // set all overall post location
                     //-----------------------------------------------------------------
                 }
                 if (isset($extrafields['show_zip']) && $extrafields['show_zip'] && isset($request_info[$prefix . 'zip'])) {
                     $gd_post_info[$prefix . 'zip'] = $request_info[$prefix . 'zip'];
                 }
                 if (isset($extrafields['show_map']) && $extrafields['show_map']) {
                     if (isset($request_info[$prefix . 'latitude']) && $request_info[$prefix . 'latitude'] != '') {
                         $gd_post_info[$prefix . 'latitude'] = $request_info[$prefix . 'latitude'];
                     }
                     if (isset($request_info[$prefix . 'longitude']) && $request_info[$prefix . 'longitude'] != '') {
                         $gd_post_info[$prefix . 'longitude'] = $request_info[$prefix . 'longitude'];
                     }
                     if (isset($request_info[$prefix . 'mapview']) && $request_info[$prefix . 'mapview'] != '') {
                         $gd_post_info[$prefix . 'mapview'] = $request_info[$prefix . 'mapview'];
                     }
                     if (isset($request_info[$prefix . 'mapzoom']) && $request_info[$prefix . 'mapzoom'] != '') {
                         $gd_post_info[$prefix . 'mapzoom'] = $request_info[$prefix . 'mapzoom'];
                     }
                 }
                 // show lat lng
                 if (isset($extrafields['show_latlng']) && $extrafields['show_latlng'] && isset($request_info[$prefix . 'latlng'])) {
                     $gd_post_info[$prefix . 'latlng'] = $request_info[$prefix . 'latlng'];
                 }
             }
         } elseif (trim($type) == 'file') {
             if (isset($request_info[$name])) {
                 $request_files = array();
                 if ($request_info[$name] != '') {
                     $request_files = explode(",", $request_info[$name]);
                 }
                 $extrafields = $extrafields != '' ? maybe_unserialize($extrafields) : NULL;
                 geodir_save_post_file_fields($last_post_id, $name, $request_files, $extrafields);
             }
         } elseif (trim($type) == 'datepicker') {
             $datetime = '';
             if ($request_info[$name] != '') {
                 $date_format = geodir_default_date_format();
                 if (isset($val['extra_fields']) && $val['extra_fields'] != '') {
                     $extra_fields = unserialize($val['extra_fields']);
                     $date_format = isset($extra_fields['date_format']) && $extra_fields['date_format'] != '' ? $extra_fields['date_format'] : $date_format;
                 }
                 $search = array('dd', 'mm', 'yy');
                 $replace = array('d', 'm', 'Y');
                 $date_format = str_replace($search, $replace, $date_format);
                 $post_htmlvar_value = $date_format == 'd/m/Y' ? str_replace('/', '-', $request_info[$name]) : $request_info[$name];
                 // PHP doesn't work well with dd/mm/yyyy format
                 $datetime = date("Y-m-d", strtotime($post_htmlvar_value));
             }
             $gd_post_info[$name] = $datetime;
         } else {
             if ($type == 'multiselect') {
                 if (isset($request_info[$name])) {
                     $gd_post_info[$name] = $request_info[$name];
                 } else {
                     if (isset($request_info['gd_field_' . $name])) {
                         $gd_post_info[$name] = '';
                         /* fix de-select for multiselect */
                     }
                 }
             } else {
                 if (isset($request_info[$name])) {
                     $gd_post_info[$name] = $request_info[$name];
                 }
             }
         }
     }
     if (isset($request_info['post_dummy']) && $request_info['post_dummy'] != '') {
         $gd_post_info['post_dummy'] = $request_info['post_dummy'];
     }
     // Save post detail info in detail table
     if (!empty($gd_post_info)) {
         geodir_save_post_info($last_post_id, $gd_post_info);
     }
     // Set categories to the listing
     if (isset($request_info['post_category']) && !empty($request_info['post_category'])) {
         $post_category = array();
         foreach ($request_info['post_category'] as $taxonomy => $cat) {
             if ($dummy) {
                 $post_category = $cat;
             } else {
                 if (!is_array($cat) && strstr($cat, ',')) {
                     $cat = explode(',', $cat);
                 }
                 if (!empty($cat) && is_array($cat)) {
                     $post_category = array_map('intval', $cat);
                 }
             }
             wp_set_object_terms($last_post_id, $post_category, $taxonomy);
         }
         $post_default_category = isset($request_info['post_default_category']) ? $request_info['post_default_category'] : '';
         $post_category_str = isset($request_info['post_category_str']) ? $request_info['post_category_str'] : '';
         geodir_set_postcat_structure($last_post_id, $taxonomy, $post_default_category, $post_category_str);
     }
     $post_tags = '';
     // Set tags to the listing
     if (isset($request_info['post_tags']) && !is_array($request_info['post_tags']) && !empty($request_info['post_tags'])) {
         $post_tags = explode(",", $request_info['post_tags']);
     } elseif (isset($request_info['post_tags']) && is_array($request_info['post_tags'])) {
         if ($dummy) {
             $post_tags = $request_info['post_tags'];
         }
     } else {
         if ($dummy) {
             $post_tags = array($request_info['post_title']);
         }
     }
     if (is_array($post_tags)) {
         $taxonomy = $request_info['listing_type'] . '_tags';
         wp_set_object_terms($last_post_id, $post_tags, $taxonomy);
     }
     // Insert attechment
     if (isset($request_info['post_images']) && !is_wp_error($last_post_id)) {
         if (!$dummy) {
             $tmpimgArr = trim($request_info['post_images'], ",");
             $tmpimgArr = explode(",", $tmpimgArr);
             geodir_save_post_images($last_post_id, $tmpimgArr, $dummy);
         } else {
             geodir_save_post_images($last_post_id, $request_info['post_images'], $dummy);
         }
     } elseif (!isset($request_info['post_images']) || $request_info['post_images'] == '') {
         /* Delete Attachments
         			$postcurr_images = geodir_get_images($last_post_id);
         			
         			$wpdb->query(
         				$wpdb->prepare(
         					"DELETE FROM ".GEODIR_ATTACHMENT_TABLE." WHERE `post_id` = %d",
         					array($last_post_id)
         				)
         			);
         			geodir_remove_attachments($postcurr_images);
         			
         			$gd_post_featured_img = array();
         			$gd_post_featured_img['featured_image'] = '';
         			geodir_save_post_info($last_post_id, $gd_post_featured_img); 
         			*/
     }
     geodir_remove_temp_images();
     geodir_set_wp_featured_image($last_post_id);
     /**
      * Called after a listing is saved to the database and before any email have been sent.
      *
      * @since 1.0.0
      * @param int $last_post_id The saved post ID.
      * @param array $request_info The post details in an array.
      * @see 'geodir_after_save_listinginfo'
      */
     do_action('geodir_after_save_listing', $last_post_id, $request_info);
     //die;
     if ($send_post_submit_mail) {
         // if new post send out email
         $to_name = geodir_get_client_name($current_user->ID);
         geodir_sendEmail('', '', $current_user->user_email, $to_name, '', '', $request_info, 'post_submit', $last_post_id, $current_user->ID);
     }
     /*
      * Unset the session so we don't loop.
      */
     if (isset($_SESSION['listing'])) {
         unset($_SESSION['listing']);
     }
     return $last_post_id;
 }
function geodir_ipn_handler_2co()
{
    global $Cart, $General;
    $req = '';
    foreach ($_POST as $field => $value) {
        $ipnData["{$field}"] = $value;
        $req .= "&{$field}={$value}";
    }
    $postid = intval($ipnData['x_invoice_num']);
    $pnref = $ipnData['x_trans_id'];
    $amount = geodir_get_currency_sym() . doubleval($ipnData['x_amount']);
    $result = intval($ipnData['x_response_code']);
    $respmsg = $ipnData['x_response_reason_text'];
    $customer_email = $ipnData['x_email'];
    $customer_name = $ipnData['x_first_name'];
    $fromEmail = get_option('site_email');
    $fromEmailName = get_site_emailName();
    $subject = "Acknowledge for Place Listing ID #{$postid} payment";
    // get current post status
    $current_post_status = get_post_status($postid);
    if ($result == '1') {
        /* Valid IPN transaction.*/
        $post_default_status = geodir_new_post_default_status();
        if ($post_default_status == '') {
            $post_default_status = 'publish';
        }
        set_property_status($postid, $post_default_status);
        $productinfosql = $wpdb->prepare("select ID,post_title,guid,post_author from {$wpdb->posts} where ID = %d", array($postid));
        $productinfo = $wpdb->get_results($productinfosql);
        foreach ($productinfo as $productinfoObj) {
            $post_title = '<a href="' . $productinfoObj->guid . '">' . $productinfoObj->post_title . '</a>';
            $aid = $productinfoObj->post_author;
            $userInfo = get_author_info($aid);
            $to_name = $userInfo->user_nicename;
            $to_email = $userInfo->user_email;
        }
        $message = __('<p>payment for Place Listing ID #' . $postid . ' confirmation.<br></p><p><b>You may find the details below:</b></p><p>----</p><p>Place Listing Id : ' . $postid . '</p><p>Place Listing Title : ' . $post_title . '</p><p>User Name : ' . $to_name . '</p><p>User Email : ' . $to_email . '</p><p>Paid Amount :       ' . $amount . '</p><p>Transaction ID :       ' . $pnref . '</p><p>Result Code : ' . $result . '</p><p>Response Message : ' . $respmsg . '</p><p>----</p><br><br><p>Thank you.</p>', GEODIRPAYMENT_TEXTDOMAIN);
        $subject = get_option('post_payment_success_admin_email_subject');
        if (!$subject) {
            $subject = __("Place Listing Submitted and Payment Success Confirmation Email", GEODIRPAYMENT_TEXTDOMAIN);
        }
        $content = get_option('post_payment_success_admin_email_content');
        $store_name = get_option('blogname');
        $fromEmail = get_option('site_email');
        $search_array = array('[#to_name#]', '[#information_details#]', '[#site_name#]');
        $replace_array = array($fromEmail, $message, $store_name);
        /*$message = str_replace($search_array,$replace_array,$content);*/
        geodir_payment_adminEmail($postid, $aid, 'payment_success', $message);
        /* email to admin*/
        geodir_payment_clientEmail($postid, $aid, 'payment_success', $message);
        /* email to client*/
        /*@wp_mail($fromEmail,$subject,$message,$headerarr);*/
        /* email to admin*/
        // Extend expire date start
        $invoice_info = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . INVOICE_TABLE . " WHERE post_id = %d AND is_current=%s", array($postid, '1')));
        $invoice_id = $invoice_info->id;
        $invoice_package_id = '';
        if (!empty($invoice_info) && isset($invoice_info->package_id)) {
            $invoice_package_id = $invoice_info->package_id;
            $invoice_alive_days = $invoice_info->alive_days;
            $invoice_status = $invoice_info->status;
        }
        $geodir_post_info = geodir_get_post_info($postid);
        if (!empty($geodir_post_info)) {
            $post_package_id = $geodir_post_info->package_id;
            $post_expire_date = $geodir_post_info->expire_date;
            if (!empty($invoice_package_id) && $invoice_alive_days > 0 && $invoice_package_id == $post_package_id && strtolower($post_expire_date) != 'never' && strtotime($post_expire_date) >= strtotime(date('Y-m-d')) && $current_post_status == 'publish') {
                $alive_days = (int) ($geodir_post_info->alive_days + $invoice_alive_days);
                $expire_date = date('Y-m-d', strtotime($post_expire_date . "+" . $invoice_alive_days . " days"));
            } else {
                $alive_days = (int) $geodir_post_info->alive_days;
                if (strtolower($post_expire_date) != 'never' && strtotime($post_expire_date) < strtotime(date('Y-m-d'))) {
                    $alive_days = $invoice_alive_days;
                }
                $expire_date = $alive_days > 0 ? date('Y-m-d', strtotime(date('Y-m-d') . "+" . $alive_days . " days")) : 'Never';
            }
            geodir_save_post_meta($postid, 'alive_days', $alive_days);
            geodir_save_post_meta($postid, 'expire_date', $expire_date);
        }
        // Extend expire date start	end
        /*############ SET THE INVOICE STATUS START ############*/
        // update invoice statuse and transactio details
        $transaction_details = $message;
        geodir_update_invoice_status($invoice_id, 'Paid');
        geodir_update_invoice_transaction_details($invoice_id, $transaction_details);
        /*############ SET THE INVOICE STATUS END ############*/
        if ($ct_on && file_exists($child_dir . '/library/includes/success.php')) {
            include_once $child_dir . '/library/includes/success.php';
        } else {
            include_once TEMPLATEPATH . '/library/includes/success.php';
        }
        exit;
        return true;
    } else {
        if ($result != '1') {
            $message = __('<p>payment for Place Listing ID #' . $postid . ' incompleted.<br>because of ' . $respmsg . '</p><p><b>You may find the details below:</b></p><p>----</p><p>Place Listing Id : ' . $postid . '</p><p>Place Listing Title : ' . $post_title . '</p><p>User Name : ' . $to_name . '</p><p>User Email : ' . $to_email . '</p><p>Paid Amount :       ' . $amount . '</p><p>Transaction ID :       ' . $pnref . '</p><p>Result Code : ' . $result . '</p><p>Response Message : ' . $respmsg . '</p><p>----</p><br><br><p>Thank you.</p>', GEODIRPAYMENT_TEXTDOMAIN);
            $subject = get_option('post_payment_success_client_email_subject');
            if (!$subject) {
                $subject = __("Place Listing Submitted and Payment Success Confirmation Email", GEODIRPAYMENT_TEXTDOMAIN);
            }
            $content = get_option('post_payment_success_client_email_content');
            $store_name = get_option('blogname');
            $search_array = array('[#to_name#]', '[#information_details#]', '[#site_name#]');
            $replace_array = array($to_name, $message, $store_name);
            /*$message = str_replace($search_array,$replace_array,$content);*/
            geodir_payment_adminEmail($postid, $aid, 'payment_success', $message);
            /* email to admin*/
            geodir_payment_clientEmail($postid, $aid, 'payment_success', $message);
            /* email to client*/
            /*@wp_mail($to_email,$subject,$message,$headerarr);*/
            /* email to client*/
            /*############ SET THE INVOICE STATUS START ############*/
            global $wpdb;
            $invoice_info = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . INVOICE_TABLE . " WHERE post_id = %d AND is_current=%s", array($postid, '1')));
            $invoice_id = $invoice_info->id;
            // update invoice statuse and transactio details
            $transaction_details = $message;
            geodir_update_invoice_status($invoice_id, 'Unpaid');
            geodir_update_invoice_transaction_details($invoice_id, $transaction_details);
            /*############ SET THE INVOICE STATUS END ############*/
            if ($ct_on && file_exists($child_dir . '/library/includes/success.php')) {
                include_once $child_dir . '/library/includes/success.php';
            } else {
                include_once TEMPLATEPATH . '/library/includes/success.php';
            }
            exit;
            return false;
        }
    }
}