/**
	 * Converts a single wprss_feed_item to a post.
	 * 
	 * @param feed 		The wprss_feed_item object to convert
	 * @param source 	The wprss_feed id of the feed item. Used to retrieve settings for conversion.
	 * @since 1.0
	 */
	public static function convert_to_post( $item, $source, $permalink ) {
		WPRSS_FTP_Utils::log( 'Starting conversion to post', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		
		$error_source = 'convert_to_post';
		$source_obj = get_post( $source );

		// If the feed source does not exist, exit
		if ( $source_obj === null || $source === '' ) {
			// unschedule any scheduled updates
			wprss_feed_source_update_stop_schedule( $source );
			WPRSS_FTP_Utils::log_object( 'Source does not exist. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
			return NULL;
		} else {
			// If the feed source exists, but is trashed or paused, exit
			if ( $source_obj->post_status !== 'trash' && !wprss_is_feed_source_active( $source ) ) {
				WPRSS_FTP_Utils::log_object( 'Source is inactive or trashed. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
				return NULL;
			}
		}

		# If we got NULL, pass it on
		if ( $item === NULL ) {
			WPRSS_FTP_Utils::log( 'Item is null. Aborting.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
			return NULL;
		}
		# If the item has an empty permalink, log an error message
		if ( empty( $permalink ) ){
			WPRSS_FTP_Utils::log( 'Encounted feed item with no permalink for feed source "' . $source_obj->post_title . '". Possibly a corrupt RSS feed.', $error_source, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
		}

		# check existence of permalink
		$existing_permalinks = self::get_existing_permalinks( $source );

		# If permalink exists, do nothing
		if ( in_array( $permalink, $existing_permalinks ) ) {
			WPRSS_FTP_Utils::log_object( 'Item with this permalink already exists. Aborting.', $permalink, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
			return NULL;
		}

		# Get the computed options ( global settings merged against individual settings )
		$options = WPRSS_FTP_Settings::get_instance()->get_computed_options( $source );

		if ( $options['post_type'] === 'wprss_feed_item' ) {
			WPRSS_FTP_Utils::log_object( 'Legacy import method. Aborting.', $source, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			return $item;
		}
		
		self::_prepareItem( $item );

		/*==============================================
		 * 1) DETERMINE THE POST AUTHOR USER
		 */
		WPRSS_FTP_Utils::log( 'Determining post author...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		// Get author-related options from meta, or from global settings, if not found
		$def_author = $options['def_author'];
		$fallback_author = $options['fallback_author'];
		$author_fallback_method = $options['author_fallback_method'];
		$fallback_user = get_user_by( 'id', $fallback_author );
		if ( ! is_object( $fallback_user ) ) {
			$fallback_user = get_user_by( 'login', $fallback_author );
		}
		$fallback_user = $fallback_user->ID;
		$no_author_found = $options['no_author_found'];

		// Determined user. Start with NULL
		$user = NULL;

		// If using an existing user, we are done.
		if ( $def_author !== '.' ) {
			$user = $def_author;
			WPRSS_FTP_Utils::log( 'Author is preset.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		}
		// If getting feed from author, determine the user to assign to the post
		else {
			/* Get the author from the feed
			 * If author not found - use fallback user
			 */
			if ( $author = $item->get_author() ) {
			    $has_author_name = $author->get_name() !== '' && is_string( $author->get_name() );
			    $has_author_email = $author->get_email() !== '' && is_string( $author->get_email() );
			}
			else {
			    $has_author_name = $has_author_email = false;
			}

			// Author NOT found
			if ( $author === NULL || !( $has_author_name || $has_author_email ) ) {
				// If option to use fallback when no author found, use fallback
				if ( $no_author_found === 'fallback' ) {
					$user = $fallback_user;
					WPRSS_FTP_Utils::log_object( 'Author is a fallback user.', $fallback_user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}
				// Otherwise, skip the post
				else {
					WPRSS_FTP_Utils::log( 'Author could not be determined. Aborting.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );
					return NULL;
				}
			}
			// Author found
			else {
				WPRSS_FTP_Utils::log( 'Author found in feed.', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				$author_name = $author->get_name();
				$author_email = $author->get_email();

				// No author name fix
				if ( !$has_author_name && $has_author_email ) {
					// "Email is actually the name"" fix
					if ( filter_var( $author_email, FILTER_VALIDATE_EMAIL ) === FALSE ) {
						// Set the name to the email, and reset the email
						$author_name = $author_email;
						$author_email = '';
						// Set the flags appropriately
						$has_author_name = TRUE;
						$has_author_email = FALSE;
					}
					else {
						$parts = explode("@", $author_email);
						$author_name = $parts[0];
						$has_author_name = TRUE;
					}
					
					WPRSS_FTP_Utils::log_object( sprintf( 'Author name determined from email "%1$s".', $author_email), $author_name, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}
				
				// No author email fix
				if ( !$has_author_email && $has_author_name ) {
					// Get rid of wwww and everything before it
					$domain_name =  preg_replace( '/^www\./', '', $_SERVER['SERVER_NAME'] );
					// Lowercase the author name, remove the spaces
					$email_username = str_replace( ' ', '', strtolower($author_name) );
					// Remove all disallowed chars
					$email_username = preg_replace('![^\w\d_.]!', '', $email_username);
					// For domains with no TLDN suffix (such as localhost)
					if ( stripos( $domain_name, '.' ) === FALSE ) $domain_name .= '.com';
					// Generate the email
					$author_email = "$email_username@$domain_name";
					$has_author_email = TRUE;
					
					WPRSS_FTP_Utils::log_object( sprintf( 'Author email determined from name "%1$s".', $author_name), $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}

				$user_obj = FALSE;

				// If email is available, check if a user with this email exists
				$user_obj = get_user_by( 'email', $author_email );
				// If search by email failed, search the email for the login
				if ( !$user_obj ) {
					$user_obj = get_user_by( 'login', $author_email );
				}
				// If search by email failed, search by name
				if ( !$user_obj ) {
					$user_obj = get_user_by( 'login', $author_name );
				}

				// Feed author has a user on site
				if ( $user_obj !== FALSE && isset( $user_obj->ID ) ) {
					$user = $user_obj->ID;
					WPRSS_FTP_Utils::log_object( 'User found in system', $user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
				}
				// Author has no user on site
				else {
					$new_user_id = NULL;

					// Fallback method: create user
					if ( $author_fallback_method === 'create' ) {
						$random_password = wp_generate_password( $length = 12, $include_standard_special_chars = false );
						$new_user_id = wp_create_user( $author_name, $random_password, $author_email );
						WPRSS_FTP_Utils::log_object( 'User not found in system. Attempted to create', $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
						if ( !$new_user_id || ($is_error = is_wp_error( $new_user_id )) ) {
							WPRSS_FTP_Utils::log_object( 'User could not be created.', $is_error ? $new_user_id->get_error_message() : $author_email, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
							$new_user_id = null;
						} else {
							// Check if the author has a URI in the feed
							$author_uri = $author->get_link();
							if ( $author_uri !== NULL ) {
								// Filter the meta field and value
								$uri_meta = apply_filters( 'wprss_author_uri_meta_field', 'wprss_author_uri' );
								$author_uri = apply_filters( 'wprss_author_uri', $author_uri, $source );
								// Add the URI as user meta
								add_user_meta( $user, $uri_meta,  $author_uri );
								// Add the URI to the author
								wp_update_user( array(
									'ID'		=>	$new_user_id,
									'user_url'	=>	$author_uri,
								) );
							}

							// Check if the author name has spaces
							if ( strpos( $author_name, ' ' ) !== FALSE ) {
								// Split name into parts
								$split = explode( ' ', $author_name );
								$first_name = '';
								$last_name = '';
								// check if we have more than one parts
								if ( ( $c = count( $split ) ) > 1 ) {
									$m = $c / 2;
									$first_half = array_slice( $split, 0, $m);
									$second_half = array_slice( $split, $m );
									$first_name = implode( ' ', $first_half );
									$last_name = implode( ' ', $second_half );
								}
								// Update the user
								wp_update_user( array(
									'ID'			=>	$new_user_id,
									'first_name'	=>	$first_name,
									'last_name'		=>	$last_name,
								) );
							}
						}
					}

					// Fallback method: existing user
					// OR creating a user failed
					if ( $new_user_id === NULL ) {
						$new_user_id = $fallback_user;
						WPRSS_FTP_Utils::log_object( 'Falling back to existing user', $new_user_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
					}

					$user = $new_user_id;
				}
			}
		}
		
		WPRSS_FTP_Utils::log_object( 'Post author determined', $user, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

		// Get WordPress' GMT offset in hours, and PHP's timezone
		$wp_tz = function_exists('wprss_get_timezone_string') ? wprss_get_timezone_string() : get_option( 'timezone_string ' );
		$php_tz = date_default_timezone_get();
		// Set Timezone to WordPress'
		date_default_timezone_set( $wp_tz );
		WPRSS_FTP_Utils::log_object( 'Default timezone temporarily changed', $wp_tz, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		
		// Prepare the rest of the post data
		$date_timestamp = ( $options['post_date'] === 'original' && ( $date_timestamp = $item->get_date( 'U' ) ) )
				? $date_timestamp
				: date( 'U' ); // Fall back to current date if explicitly configured, or no date
		
                // Prepare post dates
		$post_date		= date( 'Y-m-d H:i:s', $date_timestamp );
		$post_date_gmt	= gmdate( 'Y-m-d H:i:s', $date_timestamp );
		WPRSS_FTP_Utils::log_object( 'Post timestamp determined', $date_timestamp, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );

		// Reset Timezone to PHP's
		date_default_timezone_set( $php_tz );
		WPRSS_FTP_Utils::log_object( 'Default timezone restored', $php_tz, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		
		// Prepare the post tags
		$tags_str = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'post_tags' );
		$tags = array_map( 'trim', explode( ',', $tags_str ) );
		if( count( $tags ) )
			WPRSS_FTP_Utils::log_object( 'Tags will be added', $tags_str, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );


		/*==============================================
		 * 2) APPLY FILTERS TO POST FIELDS
		 */

		WPRSS_FTP_Utils::log( 'Applying filters to post fields...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		
		WPRSS_FTP_Utils::log( 'Applying post_title filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_title		= apply_filters( 'wprss_ftp_converter_post_title',		$item->get_title(), $source );

		WPRSS_FTP_Utils::log( 'Applying post_content filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_content	= apply_filters( 'wprss_ftp_converter_post_content',	$item->get_content(), $source );

		WPRSS_FTP_Utils::log( 'Applying post_status filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_status 	= apply_filters( 'wprss_ftp_converter_post_status',		$options['post_status'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_comments filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_comments 	= apply_filters( 'wprss_ftp_converter_post_comments',	$options['comment_status'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_type filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_type 		= apply_filters( 'wprss_ftp_converter_post_type',		$options['post_type'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_format filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_format 	= apply_filters( 'wprss_ftp_converter_post_format',		$options['post_format'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_terms filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_terms 	= apply_filters( 'wprss_ftp_converter_post_terms',		$options['post_terms'], $source );

		WPRSS_FTP_Utils::log( 'Applying post_taxonomy filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_taxonomy 	= apply_filters( 'wprss_ftp_converter_post_taxonomy',	$options['post_taxonomy'], $source );

		WPRSS_FTP_Utils::log( 'Applying permalink filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$permalink 		= apply_filters( 'wprss_ftp_converter_permalink',		$permalink, $source );

		WPRSS_FTP_Utils::log( 'Applying post_author filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_author 	= apply_filters( 'wprss_ftp_converter_post_author',		$user, $source );

		WPRSS_FTP_Utils::log( 'Applying post_date filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_date		= apply_filters( 'wprss_ftp_converter_post_date',		$post_date, $source );

		WPRSS_FTP_Utils::log( 'Applying post_date_gmt filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_date_gmt	= apply_filters( 'wprss_ftp_converter_post_date_gmt',	$post_date_gmt, $source );

		WPRSS_FTP_Utils::log( 'Applying post_tags filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_tags		= apply_filters( 'wprss_ftp_converter_post_tags',		$tags, $source );

		WPRSS_FTP_Utils::log( 'Applying post_language filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_language 	= apply_filters( 'wprss_ftp_converter_post_language',	$options['post_language'], $source );
		
		WPRSS_FTP_Utils::log( 'Applying post_site filter...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post_site		= apply_filters( 'wprss_ftp_converter_post_site',		$options['post_site'], $source );
		
		WPRSS_FTP_Utils::log( 'Filters applied', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );

		$post_comments = ( WPRSS_FTP_Utils::multiboolean( $post_comments ) === TRUE )? 'open' : 'close';
		WPRSS_FTP_Utils::log_object( 'Comments status determined', $post_comments, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );


		/*==============================================
		 * 3) CREATE THE POST
		 */

		// Initialize the excerpt to an empty string
		$post_excerpt = '';

		// Prepare the post data
		WPRSS_FTP_Utils::log( 'Begin creating post...', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		$post = array(
			'post_title'		=>	$post_title,
			'post_content'		=>	$post_content,
			'post_excerpt'		=>	$post_excerpt,
			'post_date'			=>	$post_date,
			'post_date_gmt'		=>	$post_date_gmt,
			'post_status'		=>	$post_status,
			'post_type'			=>	$post_type,
			'post_author'		=>	$post_author,
			'tags_input'		=>	implode( ', ' , $post_tags ),
			'comment_status'	=>	$post_comments
		);

		/**
		 * Filter the post args.
		 * @var array $post		Array containing the post fields
		 * @var WP_Post $source		An post that represents the feed source
		 * @var SimplePie_Item $item    The feed item currently being processed
		 */
		$post = apply_filters( 'wprss_ftp_post_args', $post, $source, $item );
		WPRSS_FTP_Utils::log( 'Post args filters applied', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		

		/*==============================================
		 * 4) INSERT THE POST
		 */
		if ( defined( 'ICL_SITEPRESS_VERSION' ) )
			@include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' );
		if ( defined( 'ICL_LANGUAGE_CODE' ) ) {
			$_POST['icl_post_language'] = $language_code = ICL_LANGUAGE_CODE;
			WPRSS_FTP_Utils::log_object( 'WPMP Detected. Language determined.', $language_code, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		}


		// check for multisite option - and switch blogs if necessaray
		$switch_success = FALSE;
		if ( WPRSS_FTP_Utils::is_multisite() && $post_site !== '' ) {
			global $switched;
			if( $switch_success = switch_to_blog( $post_site ) )
				WPRSS_FTP_Utils::log_object( 'Switched blog.', $post_site, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
			else
				WPRSS_FTP_Utils::log_object( 'Could not switch to blog.', $post_site, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_NOTICE );
		}

		// Check if embedded content is allowed
		$allow_embedded_content = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'allow_embedded_content' );

		// If embedded content is allowed, remove KSES filtering
		if ( WPRSS_FTP_Utils::multiboolean( $allow_embedded_content ) === TRUE ) {
			kses_remove_filters();
			WPRSS_FTP_Utils::log( 'Embedded content allowed', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
		}

		// Insert the post
		$inserted_id = wp_insert_post( $post );
		
		// If embedded content is allowed, re-add KSES filtering
		if ( WPRSS_FTP_Utils::multiboolean( $allow_embedded_content ) === TRUE ) {
			kses_init_filters();
		}

		if ( !is_wp_error( $inserted_id ) ) {

			if ( is_object( $inserted_id ) ) {
				if ( isset( $inserted_id['ID'] ) ) {
					$inserted_id = $inserted_id['ID'];
				}
				elseif ( isset( $inserted_id->ID ) ) {
					$inserted_id = $inserted_id->ID;
				}
			}
			
			WPRSS_FTP_Utils::log_object( 'Post created', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

			if ( $user === NULL )
				WPRSS_FTP_Utils::log( 'Failed to determine a user for post #$inserted_id', $error_source, WPRSS_FTP_Utils::LOG_LEVEL_WARNING );

			// Update the post format
			set_post_format( $inserted_id, $post_format );

			if ( function_exists( 'wpml_update_translatable_content' ) ) {
				if ( $post_language === '' || $post_language === NULL ) {
					$post_language = ICL_LANGUAGE_CODE;
				}
				// Might be needed by WPML?
				$_POST['icl_post_language '] = $post_language;
				// Update the translation for the created post
				wpml_add_translatable_content( 'post_' . $post_type, $inserted_id, $post_language );
				wpml_update_translatable_content( 'post_' . $post_type, $inserted_id, $post_language );
				icl_cache_clear($post_type.'s_per_language');
				WPRSS_FTP_Utils::log_object( 'Post translated', $post_language, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			}


			/*==============================================
			 * 5) ADD THE POST META DATA
			 */
			WPRSS_FTP_Utils::log( 'Adding post meta', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			$thumbnail = '';
			$enclosure_image = '';
			if ( $enclosure = $item->get_enclosure() ) {
				$thumbnail = $enclosure->get_thumbnail();
				$enclosure_image = $enclosure->get_link();
				$enclosure_player = $enclosure->get_player();

				WPRSS_FTP_Utils::log( 'Item has enclosure', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			}

			// Prepare the post meta, and pass though the wprss_ftp_post_meta filter.
			// Note: Prepend '!' to ignore the 'wprss_ftp_' prefix
			$post_meta_data = apply_filters(
				'wprss_ftp_post_meta',
				array(
					'!wprss_item_permalink'		=>	$permalink,
					'feed_source'				=>	$source,
					'media:thumbnail'			=>	$thumbnail,
					'enclosure:thumbnail'		=>	$enclosure_image,
					'enclosure_link'			=>	$enclosure_image, // Included twice for code readablity
					'enclosure_player'			=>	$enclosure_player,
					'import_date'				=>	time(),
					'!wprss_item_date'			=>	$date_timestamp, // Required by core
					'!wprss_feed_id'			=>	$source,
				),
				$inserted_id,
				$source,
				$item
			);
			WPRSS_FTP_Utils::log_object( 'Post meta filters applied', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );

			// Insert the post meta
			WPRSS_FTP_Meta::get_instance()->add_meta( $inserted_id, $post_meta_data );
			WPRSS_FTP_Utils::log( 'Post meta added', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );



			/*==============================================
			 * 6) ADD THE TAXONOMY TERMS
			 *
			
			$all_post_terms = ( !is_array( $post_terms ) )? array() : $post_terms;

			// Check if the source auto creates taxonomy terms
			$auto_create_terms = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'post_auto_tax_terms' );
			// If yes ...
			if ( WPRSS_FTP_Utils::multiboolean( $auto_create_terms ) === TRUE ) {
				// Get the feed categories
				$categories = $item->get_categories();
				
				if ( is_array( $categories ) && count( $categories ) > 0 ) {
					// For each category in the feed item

					// Turn the categories into an array
					$new_categories = array();
					foreach( $categories as $cat ) {
						$new_categories[] = array(
							'name'	=>	$cat->get_label(),
							'args'	=>	array(),
						);
					}

					// Filter the categories
					$categories = apply_filters( 'wprss_auto_create_terms', $new_categories, $post_taxonomy, $source );

					foreach ( $categories as $category_obj ) {
						$category = $category_obj['name'];
						// Find the term that matches that category
						$cat_term = term_exists( $category , $post_taxonomy );

						// If the term does not exist create it
						if ( $cat_term === 0 || $cat_term === NULL ) {

							// check if parent field exists, and turn the slug into an id
							if ( isset( $category_obj['args']['parent'] ) ) {
								// Get the slug, and find the term by the slug
								$parent_slug = $category_obj['args']['parent'];
								$parent_term = get_term_by( 'slug', $parent_slug, $post_taxonomy, 'ARRAY_A' );
								// If term not found, removed the parent arg
								if ( $parent_term === FALSE ) {
									unset( $category_obj['args']['parent'] );
								}
								// Otherwise, change the slug to the id
								else $category_obj['args']['parent'] = intval( $parent_term['term_id'] );
							}

							// Insert the term
							$cat_term = wp_insert_term( $category, $post_taxonomy, $category_obj['args'] );
							delete_option($post_taxonomy."_children"); // clear the cache
						}
						$term_id = $cat_term['term_id'];

						$term_obj = get_term_by( 'id', $term_id, $post_taxonomy, 'ARRAY_A' );

						if ( $term_obj !== FALSE && $term_obj !== NULL ) {

							if ( !is_array($all_post_terms) ) {
								WPRSS_FTP_Utils::log_object( 'The $all_post_terms variable is not an array:', $all_post_terms, $error_source );
							} else {
								// Add it to the list of terms to add
								$all_post_terms[] = $term_obj['slug'];
							}

						}
					}
				}
			}

			$wp_categories_return = wp_set_object_terms( $inserted_id, $all_post_terms, $post_taxonomy, FALSE );
			if ( !is_array( $wp_categories_return ) ) {
				WPRSS_FTP_Utils::log_object( "Possible error while inserting taxonomy terms for post #$inserted_id:", $all_post_terms );
			}
			*/
			wprss_ftp_add_taxonomies_to_post( $inserted_id, $source, $item );
			WPRSS_FTP_Utils::log( 'Added taxonomies', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

			/*==============================================
			 * 8) CUSTOM FIELD MAPPING
			 */

			WPRSS_FTP_Utils::log( 'Mapping custom fields', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
			
			// Get the namespaces
			$cfm_namespaces = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'rss_namespaces' );
			$cfm_namespaces = ( $cfm_namespaces === '' )? array() : $cfm_namespaces;
			// Get the tags
			$cfm_tags = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'rss_tags' );
			$cfm_tags = ( $cfm_tags === '' )? array() : $cfm_tags;
			// Get the custom fields
			$cfm_fields = WPRSS_FTP_Meta::get_instance()->get_meta( $source, 'custom_fields' );
			$cfm_fields = ( $cfm_fields === '' )? array() : $cfm_fields;

			// For each custom field mapping
			for ( $i = 0; $i < count( $cfm_namespaces ); $i++ ) {
				// Get the URL of the namespace
				$namespace_url = WPRSS_FTP_Settings::get_namespace_url( $cfm_namespaces[$i] );
				// If the namespace url is NULL (namespace no longer exists in the settings), skip to next mapping
				if ( $namespace_url === NULL ) continue;

				// Match the syntax "tagname[attrib]" in the tag name
				preg_match('/([^\[]+) (\[ ([^\]]+) \])?/x', $cfm_tags[$i], $m);
				// If no matches, stop. Tag name is not correct. Possibly empty
				if ( !is_array($m) || count($m) < 2 ) continue;
				// Get the tag and attribute from the matches
				$tag_name = $m[1];
				$attrib = ( isset( $m[3] ) )? $m[3] : NULL;

				// Get the tag from the feed item
				$item_tags = $item->get_item_tags( $namespace_url, $tag_name );
				// Check if the tag exists. If not, skip to next mapping
				if ( !isset( $item_tags[0] ) ) continue;

				// Get the first tag found, and get its data contents
				$item_tag = $item_tags[0];
				$attribs = $item_tag['attribs'][''];
				// If not using an attribute, simply get the text data
				if ( $attrib === NULL ) {
					$data = $item_tag['data'];
				}
				// Otherwise, check if the attribute exists
				elseif ( isset( $attribs[ $attrib ] ) ) {
					$data = $attribs[ $attrib ];
				}
				// Otherwise do nothing
				else {
					continue;
				}

				// Put the data in the inserted post's meta, using the custom field as the meta key
				update_post_meta( $inserted_id, $cfm_fields[$i], $data );
				WPRSS_FTP_Utils::log_object( 'Post meta updated', $i+1 . '/' . count($cfm_namespaces), __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
			}
			
			WPRSS_FTP_Utils::log( 'Custom fields mapped', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

			$post = get_post( $inserted_id );
			if ( $post === NULL || $post === FALSE ) {
				$title = $item->get_title();
				WPRSS_FTP_Utils::log( "An error occurred while converting a feed item into a post \"$title\". Kindly report this error to support@wprssaggregator.com" );
			}
			else {
				WPRSS_FTP_Utils::log_object( 'Post created', $inserted_id, __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );
				do_action( 'wprss_ftp_converter_inserted_post', $inserted_id, $source );
				self::trim_words_for_post( $inserted_id, $source );
			}
		}
		else {
			WPRSS_FTP_Utils::log( 'Failed to insert post. $inserted_id = ' . $inserted_id, $error_source );
		}

		// If multisite and blog was switched, switch back to current blog
		if ( WPRSS_FTP_Utils::is_multisite() && $switch_success === TRUE ) {
			restore_current_blog();
			WPRSS_FTP_Utils::log( 'Blog restored', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_SYSTEM );
		}
		
		WPRSS_FTP_Utils::log( 'Conversion complete', __FUNCTION__, WPRSS_FTP_Utils::LOG_LEVEL_INFO );

		// Filter the return value
		$return = apply_filters( 'wprss_ftp_converter_return_post_'.$inserted_id, TRUE );
		// If the return is still TRUE, ensure that the post that was created was not deleted
		if ( $return === TRUE ) {
			$post = get_post( $inserted_id );
			$return = ( $post !== NULL && $post !== FALSE );
		}
		// Log return value if anything other than TRUE
		else {
			wprss_log( 'Recieved "'.$return.'" as a return value for post #'.$inserted_id, NULL, WPRSS_LOG_LEVEL_SYSTEM );
		}

		return $return;
	}
Beispiel #2
0
function motopressCEWPMLFix($post_id, $tmp_post_id, $post_type)
{
    if (defined('ICL_SITEPRESS_VERSION')) {
        global $wpdb, $sitepress;
        $content_type = 'post_' . $post_type;
        // fix #169
        if ($sitepress->is_translated_post_type($post_type) && is_file(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php')) {
            require_once WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php';
            if (!wpml_get_content_trid($content_type, $tmp_post_id)) {
                $content_type_pattern = 'post_%';
                $translation_id = $wpdb->get_var($wpdb->prepare("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE element_id=%d AND element_type LIKE %s", array($tmp_post_id, $content_type_pattern)));
                if ($translation_id) {
                    $wpdb->update($wpdb->prefix . 'icl_translations', array('element_type' => $content_type), array('translation_id' => $translation_id));
                }
            }
        }
        $language_code = $wpdb->get_var($wpdb->prepare('SELECT language_code FROM ' . $wpdb->prefix . 'icl_translations WHERE element_id = %d', $post_id));
        if (!is_null($language_code) && is_file(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php')) {
            require_once WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php';
            if (wpml_get_content_trid($content_type, $tmp_post_id)) {
                wpml_update_translatable_content($content_type, $tmp_post_id, $language_code);
            } else {
                wpml_add_translatable_content($content_type, $tmp_post_id, $language_code);
            }
        }
    }
}
function _my_create_product()
{
    if (is_home() && isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'create_product') || is_page(2) && isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'create_product') || is_page('compose') && isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'create_product')) {
        //    if (is_page('withproduct') && isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'create_product')){
        $time_start = microtime(true);
        //INIT
        $ratio = "";
        $ratioT = "";
        //var_dump($_POST);
        //die();
        // GET FILEPATH
        $fileName = $_POST['post_title'];
        $lang = $_POST['lang'];
        // tip:ZlychRK4D8Ftのノイズ //
        $imgUrl = 'http://api.typograffit.com/posts/getImage/';
        $typoAddress = $imgUrl . $fileName;
        // GET INPUT TEXT
        $baseInfoUrl = 'http://api.typograffit.com/rest_json/posts/getInfo/post_id:' . $fileName;
        $ch = curl_init();
        // init
        curl_setopt($ch, CURLOPT_URL, $baseInfoUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $c = curl_exec($ch);
        curl_close($ch);
        $obj = json_decode($c);
        $input_string = $obj->{'body'};
        if (mb_strlen($input_string) > 30) {
            $post_title_string = mb_substr($input_string, 0, 30) . '...';
        } else {
            $post_title_string = $input_string;
        }
        // IMAGICK
        $image = new Imagick($typoAddress);
        $image->paintTransparentImage("white", 0, 0);
        $image->despeckleImage();
        $hashImage = clone $image;
        $image->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
        $image->setImageResolution(150, 150);
        $hashWidth = $image->getImageWidth();
        $hashHeight = $image->getImageHeight();
        //RATIO
        if ($hashWidth >= $hashHeight * 3 / 4) {
            //横長
            $ratio = "oblong";
        } else {
            //縦長
            $ratio = "verlong";
        }
        if ($hashWidth >= $hashHeight * 5 / 6) {
            //横長
            $ratioT = "oblong";
        } else {
            //縦長
            $ratioT = "verlong";
        }
        //TSHIRT
        if (isset($_POST['cat_shirt'])) {
            $tentwelveImage = clone $image;
            $resizeFlag = 0;
            // RESIZE
            $w = 1800;
            $h = 2400;
            $w2 = 1500;
            $h2 = 1800;
            $boxWidth = 360;
            //(500-$hashWidth/2,200)を始点に[360px,480px]のボックスに収める
            $boxHeight = 480;
            // DB INIT
            //$post_title_string = 'TG-SHIRT';
            $att_post_title_string = $fileName . '-tshirt';
            $att_img_title_string = $fileName . '-enlarge_12_16';
            //COMPOSING SHIRT
            $shirtMockPath = '/home1/typograf/public_html/typograffit/wp-content/uploads/typo/tshirt-white.png';
            $imageShirt = new Imagick($shirtMockPath);
            if ($hashWidth < $w && $hashHeight < $h) {
                $resizeFlag = 1;
            }
            if ($resizeFlag == 1) {
                $image->resampleImage(150, 150, imagick::FILTER_CUBIC, 1);
                if ($ratio == "oblong") {
                    //横長
                    $image->resizeImage($w, 0, imagick::FILTER_CUBIC, 1);
                    $tentwelveImage->resizeImage($w2, 0, imagick::FILTER_CUBIC, 1);
                    //$image->thumbnailImage($w, $h, true);
                    $hashImage->resizeImage($boxWidth, 0, imagick::FILTER_CUBIC, 1);
                    $shirtHashWidth = $boxWidth;
                } else {
                    //縦長
                    $image->resizeImage(0, $h, imagick::FILTER_CUBIC, 1);
                    $tentwelveImage->resizeImage(0, $h2, imagick::FILTER_CUBIC, 1);
                    //$image->thumbnailImage($w, $h, true);
                    $hashImage->resizeImage(0, $boxHeight, imagick::FILTER_CUBIC, 1);
                    $shirtHashWidth = $hashImage->getImageWidth();
                }
            }
            // SAVE
            $saveDir = makeDirectory($fileName);
            // SAVE ENLRGE IMAGE
            //$saveEnlargePath = WP_CONTENT_URL.'/uploads/typo/'.$fileName.'-enlarge.png';
            //$saveEnlargePath = wp_upload_dir('typo').$fileName.'-enlarge.png';
            $saveEnlargePath = $saveDir . 'enlarge_12_16.png';
            $image->writeImage($saveEnlargePath);
            $image->destroy();
            $saveMinEnlargePath = $saveDir . 'enlarge_10_12.png';
            $tentwelveImage->writeImage($saveMinEnlargePath);
            $tentwelveImage->destroy();
            // SAVE COMPOSING IMAGE
            //$imageShirt = compositeImage($layer, Imagick::COMPOSITE_DEFAULT, $x, $y);
            $posX = 500 - $shirtHashWidth / 2;
            $posY = 200;
            //$saveCompPath = WP_CONTENT_URL.'/uploads/typo/'.$fileName.'-tshirt.png';
            $imageShirt->compositeImage($hashImage, Imagick::COMPOSITE_DEFAULT, $posX, $posY);
            $saveCompPath = $saveDir . 'tshirt.png';
            $imageShirt->writeImage($saveCompPath);
            $imageShirt->destroy();
            //insert PRODUCT
            if ($lang == 'ja') {
                $post_id = wp_insert_post(array('post_title' => $post_title_string, 'post_name' => $fileName, 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_type' => 'product'), true);
                $_POST['icl_post_language'] = $lang;
                wpml_update_translatable_content('post_product', $post_id, $lang);
                wp_set_post_terms($post_id, '3031', 'product_cat');
                //CHANGE VARIABLE
                wp_set_object_terms($post_id, 'variable', 'product_type');
                //my array for setting the attributes
                $avail_attributes = array('2XL-ja', 'XL-ja', 'L-ja', 'M-ja', 'S-ja', 'XS-ja');
            } else {
                $post_id = wp_insert_post(array('post_title' => $post_title_string, 'post_name' => $fileName, 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_type' => 'product'), true);
                wp_set_post_terms($post_id, '3030', 'product_cat');
                //2903 is TShirt.
                //CHANGE VARIABLE
                wp_set_object_terms($post_id, 'variable', 'product_type');
                //my array for setting the attributes
                $avail_attributes = array('2XL', 'XL', 'L', 'M', 'S', 'XS');
            }
            //Sets the attributes up to be used as variations but doesnt actually set them up as variations
            wp_set_object_terms($post_id, $avail_attributes, 'pa_size');
            $thedata = array('pa_size' => array('name' => 'pa_size', 'value' => '', 'position' => '0', 'is_visible' => '1', 'is_variation' => '1', 'is_taxonomy' => '1'));
            update_post_meta($post_id, '_product_attributes', $thedata);
            //Sets the Default Attributes
            if ($lang == 'ja') {
                $default_thedata = array('pa_size' => 'M-ja');
            } else {
                $default_thedata = array('pa_size' => 'M');
            }
            update_post_meta($post_id, '_default_attributes', $default_thedata);
            //add SKU etc
            update_post_meta($post_id, '_sku', $fileName);
            update_post_meta($post_id, '_price', '28.0');
            update_post_meta($post_id, '_regular_price', '28.0');
            update_post_meta($post_id, '_visibility', 'visible');
            update_post_meta($post_id, '_stock_status', 'instock');
            //insert VARIATION
            $var_shirt_post = array('post_title' => 'Variation #1 of ' . $fileName, 'post_name' => 'product-' . $post_id . '-variation-1', 'post_status' => 'publish', 'post_parent' => $post_id, 'post_type' => 'product_variation', 'guid' => home_url() . '/product_variation/product-' . $post_id . '-variation-1/');
            // Insert the post into the database
            $post_var_id = wp_insert_post($var_shirt_post);
            update_post_meta($post_var_id, '_price', '28.0');
            update_post_meta($post_var_id, '_regular_price', '28.0');
            update_post_meta($post_var_id, '_wcml_custom_prices_status', '1');
            update_post_meta($post_var_id, '_price_JPY', '2900');
            update_post_meta($post_var_id, '_regular_price_JPY', '2900');
            update_post_meta($post_var_id, 'attribute_pa_size', '');
            //insert Generated IMAGE
            $attachment_post = array('post_mime_type' => 'image/png', 'post_title' => $att_post_title_string, 'post_content' => '', 'post_status' => 'inherit');
            $attachment_id = wp_insert_attachment($attachment_post, $saveCompPath, $post_id);
            update_post_meta($post_id, '_thumbnail_id', $attachment_id);
            update_post_meta($post_var_id, '_thumbnail_id', $attachment_id);
            $update_postid_author = wp_update_post(array('ID' => $post_id, 'post_author' => '999'));
            $update_varid_author = wp_update_post(array('ID' => $post_var_id, 'post_author' => '999'));
        } elseif (isset($_POST['cat_tote'])) {
            //トートバッグ合成
            // RESIZE
            $w = 1500;
            $h = 1800;
            $boxWidth = 300;
            //(500-$hashWidth/2,500)を始点に[300px,360px]のボックスに収める
            $boxHeight = 360;
            // DB INIT
            //$post_title_string = 'TG-TOTE';
            $att_post_title_string = $fileName . '-tote';
            $att_img_title_string = $fileName . '-enlarge_10_12';
            //COMPOSING SHIRT
            $toteMockPath = '/home1/typograf/public_html/typograffit/wp-content/uploads/typo/tote-white.png';
            $imageTote = new Imagick($toteMockPath);
            if ($hashWidth < $w && $hashHeight < $h) {
                $resizeFlag = 1;
            }
            if ($resizeFlag == 1) {
                $image->resampleImage(150, 150, imagick::FILTER_CUBIC, 1);
                if ($ratioT == "oblong") {
                    //横長
                    $image->resizeImage($w, 0, imagick::FILTER_CUBIC, 1);
                    //$image->thumbnailImage($w, $h, true);
                    $hashImage->resizeImage($boxWidth, 0, imagick::FILTER_CUBIC, 1);
                    $toteHashWidth = $boxWidth;
                } else {
                    //縦長
                    $image->resizeImage(0, $h, imagick::FILTER_CUBIC, 1);
                    //$image->thumbnailImage($w, $h, true);
                    $hashImage->resizeImage(0, $boxHeight, imagick::FILTER_CUBIC, 1);
                    $toteHashWidth = $hashImage->getImageWidth();
                }
            }
            // SAVE
            $saveDir = makeDirectory($fileName);
            // SAVE ENLRGE IMAGE
            //$saveEnlargePath = WP_CONTENT_URL.'/uploads/typo/'.$fileName.'-enlarge.png';
            //$saveEnlargePath = wp_upload_dir('typo').$fileName.'-enlarge.png';
            $saveEnlargePath = $saveDir . 'enlarge_10_12.png';
            $image->writeImage($saveEnlargePath);
            $image->destroy();
            // SAVE COMPOSING IMAGE
            //$imageShirt = compositeImage($layer, Imagick::COMPOSITE_DEFAULT, $x, $y);
            $posX = 500 - $toteHashWidth / 2 - 15;
            $posY = 500;
            //$saveCompPath = WP_CONTENT_URL.'/uploads/typo/'.$fileName.'-tshirt.png';
            $imageTote->compositeImage($hashImage, Imagick::COMPOSITE_DEFAULT, $posX, $posY);
            $saveCompPath = $saveDir . 'tote.png';
            $imageTote->writeImage($saveCompPath);
            $imageTote->destroy();
            //insert PRODUCT
            if ($lang == 'ja') {
                $post_id = wp_insert_post(array('post_title' => $post_title_string, 'post_name' => $fileName, 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_type' => 'product'), true);
                $_POST['icl_post_language'] = $lang;
                wpml_update_translatable_content('post_product', $post_id, $lang);
                wp_set_post_terms($post_id, '3033', 'product_cat');
            } else {
                $post_id = wp_insert_post(array('post_title' => $post_title_string, 'post_name' => $fileName, 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_type' => 'product'), true);
                wp_set_post_terms($post_id, '3032', 'product_cat');
            }
            //2904 is Totes.
            //add SKU etc
            update_post_meta($post_id, '_sku', $fileName);
            update_post_meta($post_id, '_price', '22.0');
            update_post_meta($post_id, '_regular_price', '22.0');
            update_post_meta($post_id, '_wcml_custom_prices_status', '1');
            update_post_meta($post_id, '_price_JPY', '2500');
            update_post_meta($post_id, '_regular_price_JPY', '2500');
            update_post_meta($post_id, '_visibility', 'visible');
            update_post_meta($post_id, '_stock_status', 'instock');
            //insert Generated IMAGE
            $attachment_post = array('post_mime_type' => 'image/png', 'post_title' => $att_post_title_string, 'post_content' => '', 'post_status' => 'inherit');
            $attachment_id = wp_insert_attachment($attachment_post, $saveCompPath, $post_id);
            update_post_meta($post_id, '_thumbnail_id', $attachment_id);
            //insert Enlarged IMAGE
            /*
                         $attachment_enlarge_post = array(
                            'post_mime_type' => 'image/png',
                            'post_title' => $att_img_title_string,
                            'post_content' => '',
                            'post_status' => 'inherit',
                        );
                        $typogenerated_id = wp_insert_attachment( $attachment_enlarge_post, $saveEnlargePath, $post_id );
                        update_post_meta( $post_id, '_typogenerated_id' , $typogenerated_id);
            */
            $update_author = wp_update_post(array('ID' => $post_id, 'post_author' => '998'));
        }
        /*
                elseif(isset($_POST['cat_mug'])){
                    //マグカップ合成
        
                }
        */
        /*
        		 $time_end = microtime(true);
        		 $time = $time_end - $time_start;
            		error_log($time."Seconds");
        */
        //データの挿入に成功していたら移動
        if (!is_wp_error($post_id)) {
            //カスタムフィールドurl_rel(参考URL)を追加
            update_post_meta($post_id, 'url_ref', $_POST['url']);
            //ページを移動
            header('Location: ' . get_permalink($post_id));
            die;
        }
    }
}