/**
  * 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;
 }
/**
 * Processes GeoDirectory ajax url calls.
 *
 * @see geodir_get_ajax_url()
 * @since 1.0.0
 * @package GeoDirectory
 * @global object $wpdb WordPress Database object.
 * @global object $current_user Current user object.
 * @todo check if nonce is required here and if so add one.
 */
function geodir_ajax_handler()
{
    global $wpdb;
    if (isset($_REQUEST['gd_listing_view']) && $_REQUEST['gd_listing_view'] != '') {
        $_SESSION['gd_listing_view'] = $_REQUEST['gd_listing_view'];
        echo '1';
    }
    if (isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'category_ajax') {
        if (isset($_REQUEST['main_catid']) && isset($_REQUEST['cat_tax']) && isset($_REQUEST['exclude'])) {
            geodir_addpost_categories_html($_REQUEST['cat_tax'], $_REQUEST['main_catid'], '', '', '', $_REQUEST['exclude']);
        } elseif (isset($_REQUEST['catpid']) && isset($_REQUEST['cat_tax'])) {
            geodir_editpost_categories_html($_REQUEST['cat_tax'], $_REQUEST['catpid']);
        }
    }
    if (isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'admin_ajax' || isset($_REQUEST['create_field']) || isset($_REQUEST['sort_create_field'])) {
        if (current_user_can('manage_options')) {
            /**
             * Contains admin ajax handling functions.
             *
             * @since 1.0.0
             * @package GeoDirectory
             */
            include_once geodir_plugin_path() . '/geodirectory-admin/geodir_admin_ajax.php';
        } else {
            wp_redirect(home_url() . '/?geodir_signup=true');
            exit;
        }
    }
    if (isset($_REQUEST['geodir_autofill']) && $_REQUEST['geodir_autofill'] != '' && isset($_REQUEST['_wpnonce'])) {
        if (current_user_can('manage_options')) {
            switch ($_REQUEST['geodir_autofill']) {
                case "geodir_dummy_delete":
                    if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'geodir_dummy_posts_delete_noncename')) {
                        return;
                    }
                    if (isset($_REQUEST['posttype'])) {
                        /**
                         * Used to delete the dummy post data per post type.
                         *
                         * Uses dynamic hook, geodir_delete_dummy_posts_$_REQUEST['posttype'].
                         *
                         * @since 1.0.0
                         */
                        do_action('geodir_delete_dummy_posts_' . $_REQUEST['posttype']);
                    }
                    break;
                case "geodir_dummy_insert":
                    if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'geodir_dummy_posts_insert_noncename')) {
                        return;
                    }
                    global $dummy_post_index, $city_bound_lat1, $city_bound_lng1, $city_bound_lat2, $city_bound_lng2;
                    $dummy_post_index = $_REQUEST['insert_dummy_post_index'];
                    $city_bound_lat1 = $_REQUEST['city_bound_lat1'];
                    $city_bound_lng1 = $_REQUEST['city_bound_lng1'];
                    $city_bound_lat2 = $_REQUEST['city_bound_lat2'];
                    $city_bound_lng2 = $_REQUEST['city_bound_lng2'];
                    if (isset($_REQUEST['posttype'])) {
                        /**
                         * Used to insert the dummy post data per post type.
                         *
                         * Uses dynamic hook, geodir_insert_dummy_posts_$_REQUEST['posttype'].
                         *
                         * @since 1.0.0
                         */
                        do_action('geodir_insert_dummy_posts_' . $_REQUEST['posttype']);
                    }
                    break;
            }
        } else {
            wp_redirect(home_url() . '/?geodir_signup=true');
            exit;
        }
    }
    if (isset($_REQUEST['geodir_import_data']) && $_REQUEST['geodir_import_data'] != '') {
        if (current_user_can('manage_options')) {
            geodir_import_data();
        } else {
            wp_redirect(home_url() . '/?geodir_signup=true');
            exit;
        }
    }
    if (isset($_REQUEST['popuptype']) && $_REQUEST['popuptype'] != '' && isset($_REQUEST['post_id']) && $_REQUEST['post_id'] != '') {
        if ($_REQUEST['popuptype'] == 'b_send_inquiry' || $_REQUEST['popuptype'] == 'b_sendtofriend') {
            require_once geodir_plugin_path() . '/geodirectory-templates/popup-forms.php';
        }
        exit;
    }
    /*if(isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'filter_ajax'){
          include_once ( geodir_plugin_path() . '/geodirectory-templates/advance-search-form.php');
      }*/
    if (isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'map_ajax') {
        /**
         * Contains map marker functions.
         *
         * @since 1.0.0
         * @package GeoDirectory
         */
        include_once geodir_plugin_path() . '/geodirectory-functions/map-functions/get_markers.php';
    }
    if (isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'favorite') {
        if (is_user_logged_in()) {
            switch ($_REQUEST['ajax_action']) {
                case "add":
                    geodir_add_to_favorite($_REQUEST['pid']);
                    break;
                case "remove":
                    geodir_remove_from_favorite($_REQUEST['pid']);
                    break;
            }
        } else {
            wp_redirect(home_url() . '/?geodir_signup=true');
            exit;
        }
    }
    if (isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'add_listing') {
        $is_current_user_owner = true;
        if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
            $is_current_user_owner = geodir_listing_belong_to_current_user($_REQUEST['pid']);
        }
        $request = isset($_SESSION['listing']) ? unserialize($_SESSION['listing']) : '';
        if (is_user_logged_in() && $is_current_user_owner) {
            switch ($_REQUEST['ajax_action']) {
                case "add":
                case "update":
                    if (isset($request['geodir_spamblocker']) && $request['geodir_spamblocker'] == '64' && isset($request['geodir_filled_by_spam_bot']) && $request['geodir_filled_by_spam_bot'] == '') {
                        $last_id = geodir_save_listing();
                        if ($last_id) {
                            //$redirect_to = get_permalink( $last_id );
                            $redirect_to = geodir_getlink(get_permalink(geodir_success_page_id()), array('pid' => $last_id));
                        } elseif (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
                            $redirect_to = get_permalink(geodir_add_listing_page_id());
                            $redirect_to = geodir_getlink($redirect_to, array('pid' => $post->pid), false);
                        } else {
                            $redirect_to = get_permalink(geodir_add_listing_page_id());
                        }
                        wp_redirect($redirect_to);
                    } else {
                        if (isset($_SESSION['listing'])) {
                            unset($_SESSION['listing']);
                        }
                        wp_redirect(home_url());
                    }
                    break;
                case "cancel":
                    unset($_SESSION['listing']);
                    if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '' && get_permalink($_REQUEST['pid'])) {
                        wp_redirect(get_permalink($_REQUEST['pid']));
                    } else {
                        geodir_remove_temp_images();
                        wp_redirect(geodir_getlink(get_permalink(geodir_add_listing_page_id()), array('listing_type' => $_REQUEST['listing_type'])));
                    }
                    break;
                case "publish":
                    if (isset($request['geodir_spamblocker']) && $request['geodir_spamblocker'] == '64' && isset($request['geodir_filled_by_spam_bot']) && $request['geodir_filled_by_spam_bot'] == '') {
                        if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
                            $new_post = array();
                            $new_post['ID'] = $_REQUEST['pid'];
                            //$new_post['post_status'] = 'publish';
                            $lastid = wp_update_post($new_post);
                            if (isset($_SESSION['listing'])) {
                                unset($_SESSION['listing']);
                            }
                            wp_redirect(get_permalink($lastid));
                        } else {
                            $last_id = geodir_save_listing();
                            if ($last_id) {
                                //$redirect_to = get_permalink( $last_id );
                                $redirect_to = geodir_getlink(get_permalink(geodir_success_page_id()), array('pid' => $last_id));
                            } elseif (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
                                $redirect_to = get_permalink(geodir_add_listing_page_id());
                                $redirect_to = geodir_getlink($redirect_to, array('pid' => $post->pid), false);
                            } else {
                                $redirect_to = get_permalink(geodir_add_listing_page_id());
                            }
                            if (isset($_SESSION['listing'])) {
                                unset($_SESSION['listing']);
                            }
                            wp_redirect($redirect_to);
                        }
                    } else {
                        if (isset($_SESSION['listing'])) {
                            unset($_SESSION['listing']);
                        }
                        wp_redirect(home_url());
                    }
                    break;
                case "delete":
                    if (isset($_REQUEST['pid']) && $_REQUEST['pid'] != '') {
                        global $current_user;
                        get_currentuserinfo();
                        $post_type = get_post_type($_REQUEST['pid']);
                        $lastid = wp_delete_post($_REQUEST['pid']);
                        if ($lastid && !is_wp_error($lastid)) {
                            wp_redirect($_SERVER['HTTP_REFERER']);
                        }
                        //wp_redirect( geodir_getlink(get_author_posts_url($current_user->ID),array('geodir_dashbord'=>'true','stype'=>$post_type ),false) );
                    }
                    break;
            }
            if (isset($_SESSION['listing'])) {
                unset($_SESSION['listing']);
            }
        } else {
            if (isset($_SESSION['listing'])) {
                unset($_SESSION['listing']);
            }
            wp_redirect(home_url() . '/?geodir_signup=true');
            exit;
        }
    }
    if (isset($_REQUEST['geodir_ajax']) && $_REQUEST['geodir_ajax'] == 'user_login') {
        /**
         * Contains registration and login functions.
         * @todo Fix the file path.
         *
         * @since 1.0.0
         * @package GeoDirectory
         */
        include_once geodir_plugin_path() . '/geodirectory-functions/geodirectory_reg.php';
    }
    if (isset($_REQUEST['ajax_action']) && $_REQUEST['ajax_action'] == 'geodir_get_term_list') {
        $terms_o = get_terms(sanitize_text_field($_REQUEST['term']));
        // Skip terms which has no listing
        if (!empty($terms_o)) {
            $filter_terms = array();
            foreach ($terms_o as $term) {
                if ($term->count > 0) {
                    $filter_terms[] = $term;
                }
            }
            $terms_o = $filter_terms;
        }
        $terms = geodir_sort_terms($terms_o, 'count');
        geodir_helper_cat_list_output($terms, intval($_REQUEST['limit']));
        exit;
    }
    die;
}
 /**
  * Imports data from csv file.
  *
  * @since 1.0.0
  * @package GeoDirectory
  * @global object $wpdb WordPress Database object.
  * @global string $plugin_prefix Geodirectory plugin table prefix.
  * @global object $current_user Current user object.
  */
 function geodir_import_data()
 {
     global $wpdb, $plugin_prefix, $current_user;
     if (isset($_REQUEST['geodir_import_data']) && !empty($_REQUEST['geodir_import_data'])) {
         $uploads = wp_upload_dir();
         $uploads_dir = $uploads['path'];
         $curr_img_url = $_REQUEST['filename'];
         $image_name_arr = explode('/', $curr_img_url);
         $filename = end($image_name_arr);
         $target_path = $uploads_dir . '/temp_' . $current_user->data->ID . '/' . $filename;
         $destination_path = $uploads_dir . '/temp_' . $current_user->data->ID;
         $csv_target_path = $target_path;
         ini_set('auto_detect_line_endings', true);
         $fd = fopen($target_path, "rt");
         $total_records = 0;
         $rowcount = 0;
         $address_invalid = 0;
         $blank_address = 0;
         $upload_files = 0;
         $invalid_post_type = 0;
         $invalid_title = 0;
         $customKeyarray = array();
         $gd_post_info = array();
         $post_location = array();
         $countpost = 0;
         $uploaded_file_type = pathinfo($filename, PATHINFO_EXTENSION);
         $extensionarr = array('csv', 'CSV');
         if (in_array($uploaded_file_type, $extensionarr)) {
             while (!feof($fd)) {
                 $buffer = fgetcsv($fd, 40960);
                 if ($rowcount == 0) {
                     for ($k = 0; $k < count($buffer); $k++) {
                         $customKeyarray[$k] = $buffer[$k];
                     }
                     if ($customKeyarray[0] == '') {
                         echo $geodir_url = admin_url() . 'admin.php?page=geodirectory&tab=general_settings&active_tab=csv_upload_settings&emsg=wrong';
                         exit;
                     }
                 } elseif (!empty($buffer)) {
                     $total_records++;
                     $post_title = addslashes($buffer[0]);
                     $current_post_author = $buffer[1];
                     $post_desc = addslashes($buffer[2]);
                     $post_cat = array();
                     $catids_arr = array();
                     $post_cat = trim($buffer[3]);
                     // comma seperated category name
                     if ($post_cat) {
                         $post_cat_arr = explode(',', $post_cat);
                         for ($c = 0; $c < count($post_cat_arr); $c++) {
                             $catid = wp_kses_normalize_entities(trim($post_cat_arr[$c]));
                             if (!empty($buffer[5])) {
                                 if (in_array($buffer[5], geodir_get_posttypes())) {
                                     $p_taxonomy = geodir_get_taxonomies(addslashes($buffer[5]));
                                     if (get_term_by('name', $catid, $p_taxonomy[0])) {
                                         $cat = get_term_by('name', $catid, $p_taxonomy[0]);
                                         $catids_arr[] = $cat->slug;
                                     } elseif (get_term_by('slug', $catid, $p_taxonomy[0])) {
                                         $cat = get_term_by('slug', $catid, $p_taxonomy[0]);
                                         $catids_arr[] = $cat->slug;
                                     }
                                 }
                             }
                         }
                     }
                     if (!$catids_arr) {
                         $catids_arr[] = 1;
                     }
                     $post_tags = trim($buffer[4]);
                     // comma seperated tags
                     $tag_arr = '';
                     if ($post_tags) {
                         $tag_arr = explode(',', $post_tags);
                     }
                     $table = $plugin_prefix . $buffer[5] . '_detail';
                     // check table in database
                     $error = '';
                     if ($wpdb->get_var("SHOW TABLES LIKE '" . $table . "'") != $table) {
                         $invalid_post_type++;
                         continue;
                     }
                     if ($post_title != '') {
                         $menu_order = 0;
                         $image_folder_name = 'uplaod/';
                         $image_names = array();
                         for ($c = 5; $c < count($customKeyarray); $c++) {
                             $gd_post_info[$customKeyarray[$c]] = addslashes($buffer[$c]);
                             if ($customKeyarray[$c] == 'IMAGE') {
                                 $buffer[$c] = trim($buffer[$c]);
                                 if (!empty($buffer[$c])) {
                                     $image_names[] = $buffer[$c];
                                 }
                             }
                             if ($customKeyarray[$c] == 'alive_days') {
                                 if ($buffer[$c] != '0' && $buffer[$c] != '') {
                                     $submitdata = date('Y-m-d');
                                     $gd_post_info['expire_date'] = date('Y-m-d', strtotime($submitdata . "+" . addslashes($buffer[$c]) . " days"));
                                 } else {
                                     $gd_post_info['expire_date'] = 'Never';
                                 }
                             }
                             if ($customKeyarray[$c] == 'post_city') {
                                 $post_city = addslashes($buffer[$c]);
                             }
                             if ($customKeyarray[$c] == 'post_region') {
                                 $post_region = addslashes($buffer[$c]);
                             }
                             if ($customKeyarray[$c] == 'post_country') {
                                 $post_country = addslashes($buffer[$c]);
                             }
                             if ($customKeyarray[$c] == 'post_latitude') {
                                 $post_latitude = addslashes($buffer[$c]);
                             }
                             if ($customKeyarray[$c] == 'post_longitude') {
                                 $post_longitude = addslashes($buffer[$c]);
                             }
                         }
                         /* ================ before array create ============== */
                         $location_result = geodir_get_default_location();
                         if (!isset($gd_post_info['post_city']) || $gd_post_info['post_city'] == '' || (!isset($gd_post_info['post_region']) || $gd_post_info['post_region'] == '') || (!isset($gd_post_info['post_country']) || $gd_post_info['post_country'] == '') || (!isset($gd_post_info['post_address']) || $gd_post_info['post_address'] == '') || (!isset($gd_post_info['post_latitude']) || $gd_post_info['post_latitude'] == '') || (!isset($gd_post_info['post_longitude']) || $gd_post_info['post_longitude'] == '')) {
                             $blank_address++;
                             continue;
                         } elseif ($location_result->location_id == 0) {
                             if (strtolower($gd_post_info['post_city']) != strtolower($location_result->city) || strtolower($gd_post_info['post_region']) != strtolower($location_result->region) || strtolower($gd_post_info['post_country']) != strtolower($location_result->country)) {
                                 $address_invalid++;
                                 continue;
                             }
                         }
                         $my_post['post_title'] = $post_title;
                         $my_post['post_content'] = $post_desc;
                         $my_post['post_type'] = addslashes($buffer[5]);
                         $my_post['post_author'] = $current_post_author;
                         $my_post['post_status'] = 'publish';
                         $my_post['post_category'] = $catids_arr;
                         $my_post['post_tags'] = $tag_arr;
                         $gd_post_info['post_tags'] = $tag_arr;
                         $gd_post_info['post_title'] = $post_title;
                         $gd_post_info['post_status'] = 'publish';
                         $gd_post_info['submit_time'] = time();
                         $gd_post_info['submit_ip'] = $_SERVER['REMOTE_ADDR'];
                         $last_postid = wp_insert_post($my_post);
                         $countpost++;
                         // Check if we need to save post location as new location
                         if ($location_result->location_id > 0) {
                             if (isset($post_city) && isset($post_region)) {
                                 $request_info['post_location'] = array('city' => $post_city, 'region' => $post_region, 'country' => $post_country, 'geo_lat' => $post_latitude, 'geo_lng' => $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 = 0;
                             }
                         } else {
                             $post_location_id = 0;
                         }
                         /* ------- get default package info ----- */
                         $payment_info = array();
                         $package_info = array();
                         $package_info = (array) geodir_post_package_info($package_info, '', $buffer[5]);
                         $package_id = '';
                         if (isset($gd_post_info['package_id']) && $gd_post_info['package_id'] != '') {
                             $package_id = $gd_post_info['package_id'];
                         }
                         if (!empty($package_info)) {
                             $payment_info['package_id'] = $package_info['pid'];
                             if (isset($package_info['alive_days']) && $package_info['alive_days'] != 0) {
                                 $payment_info['expire_date'] = date('Y-m-d', strtotime("+" . $package_info['alive_days'] . " days"));
                             } else {
                                 $payment_info['expire_date'] = 'Never';
                             }
                             $gd_post_info = array_merge($gd_post_info, $payment_info);
                         }
                         $gd_post_info['post_location_id'] = $post_location_id;
                         $post_type = get_post_type($last_postid);
                         $table = $plugin_prefix . $post_type . '_detail';
                         geodir_save_post_info($last_postid, $gd_post_info);
                         if (!empty($image_names)) {
                             $upload_files++;
                             $menu_order = 1;
                             foreach ($image_names as $image_name) {
                                 $img_name_arr = explode('.', $image_name);
                                 $uploads = wp_upload_dir();
                                 $sub_dir = $uploads['subdir'];
                                 $arr_file_type = wp_check_filetype($image_name);
                                 $uploaded_file_type = $arr_file_type['type'];
                                 $attachment = array();
                                 $attachment['post_id'] = $last_postid;
                                 $attachment['title'] = $img_name_arr[0];
                                 $attachment['content'] = '';
                                 $attachment['file'] = $sub_dir . '/' . $image_name;
                                 $attachment['mime_type'] = $uploaded_file_type;
                                 $attachment['menu_order'] = $menu_order;
                                 $attachment['is_featured'] = 0;
                                 $attachment_set = '';
                                 foreach ($attachment as $key => $val) {
                                     if ($val != '') {
                                         $attachment_set .= $key . " = '" . $val . "', ";
                                     }
                                 }
                                 $attachment_set = trim($attachment_set, ", ");
                                 $wpdb->query("INSERT INTO " . GEODIR_ATTACHMENT_TABLE . " SET " . $attachment_set);
                                 if ($menu_order == 1) {
                                     $post_type = get_post_type($last_postid);
                                     $wpdb->query($wpdb->prepare("UPDATE " . $table . " SET featured_image = %s where post_id =%d", array($sub_dir . '/' . $image_name, $last_postid)));
                                 }
                                 $menu_order++;
                             }
                         }
                         $gd_post_info['package_id'] = $package_id;
                         /** This action is documented in geodirectory-functions/post-functions.php */
                         do_action('geodir_after_save_listing', $last_postid, $gd_post_info);
                         if (!empty($buffer[5])) {
                             if (in_array($buffer[5], geodir_get_posttypes())) {
                                 $taxonomies = geodir_get_posttype_info(addslashes($buffer[5]));
                                 wp_set_object_terms($last_postid, $my_post['post_tags'], $taxonomy = $taxonomies['taxonomies'][1]);
                                 wp_set_object_terms($last_postid, $my_post['post_category'], $taxonomy = $taxonomies['taxonomies'][0]);
                                 $post_default_category = isset($my_post['post_default_category']) ? $my_post['post_default_category'] : '';
                                 $post_category_str = isset($my_post['post_category_str']) ? $my_post['post_category_str'] : '';
                                 geodir_set_postcat_structure($last_postid, $taxonomy, $post_default_category, $post_category_str);
                             }
                         }
                     } else {
                         $invalid_title++;
                     }
                 }
                 $rowcount++;
             }
             fclose($fd);
             //unlink($csv_target_path);
             //rmdir($destination_path);
             if (!empty($filename)) {
                 geodir_remove_temp_images();
             }
             echo $geodir_url = admin_url() . 'admin.php?page=geodirectory&tab=general_settings&active_tab=csv_upload_settings&msg=success&rowcount=' . $countpost . '&invalidcount=' . $address_invalid . '&blank_address=' . $blank_address . '&upload_files=' . $upload_files . '&invalid_post_type=' . $invalid_post_type . '&invalid_title=' . $invalid_title . '&total_records=' . $total_records;
             exit;
         } else {
             echo $geodir_url = admin_url() . 'admin.php?page=geodirectory&tab=general_settings&active_tab=csv_upload_settings&emsg=csvonly';
             exit;
         }
     }
 }