/**
	* import_views
	*
	* Main import method for Views - import Views and WordPress Archives
	*
	* @param $import_data (array) Array of items to import
	* @param $args (array) Import modifiers
	*	'views-overwrite' 			will force overwriting existing Views and WPA
	* 	'views-delete' 				will delete any existing Views and WPA that are not on the import file
	*	'force_import_id,			will only import items with those XML IDs
	*	'force_import_post_name',	will only import items with those XML post_name
	*	'force_skip_id',			will not import items with those XML IDs
	*	'force_skip_post_name',		will not import items with those XML post_name
	*	'force_duplicate_id',		will duplicate, if they already exist, items with those XML IDs
	*	'force_duplicate_post_name'	will duplicate, if they already exist, items with those XML post_name
	* 	'return_to'					will handle the special case of Module Manager imports
	*
	* @return (mixed) true on success, WP_Error otherwise | array with result data for Module Manager import
	*
	* @since 1.8.0
	*/
	
	function import_views( $import_data, $args = array() ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error( 'wrong_capability', __( 'Your user can not perform that action.', 'wpv-views' ) );
		}
		global $wpdb, $WP_Views, $_wp_additional_image_sizes;
		$return_to = 'views';
		$force_overwrite = false;
		$force_delete = false;
		$force_import_id = array();
		$force_import_post_name = array();
		$force_skip_id = array();
		$force_skip_post_name = array();
		$force_duplicate_id = array();
		$force_duplicate_post_name = array();
		if ( isset( $args['return_to'] ) ) {
			$return_to = $args['return_to'] ;
		}
		if ( isset( $args['views-overwrite'] ) ) {
			$force_overwrite = true;
		}
		if ( isset( $args['views-delete'] ) ) {
			$force_delete = true;
		}
		if ( 
			isset( $args['force_import_id'] ) 
			&& is_array( $args['force_import_id'] )
		) {
			$force_import_id = $args['force_import_id'];
		}
		if ( 
			isset( $args['force_import_post_name'] ) 
			&& is_array( $args['force_import_post_name'] )
		) {
			$force_import_post_name = $args['force_import_post_name'];
		}
		if ( 
			isset( $args['force_skip_id'] ) 
			&& is_array( $args['force_skip_id'] )
		) {
			$force_skip_id = $args['force_skip_id'];
		}
		if ( 
			isset( $args['force_skip_post_name'] ) 
			&& is_array( $args['force_skip_post_name'] )
		) {
			$force_skip_post_name = $args['force_skip_post_name'];
		}
		if ( 
			isset( $args['force_duplicate_id'] ) 
			&& is_array( $args['force_duplicate_id'] )
		) {
			$force_duplicate_id = $args['force_duplicate_id'];
		}
		if ( 
			isset( $args['force_duplicate_post_name'] ) 
			&& is_array( $args['force_duplicate_post_name'] )
		) {
			$force_duplicate_post_name = $args['force_duplicate_post_name'];
		}

		$imported_views = array();
		$overwrite_count = 0;
		$new_count = 0;
		$results = array(
			'updated' => 0,
			'new' => 0,
			'failed' => 0,
			'errors' => array()
		);
		$newitems = array();

		if ( 
			! isset( $_wp_additional_image_sizes ) 
			|| !is_array( $_wp_additional_image_sizes ) 
		) {
			$_wp_additional_image_sizes = array();
		}
		$attached_images_sizes = array_merge(
			// additional thumbnail sizes
			array_keys( $_wp_additional_image_sizes ),
			// wp default thumbnail sizes
			array( 'thumbnail', 'medium', 'large' )
		);
		
		/**
		* wpv_filter_view_extra_fields_for_import_export
		*
		* Extra postdata from the View that needs to be imported, beyond the settings, layout settings and description
		*
		* @param (array) 
		*
		* @since 1.7
		*/
		
		$extra_metas = apply_filters( 'wpv_filter_view_extra_fields_for_import_export', array() );
	
		$this_settings_metaboxes = array(
			'filter_meta_html',
			'filter_meta_html_css',
			'filter_meta_html_js',
			'layout_meta_html_css',
			'layout_meta_html_js'
		);
		$this_layout_settings_metaboxes = array(
			'layout_meta_html'
		);

		if ( isset( $import_data['views']['view'] ) ) {
			$views = $import_data['views']['view'];
			// check for a single view
			if ( ! isset( $views[0] ) ) {
				$views = array( $views );
			}
			foreach ( $views as $view ) {
				
				if (
					in_array( $view['ID'], $force_skip_id )
					|| in_array( $view['post_name'], $force_skip_post_name )
				) {
					continue;
				}
				
				$meta = $view['meta'];
				unset( $view['meta'] );
				$view_images = array();
				if ( isset( $view['attachments'] ) ) {
					$view_images = array( $view['attachments'] );
					unset( $view['attachments'] );
				}
				// SRDJAN - https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/142389966/comments
				// Fix URLs
				if (
					! empty( $import_data['site_url'] ) 
					&& ! empty( $import_data['fileupload_url'] ) 
				) {
					if ( 
						isset( $meta['_wpv_settings']['pagination']['spinner_image'] ) 
						&& ! empty( $meta['_wpv_settings']['pagination']['spinner_image'] ) 
					) {
						$meta['_wpv_settings']['pagination']['spinner_image'] = WPV_URL_EMBEDDED . '/res/img/' . basename($meta['_wpv_settings']['pagination']['spinner_image']);
					}
					if (
						isset( $meta['_wpv_settings']['dps']['spinner_image'] ) 
						&& ! empty( $meta['_wpv_settings']['dps']['spinner_image'] ) 
					) {
						$meta['_wpv_settings']['dps']['spinner_image'] = WPV_URL_EMBEDDED . '/res/img/' . basename($meta['_wpv_settings']['dps']['spinner_image']);
					}
					if ( 
						isset( $meta['_wpv_settings']['pagination']['spinner_image_uploaded'] ) 
						&& ! empty( $meta['_wpv_settings']['pagination']['spinner_image_uploaded'] ) 
					) {
						$old_custom_spinner = $meta['_wpv_settings']['pagination']['spinner_image_uploaded']; // keep it for comparing in the new images importing flow
						$meta['_wpv_settings']['pagination']['spinner_image_uploaded'] = wpv_convert_url(
							$meta['_wpv_settings']['pagination']['spinner_image_uploaded'],
							$import_data['site_url'],
							$import_data['fileupload_url']
						);
					}
					if ( 
						isset( $meta['_wpv_settings']['dps']['spinner_image_uploaded'] ) 
						&& ! empty( $meta['_wpv_settings']['dps']['spinner_image_uploaded'] ) 
					) {
						$old_dps_custom_spinner = $meta['_wpv_settings']['dps']['spinner_image_uploaded']; // keep it for comparing in the new images importing flow
						$meta['_wpv_settings']['dps']['spinner_image_uploaded'] = wpv_convert_url(
							$meta['_wpv_settings']['dps']['spinner_image_uploaded'],
							$import_data['site_url'],
							$import_data['fileupload_url']
						);
					}
				}
				// TODO Move all of this to a proper adjustment method
				// SRDJAN - fix term_ids
				// https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/142382866/comments
				if ( 
					! empty( $meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'] ) 
					&& is_array( $meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'] ) 
				) {
					foreach ( $meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'] as $term_key => $old_term_id ) {
						if ( isset( $import_data['terms_map']['term_' . $old_term_id] ) ) {
							$new_term = get_term_by( 'slug', $import_data['terms_map']['term_' . $old_term_id]['slug'], $import_data['terms_map']['term_' . $old_term_id]['taxonomy'] );
							if ( !empty( $new_term ) ) {
								$meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'][$term_key] = $new_term->term_id;
							}
						}
					}
				}
				
				$post_to_update = $wpdb->get_var( 
					$wpdb->prepare( 
						"SELECT ID FROM {$wpdb->posts} 
						WHERE post_name = %s 
						AND post_type = %s 
						LIMIT 1", 
						$view['post_name'], 
						'view' 
					) 
				);

				$idflag = 0;
				$id_to_import = $view['ID'];
				
				if ( $post_to_update ) {
					$imported_views[] = $post_to_update;
					if (
						in_array( $view['ID'], $force_duplicate_id )
						|| in_array( $view['post_name'], $force_duplicate_post_name )
					) {
						$duplicated_view = $view;
						unset( $duplicated_view['ID'] );
						unset( $duplicated_view['post_name'] );
						$counter = 0;
						$real_suffix = current_time( 'timestamp' );
						while ( $counter < 20 ) {
							$add = ' ' . $counter;
							if ( $counter == 0 ) {
								$add = '';
							}
							$view_title = $duplicated_view['post_title'] . $real_suffix . $add;
							$existing = $wpdb->get_var(
								$wpdb->prepare(
									"SELECT count(ID) FROM {$wpdb->posts} 
									WHERE ( post_title = %s OR post_name = %s ) 
									AND post_type = 'view' 
									LIMIT 1",
									$view_title,
									$view_title
								)
							);
							if ( $existing <= 0 ) {
								break;
							} else {
								$counter++;
							}
						}
						$duplicated_view['post_title'] = $view_title;
						$id = wp_insert_post( $duplicated_view, true );
						if ( is_object( $id ) ) {
							// it's an WP_Error object.
							if ( $return_to == 'module_manager' ) { // if using Module Manager
								$results['failed'] += 1;
								$results['errors'][] = sprintf( __( 'Failed to duplicate view - %s.', 'wpv-views' ), $view['post_name'] );
							} else { // normal import
								return new WP_Error( 'could_not_duplicate_post', sprintf( __( 'Failed to duplicate view - %s.', 'wpv-views' ), $view['post_name'] ) );
							}
						} else {
							$idflag = $id;
							$new_count++;
							$imported_views[] = $id;
						}
					} else if ( 
						$force_overwrite
						|| in_array( $view['ID'], $force_import_id ) 
						|| in_array( $view['post_name'], $force_import_post_name )
					) {
						$view['ID'] = $post_to_update;
						$id = wp_update_post( $view );
						if ( ! $id ) {
							if ( $return_to == 'module_manager' ) { // if using Module Manager
								$results['failed'] += 1;
								$results['errors'][] = sprintf( __( 'Failed to update view - %s.', 'wpv-views' ), $view['post_name'] );
							} else { // normal import
								return new WP_Error( 'could_not_update_post', sprintf( __( 'Failed to update view - %s.', 'wpv-views' ), $view['post_name'] ) );
							}
						} else {
							$idflag = $id;
							$overwrite_count++;
						}
					}
				} else {
					if (
						! empty( $force_import_id )
						&& ! in_array( $view['ID'] , $force_import_id )
					) {
						continue;
					} else if (
						! empty( $force_import_post_name )
						&& ! in_array( $view['post_name'] , $force_import_post_name )
					) {
						continue;
					}
					// it's a new view: create it
					unset( $view['ID'] );
					$id = wp_insert_post( $view, true );
					if ( is_object( $id ) ) {
						// it's an WP_Error object.
						if ( $return_to == 'module_manager' ) { // if using Module Manager
							$results['failed'] += 1;
							$results['errors'][] = sprintf( __( 'Failed to create view - %s.', 'wpv-views' ), $view['post_name'] );
						} else { // normal import
							return new WP_Error( 'could_not_create_post', sprintf( __( 'Failed to create view - %s.', 'wpv-views' ), $view['post_name'] ) );
						}
					} else {
						$idflag = $id;
						$new_count++;
						$imported_views[] = $id;
					}
				}
				// Register wpml-string shortcodes for translation
				if ( $idflag ) {
					// The View was updated (if overwrite) or created, based on settings
					// Now, update postmeta
					if ( isset( $meta['_wpv_settings'] ) ) {
						
						/**
						* wpv_filter_adjust_view_settings_for_import
						*
						* Filter to adjust Views settings on import
						*
						* Some View settings are stored as indexed arrays, producing errors on index 0
						* We transformed those indexed arrays into associative arrays before export, and we restore them on import
						* Also, some settings contain IDs pointing to other Views or Content Templates
						* We transformed them into names, and we restore them on import
						*
						* @param (array) $meta['_wpv_settings'] The View settings being imported
						* @param (array) $view The View post data as an array - no meta, no attachments
						* @param (int) $idflag The resulting View ID
						*
						* @since 1.7
						*/
						
						$meta['_wpv_settings'] = apply_filters( 'wpv_filter_adjust_view_settings_for_import', $meta['_wpv_settings'], $view, $idflag );
						// Check whether this View has a filter by post Ids that might need some manual changes, and warn about it
						if ( isset( $meta['_wpv_settings']['post_id_ids_list_lost'] ) ) {
							if (
								isset( $meta['_wpv_settings']['id_mode'][0] )
								&& $meta['_wpv_settings']['id_mode'][0] == 'by_ids'
							) {
								$not_found_names[$view['post_title']] = $meta['_wpv_settings']['post_id_ids_list_lost'];
							}
							unset( $meta['_wpv_settings']['post_id_ids_list_lost'] );
						}
						if ( 
							isset( $meta['_wpv_settings']['id_mode'] ) 
							&& isset( $meta['_wpv_settings']['id_mode'][0] ) 
							&& 'shortcode' == $meta['_wpv_settings']['id_mode'][0] 
						) {
							$views_with_id_shortcodes[$view['post_title']] = $view['post_title'];
						}
						update_post_meta( $idflag, '_wpv_settings', $meta['_wpv_settings'] );
					}
					if ( isset( $meta['_wpv_layout_settings'] ) ) {
						
						/**
						* wpv_filter_adjust_view_layout_settings_for_import
						*
						* Filter to adjust Views layout settings on import
						*
						* @param (array) $meta['_wpv_settings'] The View settings being imported
						* @param (array) $view The View post data as an array - no meta, no attachments
						* @param (int) $idflag The resulting View ID
						*
						* @since 1.7
						*/
						
						$meta['_wpv_layout_settings'] = apply_filters( 'wpv_filter_adjust_view_layout_settings_for_import', $meta['_wpv_layout_settings'], $view, $idflag );
						update_post_meta( $idflag, '_wpv_layout_settings', $meta['_wpv_layout_settings'] );
					}
					foreach ( $extra_metas as $extra_meta_key ) {
						if ( isset( $meta[$extra_meta_key] ) ) {
							
							/**
							* wpv_filter_adjust_view_extra_fields_for_import
							*
							* Filter to adjust Views registered postmeta that is to be imported
							*
							* @param (array) $meta['_wpv_settings'] The View settings being imported
							* @param (array) $view The View post data as an array - no meta, no attachments
							* @param (string) $extra_meta_key The postmeta key
							* @param (int) $idflag The resulting View ID
							*
							* @since 1.7
							*/
							
							$meta[$extra_meta_key] = apply_filters( 'wpv_filter_adjust_view_extra_fields_for_import', $meta[$extra_meta_key], $view, $extra_meta_key, $idflag );
							update_post_meta( $idflag, $extra_meta_key, $meta[$extra_meta_key] );
						} else {
							delete_post_meta( $idflag, $extra_meta_key );
						}
					}
					// @todo review why or when this action is being used
					// @todo we might need the same kind of action for Content Templates import
					do_action( 'wpv_view_imported', $id_to_import, $idflag );
					// And now, translate strings if needed
					if ( isset( $view['post_content'] ) ) {
						wpv_register_wpml_strings( $view['post_content'] );
					}
					if ( isset( $meta['_wpv_settings'] ) && isset( $meta['_wpv_settings']['filter_meta_html'] ) ) {
						wpv_add_controls_labels_to_translation( $meta['_wpv_settings']['filter_meta_html'], $idflag );
						wpv_register_wpml_strings( $meta['_wpv_settings']['filter_meta_html'] );
					}
					if ( isset( $meta['_wpv_layout_settings'] ) && isset( $meta['_wpv_layout_settings']['layout_meta_html'] ) ) {
						wpv_register_wpml_strings( $meta['_wpv_layout_settings']['layout_meta_html'] );
					}

					$newitems[_VIEWS_MODULE_MANAGER_KEY_. $id_to_import] = _VIEWS_MODULE_MANAGER_KEY_.$idflag;
					
					// Remove the _toolset_edit_last postmeta flag if it exists
					do_action( 'wpv_action_wpv_import_item', $idflag );
				}
				// Juan - add images importing
				// https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/150919286/comments

				if ( 
					$idflag 
					&& ! empty( $view_images ) 
				) {
					$upload_dir = wp_upload_dir();
					$upload_path = $upload_dir['basedir'];
					$upload_directory = $upload_dir['baseurl'];
					$path_flag = true;
					if ( ! is_dir( $upload_path . DIRECTORY_SEPARATOR . 'views-import-temp' ) ) {
						mkdir( $upload_path . DIRECTORY_SEPARATOR . 'views-import-temp' );
					} else {
						$path_flag = false;  // if folder already existed
					}
					include_once( ABSPATH . 'wp-admin/includes/file.php' );
					include_once( ABSPATH . 'wp-admin/includes/media.php' );
					include_once( ABSPATH . 'wp-admin/includes/image.php');
					foreach ( $view_images as $attach_array ) {
						$attach_array = array_reverse( $attach_array );
						foreach ( $attach_array as $attach ) {
							if ( 
								isset( $attach['data'] ) 
								&& isset( $attach['filename'] ) 
							) {
								//  decode attachment data and create the file
								$imgdata = base64_decode($attach['data']);
								file_put_contents( $upload_path . DIRECTORY_SEPARATOR . 'views-import-temp' . DIRECTORY_SEPARATOR . $attach['filename'], $imgdata );
								// upload the file using WordPress API and add it to the post as attachment
								// preserving all fields but alt
								$tmp = download_url( $upload_directory . '/views-import-temp/' . $attach['filename'] );
								$file_array['name'] = $attach['filename'];
								$file_array['tmp_name'] = $tmp;
								if ( is_wp_error( $tmp ) ) {
									@unlink( $file_array['tmp_name'] );
									$file_array['tmp_name'] = '';
								}
								$att_data = array();
								if ( isset( $attach['title'] ) ) {
									$att_data['post_title'] = $attach['title'];
								}
								if ( isset($attach['content'] ) ) {
									$att_data['post_content'] = $attach['content'];
								}
								if ( isset($attach['excerpt'] ) ) {
									$att_data['post_excerpt'] = $attach['excerpt'];
								}
								if ( isset($attach['status'] ) ) {
									$att_data['post_status'] = $attach['status'];
								}
								$att_id = media_handle_sideload( $file_array, $idflag, null, $att_data );
								if ( is_wp_error($att_id) ) {
									@unlink( $file_array['tmp_name'] );
									return new WP_Error( 'could_not_import_attachment', sprintf( __( 'Failed to import View attachment - %s, %s.', 'wpv-views' ), $view['post_name'], $file_array['name'] ) );
								}
								// update alt field
								if ( isset( $attach['alt'] ) ) {
									update_post_meta( $att_id, '_wp_attachment_image_alt', $attach['alt'] );
								}
								@unlink( $upload_path . DIRECTORY_SEPARATOR . 'views-import-temp' . DIRECTORY_SEPARATOR . $attach['filename'] );
								// set spinner image and attached images added to MetaHTML boxes
								$att_attributes = wp_get_attachment_image_src( $att_id, 'full');
								foreach ($attached_images_sizes as $ts) {
									$imthumbs[$ts] = wp_get_attachment_image_src( $att_id, $ts );
									if ( isset( $attach['custom_spinner'] ) && ( 'this_' . $ts == $attach['custom_spinner'] ) ) {
										$meta['_wpv_settings']['pagination']['spinner_image_uploaded'] = $imthumbs[$ts][0];
									}
									if ( isset( $attach['dps_custom_spinner'] ) && ( 'this_' . $ts == $attach['dps_custom_spinner'] ) ) {
										$meta['_wpv_settings']['dps']['spinner_image_uploaded'] = $imthumbs[$ts][0];
									}
								}
								if ( isset( $attach['custom_spinner'] ) && 'this' == $attach['custom_spinner'] ) {
									$meta['_wpv_settings']['pagination']['spinner_image_uploaded'] = $att_attributes[0];
								}
								if ( isset( $attach['dps_custom_spinner'] ) && 'this' == $attach['dps_custom_spinner'] ) {
									$meta['_wpv_settings']['dps']['spinner_image_uploaded'] = $att_attributes[0];
								}
								
								foreach ( $this_settings_metaboxes as $metabox_id ) {
									if ( isset( $attach['on_' . $metabox_id] ) ) {
										$meta['_wpv_settings'][$metabox_id] = str_replace( $attach['on_' . $metabox_id], $att_attributes[0], $meta['_wpv_settings'][$metabox_id] );
									}
									if ( 
										isset( $attach['on_' . $metabox_id . '_sizes'] ) 
										&& is_array( $attach['on_' . $metabox_id . '_sizes'] ) 
									) {
										foreach ( $attach['on_' . $metabox_id . '_sizes'] as $atsize => $aturl ) {
											if ( in_array( $atsize, $attached_images_sizes ) ) {
												$meta['_wpv_settings'][$metabox_id] = str_replace( $aturl, $imthumbs[$atsize][0], $meta['_wpv_settings'][$metabox_id] );
											} else {
												$meta['_wpv_settings'][$metabox_id] = str_replace( $aturl, $imthumbs['thumbnail'][0], $meta['_wpv_settings'][$metabox_id] );
											}
										}
									}
								}
								foreach ( $this_layout_settings_metaboxes as $metabox_id ) {
									if ( isset( $attach['on_' . $metabox_id] ) ) {
										$meta['_wpv_layout_settings'][$metabox_id] = str_replace( $attach['on_' . $metabox_id], $att_attributes[0], $meta['_wpv_layout_settings'][$metabox_id] );
									}
									if ( 
										isset( $attach['on_' . $metabox_id . '_sizes'] ) 
										&& is_array( $attach['on_' . $metabox_id . '_sizes'] ) 
									) {
										foreach ( $attach['on_' . $metabox_id . '_sizes'] as $atsize => $aturl ) {
											if ( in_array( $atsize, $attached_images_sizes ) ) {
												$meta['_wpv_layout_settings'][$metabox_id] = str_replace( $aturl, $imthumbs[$atsize][0], $meta['_wpv_layout_settings'][$metabox_id] );
											} else {
												$meta['_wpv_layout_settings'][$metabox_id] = str_replace( $aturl, $imthumbs['thumbnail'][0], $meta['_wpv_layout_settings'][$metabox_id] );
											}
										}
									}
								}
								if ( isset( $attach['on_post_content'] ) ) {
									$up['ID'] = $idflag;
									$up['post_content'] = get_post_field('post_content', $idflag);
									$up['post_content'] = str_replace( $attach['on_post_content'], $att_attributes[0], $up['post_content'] );
									wp_update_post( $up );
								}
								if ( 
									isset( $attach['on_post_content_sizes'] ) 
									&& is_array( $attach['on_post_content_sizes'] ) 
								) {
									$up['ID'] = $idflag;
									$up['post_content'] = get_post_field( 'post_content', $idflag );
									foreach ( $attach['on_post_content_sizes'] as $atsize => $aturl ) {
										if ( in_array( $atsize, $attached_images_sizes ) ) {
											$up['post_content'] = str_replace( $aturl, $imthumbs[$atsize][0], $up['post_content'] );
										} else {
											$up['post_content'] = str_replace( $aturl, $imthumbs['thumbnail'][0], $up['post_content'] );
										}
									}
									wp_update_post( $up );
								}
							}
						}
					}
					update_post_meta( $idflag, '_wpv_settings', $meta['_wpv_settings'] );
					update_post_meta( $idflag, '_wpv_layout_settings', $meta['_wpv_layout_settings'] );
					if ( $path_flag ) {
						rmdir($upload_path . DIRECTORY_SEPARATOR . 'views-import-temp');
					}
				}
			}
		}

		$deleted_count = 0;
		if ( $force_delete ) {
			if ( ! is_array( $imported_views ) ) {
				$imported_views = array();
			}
			$imported_views = array_map( 'esc_attr', $imported_views );
			$imported_views = array_map( 'trim', $imported_views );
			// is_numeric + intval does sanitization
			$imported_views = array_filter( $imported_views, 'is_numeric' );
			$imported_views = array_map( 'intval', $imported_views );
			$views_delete_exclude_for_query = implode( ',', $imported_views );
			if ( ! empty( $views_delete_exclude_for_query ) ) {
				$views_delete_exclude_for_query = " AND ID NOT IN ( " . $views_delete_exclude_for_query . " )";
			}
			$views_to_delete = $wpdb->get_col( 
				$wpdb->prepare(
					"SELECT ID FROM {$wpdb->posts} 
					WHERE post_type = %s 
					{$views_delete_exclude_for_query}",
					'view'
				)
			);
			if ( ! empty( $views_to_delete ) ) {
				foreach ( $views_to_delete as $views_to_delete_id ) {
					wp_delete_post( $views_to_delete_id, true );
					$deleted_count++;
				}
			}
		}

		$this->import_messages[] = sprintf( __( '%d Views found in the file. %d have been created and %d have been over written.', 'wpv-views' ), sizeof( $imported_views ), $new_count, $overwrite_count );

		if ( $deleted_count ) {
			$this->import_messages[] = sprintf( __( '%d existing Views were deleted.', 'wpv-views' ), $deleted_count );
		}

		if ( 
			isset( $not_found_names ) 
			&& ! empty( $not_found_names ) 
		) {
			$view_names = implode( ', ', array_keys( $not_found_names ) );
			$this->import_messages[] = __('Those Views have filters by IDs that were not correctly imported because they filter by posts that do not exist. Please review them: ', 'wpv-views') . '<strong>' . $view_names . '</strong>';
		}
		if ( 
			isset( $views_with_id_shortcodes ) 
			&& ! empty( $views_with_id_shortcodes ) 
		) {
			$view_names = implode( ', ', array_keys( $views_with_id_shortcodes ) );
			$this->import_messages[] = __( 'Those Views filter by post IDs using a shortcode attribute. You may need to modify the Views shortcodes if post IDs have changed during import: ', 'wpv-views' ) . '<strong>' . $view_names . '</strong>';
		}

		$results['updated'] = $overwrite_count;
		$results['new'] = $new_count;
		
		if ( $return_to == 'module_manager' ) {
			$results['items'] = $newitems;
			return $results;
		} else {
			return true; // no errors
		}
	}
function wpv_admin_import_views($import_data, $items = array())
{
    global $wpdb, $import_messages, $WP_Views;
    $imported_views = array();
    $overwrite_count = 0;
    $new_count = 0;
    $results = array('updated' => 0, 'new' => 0, 'failed' => 0, 'errors' => array());
    $newitems = array();
    if (false !== $items && is_array($items)) {
        $import_items = array();
        foreach ($items as $item) {
            $import_items[] = str_replace(_VIEWS_MODULE_MANAGER_KEY_, '', $item);
        }
    }
    if (isset($import_data['views']['view'])) {
        $views = $import_data['views']['view'];
        // check for a single view
        if (!isset($views[0])) {
            $views = array($views);
        }
        foreach ($views as $view) {
            $meta = $view['meta'];
            unset($view['meta']);
            $view_images = array();
            if (isset($view['attachments'])) {
                $view_images = array($view['attachments']);
                unset($view['attachments']);
            }
            // SRDJAN - https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/142389966/comments
            // Fix URLs
            if (!empty($import_data['site_url']) && !empty($import_data['fileupload_url'])) {
                if (!empty($meta['_wpv_settings']['pagination']['spinner_image'])) {
                    $meta['_wpv_settings']['pagination']['spinner_image'] = WPV_URL_EMBEDDED . '/res/img/' . basename($meta['_wpv_settings']['pagination']['spinner_image']);
                }
                if (!empty($meta['_wpv_settings']['pagination']['spinner_image_uploaded'])) {
                    $old_custom_spinner = $meta['_wpv_settings']['pagination']['spinner_image_uploaded'];
                    // keep it for comparing in the new images importing flow
                    $meta['_wpv_settings']['pagination']['spinner_image_uploaded'] = wpv_convert_url($meta['_wpv_settings']['pagination']['spinner_image_uploaded'], $import_data['site_url'], $import_data['fileupload_url']);
                }
            }
            // SRDJAN - fix term_ids
            // https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/142382866/comments
            if (!empty($meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'])) {
                foreach ($meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'] as $term_key => $old_term_id) {
                    if (isset($import_data['terms_map']['term_' . $old_term_id])) {
                        $new_term = get_term_by('slug', $import_data['terms_map']['term_' . $old_term_id]['slug'], $import_data['terms_map']['term_' . $old_term_id]['taxonomy']);
                        if (!empty($new_term)) {
                            $meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'][$term_key] = $new_term->term_id;
                        }
                    }
                }
            }
            if (isset($meta['_wpv_settings'])) {
                $meta['_wpv_settings'] = $WP_Views->convert_names_to_ids_in_settings($meta['_wpv_settings']);
            }
            if (isset($meta['_wpv_layout_settings'])) {
                $meta['_wpv_layout_settings'] = $WP_Views->convert_names_to_ids_in_layout_settings($meta['_wpv_layout_settings']);
            }
            $idflag = 0;
            // add flag to know if we are overwritting or creating something
            $id_to_import = $view['ID'];
            $post_to_update = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts}\n                                WHERE post_name = %s AND post_type = %s", $view['post_name'], 'view'));
            if ($post_to_update) {
                $imported_views[] = $post_to_update;
                // only update if we have overwrite enabled (normal import) or if the View is on the $import_items array (Module Manager)
                if (isset($_POST['views-overwrite']) && $_POST['views-overwrite'] == 'on' || in_array($view['ID'], $import_items)) {
                    $old_view_id = $view['ID'];
                    $view['ID'] = $post_to_update;
                    $id = wp_update_post($view);
                    if (!$id) {
                        if (in_array($old_view_id, $import_items)) {
                            // if using Module Manager
                            $results['failed'] += 1;
                            $results['errors'][] = sprintf(__('Failed to update view - %s.', 'wpv-views'), $view['post_name']);
                        } else {
                            // normal import
                            return new WP_Error('could_not_update_post', sprintf(__('Failed to update view - %s.', 'wpv-views'), $view['post_name']));
                        }
                    } else {
                        $idflag = $id;
                        $overwrite_count++;
                        if (isset($meta['_wpv_settings'])) {
                            update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                        }
                        if (isset($meta['_wpv_layout_settings'])) {
                            update_post_meta($id, '_wpv_layout_settings', $meta['_wpv_layout_settings']);
                        }
                        do_action('wpv_view_imported', $old_view_id, $id);
                    }
                }
            } elseif (empty($import_items) || !empty($import_items) && in_array($view['ID'], $import_items)) {
                // it's a new view: create it
                // create if array $import_items is empty (normal import) or if array is not empty and the View is on this array (Module Manager)
                $old_view_id = $view['ID'];
                unset($view['ID']);
                $id = wp_insert_post($view, true);
                if (is_object($id)) {
                    // it's an WP_Error object.
                    if (in_array($old_view_id, $import_items)) {
                        // if using Module Manager
                        $results['failed'] += 1;
                        $results['errors'][] = sprintf(__('Failed to create view - %s.', 'wpv-views'), $view['post_name']);
                    } else {
                        // normal import
                        return $id;
                    }
                } else {
                    $idflag = $id;
                    $new_count++;
                    $imported_views[] = $id;
                    if (isset($meta['_wpv_settings'])) {
                        update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                    }
                    if (isset($meta['_wpv_layout_settings'])) {
                        update_post_meta($id, '_wpv_layout_settings', $meta['_wpv_layout_settings']);
                    }
                    do_action('wpv_view_imported', $old_view_id, $id);
                }
            }
            // Juan - add images importing
            // https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/150919286/comments
            if ($idflag && !empty($view_images)) {
                $upload_dir = wp_upload_dir();
                $upload_path = $upload_dir['basedir'];
                $upload_directory = $upload_dir['baseurl'];
                $path_flag = true;
                if (!is_dir($upload_path . DIRECTORY_SEPARATOR . 'views-import-temp')) {
                    mkdir($upload_path . DIRECTORY_SEPARATOR . 'views-import-temp');
                } else {
                    $path_flag = false;
                    // if folder already existed
                }
                include_once ABSPATH . 'wp-admin/includes/file.php';
                include_once ABSPATH . 'wp-admin/includes/media.php';
                include_once ABSPATH . 'wp-admin/includes/image.php';
                foreach ($view_images as $attach_array) {
                    foreach ($attach_array as $attach) {
                        if (isset($attach['data']) && isset($attach['filename'])) {
                            //  decode attachment data and create the file
                            $imgdata = base64_decode($attach['data']);
                            file_put_contents($upload_path . DIRECTORY_SEPARATOR . 'views-import-temp' . DIRECTORY_SEPARATOR . $attach['filename'], $imgdata);
                            // upload the file using WordPress API and add it to the post as attachment
                            // preserving all fields but alt
                            $tmp = download_url($upload_directory . '/views-import-temp/' . $attach['filename']);
                            $file_array['name'] = $attach['filename'];
                            $file_array['tmp_name'] = $tmp;
                            if (is_wp_error($tmp)) {
                                @unlink($file_array['tmp_name']);
                                $file_array['tmp_name'] = '';
                            }
                            $att_data = array();
                            if (isset($attach['title'])) {
                                $att_data['post_title'] = $attach['title'];
                            }
                            if (isset($attach['content'])) {
                                $att_data['post_content'] = $attach['content'];
                            }
                            if (isset($attach['excerpt'])) {
                                $att_data['post_excerpt'] = $attach['excerpt'];
                            }
                            if (isset($attach['status'])) {
                                $att_data['post_status'] = $attach['status'];
                            }
                            $att_id = media_handle_sideload($file_array, $id, null, $att_data);
                            if (is_wp_error($att_id)) {
                                @unlink($file_array['tmp_name']);
                                return $att_id;
                            }
                            // update alt field
                            if (isset($attach['alt'])) {
                                update_post_meta($att_id, '_wp_attachment_image_alt', $attach['alt']);
                            }
                            @unlink($upload_path . DIRECTORY_SEPARATOR . 'views-import-temp' . DIRECTORY_SEPARATOR . $attach['filename']);
                            // set spinner image and attached images added to MetaHTML boxes
                            $att_attributes = wp_get_attachment_image_src($att_id, 'full');
                            if (isset($attach['custom_spinner']) && 'this' == $attach['custom_spinner']) {
                                $meta['_wpv_settings']['pagination']['spinner_image_uploaded'] = $att_attributes[0];
                                update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                            }
                            if (isset($attach['on_filter_meta_html'])) {
                                $meta['_wpv_settings']['filter_meta_html'] = str_replace($attach['on_filter_meta_html'], $att_attributes[0], $meta['_wpv_settings']['filter_meta_html']);
                                update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                            }
                            if (isset($attach['on_filter_meta_html_css'])) {
                                $meta['_wpv_settings']['filter_meta_html_css'] = str_replace($attach['on_filter_meta_html_css'], $att_attributes[0], $meta['_wpv_settings']['filter_meta_html_css']);
                                update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                            }
                            if (isset($attach['on_layout_meta_html'])) {
                                $meta['_wpv_layout_settings']['layout_meta_html'] = str_replace($attach['on_layout_meta_html'], $att_attributes[0], $meta['_wpv_layout_settings']['layout_meta_html']);
                                update_post_meta($id, '_wpv_layout_settings', $meta['_wpv_layout_settings']);
                            }
                            if (isset($attach['on_layout_meta_html_css'])) {
                                $meta['_wpv_settings']['layout_meta_html_css'] = str_replace($attach['on_layout_meta_html_css'], $att_attributes[0], $meta['_wpv_settings']['layout_meta_html_css']);
                                update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                            }
                        }
                    }
                }
                if ($path_flag) {
                    rmdir($upload_path . DIRECTORY_SEPARATOR . 'views-import-temp');
                }
            }
            if ($idflag) {
                $newitems[$id_to_import] = $idflag;
            }
        }
    }
    $deleted_count = 0;
    if (isset($_POST['views-delete']) && $_POST['views-delete'] == 'on') {
        $views_to_delete = get_posts('post_type=view&post_status=any&posts_per_page=-1');
        if (!empty($views_to_delete)) {
            foreach ($views_to_delete as $view_to_delete) {
                if (!in_array($view_to_delete->ID, $imported_views)) {
                    wp_delete_post($view_to_delete->ID, true);
                    $deleted_count++;
                }
            }
        }
    }
    $import_messages[] = sprintf(__('%d Views found in the file. %d have been created and %d have been over written.', 'wpv-views'), sizeof($imported_views), $new_count, $overwrite_count);
    if ($deleted_count) {
        $import_messages[] = sprintf(__('%d existing Views were deleted.', 'wpv-views'), $deleted_count);
    }
    $results['updated'] = $overwrite_count;
    $results['new'] = $new_count;
    if (empty($import_items)) {
        // normal import
        return false;
        // no errors
    } else {
        // Module Manager import
        $results['items'] = $newitems;
        return $results;
    }
}
function wpv_admin_import_views($import_data)
{
    global $wpdb, $import_messages, $WP_Views;
    $imported_views = array();
    $overwrite_count = 0;
    $new_count = 0;
    if (isset($import_data['views']['view'])) {
        $views = $import_data['views']['view'];
        // check for a single view
        if (!isset($views[0])) {
            $views = array($views);
        }
        foreach ($views as $view) {
            $meta = $view['meta'];
            unset($view['meta']);
            // SRDJAN - https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/142389966/comments
            // Fix URLs
            if (!empty($import_data['site_url']) && !empty($import_data['fileupload_url'])) {
                if (!empty($meta['_wpv_settings']['pagination']['spinner_image'])) {
                    $meta['_wpv_settings']['pagination']['spinner_image'] = WPV_URL_EMBEDDED . '/res/img/' . basename($meta['_wpv_settings']['pagination']['spinner_image']);
                }
                if (!empty($meta['_wpv_settings']['pagination']['spinner_image_uploaded'])) {
                    $meta['_wpv_settings']['pagination']['spinner_image_uploaded'] = wpv_convert_url($meta['_wpv_settings']['pagination']['spinner_image_uploaded'], $import_data['site_url'], $import_data['fileupload_url']);
                }
            }
            // SRDJAN - fix term_ids
            // https://icanlocalize.basecamphq.com/projects/7393061-wp-views/todo_items/142382866/comments
            if (!empty($meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'])) {
                foreach ($meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'] as $term_key => $old_term_id) {
                    if (isset($import_data['terms_map']['term_' . $old_term_id])) {
                        $new_term = get_term_by('slug', $import_data['terms_map']['term_' . $old_term_id]['slug'], $import_data['terms_map']['term_' . $old_term_id]['taxonomy']);
                        if (!empty($new_term)) {
                            $meta['_wpv_settings']['taxonomy_terms']['taxonomy_term'][$term_key] = $new_term->term_id;
                        }
                    }
                }
            }
            if (isset($meta['_wpv_settings'])) {
                $meta['_wpv_settings'] = $WP_Views->convert_names_to_ids_in_settings($meta['_wpv_settings']);
            }
            if (isset($meta['_wpv_layout_settings'])) {
                $meta['_wpv_layout_settings'] = $WP_Views->convert_names_to_ids_in_layout_settings($meta['_wpv_layout_settings']);
            }
            $post_to_update = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts}\n                                WHERE post_name = %s AND post_type = %s", $view['post_name'], 'view'));
            if ($post_to_update) {
                $imported_views[] = $post_to_update;
                // only update if we have overwrite enabled.
                if (isset($_POST['views-overwrite']) && $_POST['views-overwrite'] == 'on') {
                    $overwrite_count++;
                    $view['ID'] = $post_to_update;
                    $id = wp_update_post($view);
                    if (!$id) {
                        return new WP_Error('could_not_update_post', sprintf(__('Failed to update view - %s.', 'wpv-views'), $view['post_name']));
                    }
                    if (isset($meta['_wpv_settings'])) {
                        update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                    }
                    if (isset($meta['_wpv_layout_settings'])) {
                        update_post_meta($id, '_wpv_layout_settings', $meta['_wpv_layout_settings']);
                    }
                }
            } else {
                // it's a new view template
                $new_count++;
                unset($view['ID']);
                $id = wp_insert_post($view, true);
                if (is_object($id)) {
                    // it's an WP_Error object.
                    return $id;
                }
                $imported_views[] = $id;
                if (isset($meta['_wpv_settings'])) {
                    update_post_meta($id, '_wpv_settings', $meta['_wpv_settings']);
                }
                if (isset($meta['_wpv_layout_settings'])) {
                    update_post_meta($id, '_wpv_layout_settings', $meta['_wpv_layout_settings']);
                }
            }
        }
    }
    $deleted_count = 0;
    if (isset($_POST['views-delete']) && $_POST['views-delete'] == 'on') {
        $views_to_delete = get_posts('post_type=view&post_status=any&posts_per_page=-1');
        if (!empty($views_to_delete)) {
            foreach ($views_to_delete as $view_to_delete) {
                if (!in_array($view_to_delete->ID, $imported_views)) {
                    wp_delete_post($view_to_delete->ID, true);
                    $deleted_count++;
                }
            }
        }
    }
    $import_messages[] = sprintf(__('%d Views found in the file. %d have been created and %d have been over written.', 'wpv-views'), sizeof($imported_views), $new_count, $overwrite_count);
    if ($deleted_count) {
        $import_messages[] = sprintf(__('%d existing Views were deleted.', 'wpv-views'), $deleted_count);
    }
    return false;
    // no errors
}