/** * Update attachment file path based on attachment ID. * * Used to update the file path of the attachment, which uses post meta name * '_wp_attached_file' to store the path of the attachment. * * @since 2.1.0 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID. * * @param int $attachment_id Attachment ID * @param string $file File path for the attachment * @return bool False on failure, true on success. */ function update_attached_file($attachment_id, $file) { if (!get_post($attachment_id)) { return false; } $file = apply_filters('update_attached_file', $file, $attachment_id); $file = _wp_relative_upload_path($file); return update_post_meta($attachment_id, '_wp_attached_file', $file); }
function insert_attachment($file, $id) { $dirs = wp_upload_dir(); $filetype = wp_check_filetype($file); $attachment = array('guid' => $dirs['baseurl'] . '/' . _wp_relative_upload_path($file), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $file, $id); //$attach_data=wp_generate_attachment_metadata($attach_id,$file); //wp_update_attachment_metadata($attach_id,$attach_data); return $attach_id; }
function hack_wp_generate_attachment_metadata($metadata, $attachment_id) { if (!isset($metadata['file'])) { return $metadata; } $attachment = get_post($attachment_id); $uploadPath = wp_upload_dir(); $file = path_join($uploadPath['basedir'], $metadata['file']); $metadata = array(); if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // make thumbnails and other intermediate sizes global $_wp_additional_image_sizes; foreach (get_intermediate_image_sizes() as $s) { $sizes[$s] = array('width' => '', 'height' => '', 'crop' => FALSE); if (isset($_wp_additional_image_sizes[$s]['width'])) { $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']); } else { $sizes[$s]['width'] = get_option("{$s}_size_w"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['height'])) { $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']); } else { $sizes[$s]['height'] = get_option("{$s}_size_h"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['crop'])) { $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']); } else { $sizes[$s]['crop'] = get_option("{$s}_crop"); } // For default sizes set in options } foreach ($sizes as $size => $size_data) { $resized = hack_image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop'], $size); if ($resized) { $metadata['sizes'][$size] = $resized; } } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } return $metadata; }
/** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * @return mixed Metadata for attachment. */ function wp_generate_attachment_metadata( $attachment_id, $file ) { $attachment = get_post( $attachment_id ); $metadata = array(); if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) { $imagesize = getimagesize( $file ); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // make thumbnails and other intermediate sizes global $_wp_additional_image_sizes; foreach ( get_intermediate_image_sizes() as $s ) { $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false ); if ( isset( $_wp_additional_image_sizes[$s]['width'] ) ) $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes else $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options if ( isset( $_wp_additional_image_sizes[$s]['height'] ) ) $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes else $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) ) $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes else $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options } $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes ); if ( $sizes ) { $editor = wp_get_image_editor( $file ); if ( ! is_wp_error( $editor ) ) $metadata['sizes'] = $editor->multi_resize( $sizes ); } else { $metadata['sizes'] = array(); } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata( $file ); if ( $image_meta ) $metadata['image_meta'] = $image_meta; } return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id ); }
function get_media_item($media_id) { $media_item = get_post($media_id); if (!$media_item || is_wp_error($media_item)) { return new WP_Error('unknown_media', 'Unknown Media', 404); } $response = array('id' => strval($media_item->ID), 'date' => (string) $this->format_date($media_item->post_date_gmt, $media_item->post_date), 'parent' => $media_item->post_parent, 'link' => wp_get_attachment_url($media_item->ID), 'title' => $media_item->post_title, 'caption' => $media_item->post_excerpt, 'description' => $media_item->post_content, 'metadata' => wp_get_attachment_metadata($media_item->ID)); if (defined('IS_WPCOM') && IS_WPCOM && is_array($response['metadata']) && !empty($response['metadata']['file'])) { remove_filter('_wp_relative_upload_path', 'wpcom_wp_relative_upload_path', 10); $response['metadata']['file'] = _wp_relative_upload_path($response['metadata']['file']); add_filter('_wp_relative_upload_path', 'wpcom_wp_relative_upload_path', 10, 2); } $response['meta'] = (object) array('links' => (object) array('self' => (string) $this->get_media_link($this->api->get_blog_id_for_output(), $media_id), 'help' => (string) $this->get_media_link($this->api->get_blog_id_for_output(), $media_id, 'help'), 'site' => (string) $this->get_site_link($this->api->get_blog_id_for_output()))); return (object) $response; }
if ($value['size'] > $max_attach_size) { wp_die(sprintf(__("File size exceeds %dMB. Most email providers will reject emails with attachments larger than %dMB. Please decrease the file size and try again.", 'visual-form-builder'), $size), '', array('back_link' => true)); } // Options array for the wp_handle_upload function. 'test_form' => false $upload_overrides = array('test_form' => false); // We need to include the file that runs the wp_handle_upload function require_once ABSPATH . 'wp-admin/includes/file.php'; // Handle the upload using WP's wp_handle_upload function. Takes the posted file and an options array $uploaded_file = wp_handle_upload($value, $upload_overrides); // If the wp_handle_upload call returned a local path for the image if (isset($uploaded_file['file'])) { // Retrieve the file type from the file name. Returns an array with extension and mime type $wp_filetype = wp_check_filetype(basename($uploaded_file['file']), null); // Return the current upload directory location $wp_upload_dir = wp_upload_dir(); $media_upload = array('guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path($uploaded_file['file']), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($uploaded_file['file'])), 'post_content' => '', 'post_status' => 'inherit'); // Insert attachment into Media Library and get attachment ID $attach_id = wp_insert_attachment($media_upload, $uploaded_file['file']); // Include the file that runs wp_generate_attachment_metadata() require_once ABSPATH . 'wp-admin/includes/image.php'; // Setup attachment metadata $attach_data = wp_generate_attachment_metadata($attach_id, $uploaded_file['file']); // Update the attachment metadata wp_update_attachment_metadata($attach_id, $attach_data); $attachments['vfb-' . $field->field_id] = $uploaded_file['file']; $data[] = array('id' => $field->field_id, 'slug' => $field->field_key, 'name' => $field->field_name, 'type' => $field->field_type, 'options' => $field->field_options, 'parent_id' => $field->field_parent, 'value' => $uploaded_file['url']); $body .= sprintf('<tr> <td><strong>%1$s: </strong></td> <td><a href="%2$s">%2$s</a></td> </tr>' . "\n", stripslashes($field->field_name), $uploaded_file['url']); }
/** * Add new entity element from anywhere */ function ajax_wpshop_add_entity() { global $wpdb; check_ajax_referer('wpshop_add_new_entity_ajax_nonce', 'wpshop_ajax_nonce'); $attributes = array(); /** Get the attribute to create */ $attribute_to_reload = null; if (!empty($_POST['attribute']['new_value_creation']) && is_array($_POST['attribute']['new_value_creation'])) { foreach ($_POST['attribute']['new_value_creation'] as $attribute_code => $value) { $query = $wpdb->prepare('SELECT * FROM ' . WPSHOP_DBT_ATTRIBUTE . ' WHERE code = %s', $attribute_code); $attribute_def = $wpdb->get_row($query); if ($value != "") { if ($attribute_def->data_type_to_use == 'internal') { $attribute_default_value = unserialize($attribute_def->default_value); if ($attribute_default_value['default_value'] == WPSHOP_NEWTYPE_IDENTIFIER_CUSTOMERS) { $user_id = wp_create_user(sanitize_user($value), wp_generate_password(12, false)); $query = $wpdb->prepare("SELECT ID FROM " . $wpdb->posts . " WHERE post_type = %s AND post_author = %d", WPSHOP_NEWTYPE_IDENTIFIER_CUSTOMERS, $user_id); $attribute_option_id = $wpdb->get_var($query); } else { $entity_args = array('post_type' => $attribute_default_value['default_value'], 'post_title' => $value, 'post_author' => function_exists('is_user_logged_in') && is_user_logged_in() ? get_current_user_id() : 'NaN', 'comment_status' => 'closed'); $attribute_option_id = wp_insert_post($entity_args); } } else { $wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS, array('status' => 'valid', 'creation_date' => current_time('mysql', 0), 'position' => 1, 'attribute_id' => $attribute_def->id, 'value' => $value, 'label' => $value)); $attribute_option_id = $wpdb->insert_id; } foreach ($_POST['attribute'] as $attribute => $val) { foreach ($val as $k => $v) { if ($k == $attribute_code) { $_POST['attribute'][$attribute][$k] = $attribute_option_id; } } } } } } /** Store send attribute into a new array for save purpose */ if (is_array($_POST['attribute'])) { foreach ($_POST['attribute'] as $attribute_type => $attribute) { foreach ($attribute as $attribute_code => $attribute_value) { if (!isset($attributes[$attribute_code])) { $attributes[$attribute_code] = $attribute_value; } } } } /** Save the new entity into database */ $result = wpshop_entities::create_new_entity($_POST['entity_type'], $_POST['wp_fields']['post_title'], '', $attributes, array('attribute_set_id' => $_POST['attribute_set_id'])); $new_entity_id = $result[1]; if (!empty($new_entity_id)) { /** Save address for current entity */ if (!empty($_POST['type_of_form']) && !empty($_POST['attribute'][$_POST['type_of_form']])) { global $wpshop_account; $result = wps_address::wps_address($_POST['type_of_form']); update_post_meta($new_entity_id, '_wpshop_attached_address', $result['current_id']); } /** Make price calculation if entity is a product */ if ($_POST['entity_type'] == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT) { $wpshop_prices_attribute = unserialize(WPSHOP_ATTRIBUTE_PRICES); $calculate_price = false; foreach ($wpshop_prices_attribute as $attribute_price_code) { if (array_key_exists($attribute_price_code, $attributes)) { $calculate_price = true; } } if ($calculate_price) { wpshop_products::calculate_price($new_entity_id); } } /** Add picture if a file has been send */ if (!empty($_FILES)) { $wp_upload_dir = wp_upload_dir(); $final_dir = $wp_upload_dir['path'] . '/'; if (!is_dir($final_dir)) { mkdir($final_dir, 0755, true); } foreach ($_FILES as $file) { $tmp_name = $file['tmp_name']['post_thumbnail']; $name = $file['name']['post_thumbnail']; $filename = $final_dir . $name; @move_uploaded_file($tmp_name, $filename); $wp_filetype = wp_check_filetype(basename($filename), null); $attachment = array('guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path($filename), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $filename, $new_entity_id); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); add_post_meta($new_entity_id, '_thumbnail_id', $attach_id, true); } } echo json_encode(array(true, __('Element has been saved', 'wpshop'), $attribute_to_reload, $new_entity_id)); } else { echo json_encode(array(false, __('An error occured while adding your element', 'wpshop'))); } die; }
/** * Update attachment file path based on attachment ID. * * Used to update the file path of the attachment, which uses post meta name * '_wp_attached_file' to store the path of the attachment. * * @since 2.1.0 * * @param int $attachment_id Attachment ID. * @param string $file File path for the attachment. * @return bool True on success, false on failure. */ function update_attached_file($attachment_id, $file) { if (!get_post($attachment_id)) { return false; } /** * Filter the path to the attached file to update. * * @since 2.1.0 * * @param string $file Path to the attached file to update. * @param int $attachment_id Attachment ID. */ $file = apply_filters('update_attached_file', $file, $attachment_id); if ($file = _wp_relative_upload_path($file)) { return update_post_meta($attachment_id, '_wp_attached_file', $file); } else { return delete_post_meta($attachment_id, '_wp_attached_file'); } }
/** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * @return mixed Metadata for attachment. */ function wp_generate_attachment_metadata($attachment_id, $file) { $attachment = get_post($attachment_id); $metadata = array(); $support = false; if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // make thumbnails and other intermediate sizes global $_wp_additional_image_sizes; $sizes = array(); foreach (get_intermediate_image_sizes() as $s) { $sizes[$s] = array('width' => '', 'height' => '', 'crop' => false); if (isset($_wp_additional_image_sizes[$s]['width'])) { $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']); } else { $sizes[$s]['width'] = get_option("{$s}_size_w"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['height'])) { $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']); } else { $sizes[$s]['height'] = get_option("{$s}_size_h"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['crop'])) { $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']); } else { $sizes[$s]['crop'] = get_option("{$s}_crop"); } // For default sizes set in options } $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes); if ($sizes) { $editor = wp_get_image_editor($file); if (!is_wp_error($editor)) { $metadata['sizes'] = $editor->multi_resize($sizes); } } else { $metadata['sizes'] = array(); } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } elseif (preg_match('#^video/#', get_post_mime_type($attachment))) { $metadata = wp_read_video_metadata($file); $support = current_theme_supports('post-thumbnails', 'attachment:video') && post_type_supports('attachment:video', 'thumbnail'); } elseif (preg_match('#^audio/#', get_post_mime_type($attachment))) { $metadata = wp_read_audio_metadata($file); $support = current_theme_supports('post-thumbnails', 'attachment:audio') && post_type_supports('attachment:audio', 'thumbnail'); } if ($support && !empty($metadata['image']['data'])) { $ext = '.jpg'; switch ($metadata['image']['mime']) { case 'image/gif': $ext = '.gif'; break; case 'image/png': $ext = '.png'; break; } $basename = str_replace('.', '-', basename($file)) . '-image' . $ext; $uploaded = wp_upload_bits($basename, '', $metadata['image']['data']); if (false === $uploaded['error']) { $attachment = array('post_mime_type' => $metadata['image']['mime'], 'post_type' => 'attachment', 'post_content' => ''); $sub_attachment_id = wp_insert_attachment($attachment, $uploaded['file']); $attach_data = wp_generate_attachment_metadata($sub_attachment_id, $uploaded['file']); wp_update_attachment_metadata($sub_attachment_id, $attach_data); update_post_meta($attachment_id, '_thumbnail_id', $sub_attachment_id); } } // remove the blob of binary data from the array unset($metadata['image']['data']); return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id); }
/** * Perform import operation * @param string $xml XML string to import * @param callback[optional] $logger Method where progress messages are submmitted * @return PMXI_Import_Record * @chainable */ public function process($xml, $logger = NULL, $chunk = false, $is_cron = false, $xpath_prefix = '') { add_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html')); kses_init(); // do not perform special filtering for imported content $cxpath = $xpath_prefix . $this->xpath; $this->options += PMXI_Plugin::get_default_import_options(); // make sure all options are defined $avoid_pingbacks = PMXI_Plugin::getInstance()->getOption('pingbacks'); if ($avoid_pingbacks and !defined('WP_IMPORTING')) { define('WP_IMPORTING', true); } $postRecord = new PMXI_Post_Record(); $tmp_files = array(); // compose records to import $records = array(); $is_import_complete = false; try { $chunk == 1 and $logger and call_user_func($logger, __('Composing titles...', 'pmxi_plugin')); $titles = XmlImportParser::factory($xml, $cxpath, $this->template['title'], $file)->parse($records); $tmp_files[] = $file; $chunk == 1 and $logger and call_user_func($logger, __('Composing excerpts...', 'pmxi_plugin')); $post_excerpt = array(); if (!empty($this->options['post_excerpt'])) { $post_excerpt = XmlImportParser::factory($xml, $cxpath, $this->options['post_excerpt'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_excerpt = array_fill(0, count($titles), ''); } if ("xpath" == $this->options['status']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing statuses...', 'pmxi_plugin')); $post_status = array(); if (!empty($this->options['status_xpath'])) { $post_status = XmlImportParser::factory($xml, $cxpath, $this->options['status_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_status = array_fill(0, count($titles), ''); } } $chunk == 1 and $logger and call_user_func($logger, __('Composing authors...', 'pmxi_plugin')); $post_author = array(); $current_user = wp_get_current_user(); if (!empty($this->options['author'])) { $post_author = XmlImportParser::factory($xml, $cxpath, $this->options['author'], $file)->parse($records); $tmp_files[] = $file; foreach ($post_author as $key => $author) { $user = get_user_by('login', $author) or $user = get_user_by('slug', $author) or $user = get_user_by('email', $author) or ctype_digit($author) and $user = get_user_by('id', $author); $post_author[$key] = !empty($user) ? $user->ID : $current_user->ID; } } else { count($titles) and $post_author = array_fill(0, count($titles), $current_user->ID); } $chunk == 1 and $logger and call_user_func($logger, __('Composing slugs...', 'pmxi_plugin')); $post_slug = array(); if (!empty($this->options['post_slug'])) { $post_slug = XmlImportParser::factory($xml, $cxpath, $this->options['post_slug'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_slug = array_fill(0, count($titles), ''); } $chunk == 1 and $logger and call_user_func($logger, __('Composing contents...', 'pmxi_plugin')); $contents = XmlImportParser::factory((!empty($this->template['is_keep_linebreaks']) and intval($this->template['is_keep_linebreaks'])) ? $xml : preg_replace('%\\r\\n?|\\n%', ' ', $xml), $cxpath, $this->template['content'], $file)->parse($records); $tmp_files[] = $file; $chunk == 1 and $logger and call_user_func($logger, __('Composing dates...', 'pmxi_plugin')); if ('specific' == $this->options['date_type']) { $dates = XmlImportParser::factory($xml, $cxpath, $this->options['date'], $file)->parse($records); $tmp_files[] = $file; $warned = array(); // used to prevent the same notice displaying several times foreach ($dates as $i => $d) { if ($d == 'now') { $d = current_time('mysql'); } // Replace 'now' with the WordPress local time to account for timezone offsets (WordPress references its local time during publishing rather than the server’s time so it should use that) $time = strtotime($d); if (FALSE === $time) { in_array($d, $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'pmxi_plugin'), $warned[] = $d)); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $time = time(); } $dates[$i] = date('Y-m-d H:i:s', $time); } } else { $dates_start = XmlImportParser::factory($xml, $cxpath, $this->options['date_start'], $file)->parse($records); $tmp_files[] = $file; $dates_end = XmlImportParser::factory($xml, $cxpath, $this->options['date_end'], $file)->parse($records); $tmp_files[] = $file; $warned = array(); // used to prevent the same notice displaying several times foreach ($dates_start as $i => $d) { $time_start = strtotime($dates_start[$i]); if (FALSE === $time_start) { in_array($dates_start[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'pmxi_plugin'), $warned[] = $dates_start[$i])); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $time_start = time(); } $time_end = strtotime($dates_end[$i]); if (FALSE === $time_end) { in_array($dates_end[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'pmxi_plugin'), $warned[] = $dates_end[$i])); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $time_end = time(); } $dates[$i] = date('Y-m-d H:i:s', mt_rand($time_start, $time_end)); } } $tags = array(); if ($this->options['tags']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing tags...', 'pmxi_plugin')); $tags_raw = XmlImportParser::factory($xml, $cxpath, $this->options['tags'], $file)->parse($records); $tmp_files[] = $file; foreach ($tags_raw as $i => $t_raw) { $tags[$i] = ''; if ('' != $t_raw) { $tags[$i] = implode(', ', str_getcsv($t_raw, $this->options['tags_delim'])); } } } else { count($titles) and $tags = array_fill(0, count($titles), ''); } // [posts categories] require_once ABSPATH . 'wp-admin/includes/taxonomy.php'; if ('post' == $this->options['type']) { $cats = array(); $categories_hierarchy = !empty($this->options['categories']) ? json_decode($this->options['categories']) : array(); if (!empty($categories_hierarchy) and is_array($categories_hierarchy)) { $chunk == 1 and $logger and call_user_func($logger, __('Composing categories...', 'pmxi_plugin')); $categories = array(); foreach ($categories_hierarchy as $k => $category) { if ("" == $category->xpath) { continue; } $cats_raw = XmlImportParser::factory($xml, $cxpath, str_replace('\'', '"', $category->xpath), $file)->parse($records); $tmp_files[] = $file; $warned = array(); // used to prevent the same notice displaying several times foreach ($cats_raw as $i => $c_raw) { if (empty($categories_hierarchy[$k]->cat_ids[$i])) { $categories_hierarchy[$k]->cat_ids[$i] = array(); } if (empty($cats[$i])) { $cats[$i] = array(); } $count_cats = count($cats[$i]); $delimeted_categories = explode($this->options['categories_delim'], $c_raw); if ('' != $c_raw) { foreach (explode($this->options['categories_delim'], $c_raw) as $j => $cc) { if ('' != $cc) { $cat = get_term_by('name', trim($cc), 'category') or $cat = get_term_by('slug', trim($cc), 'category') or ctype_digit($cc) and $cat = get_term_by('id', trim($cc), 'category'); if (!empty($category->parent_id)) { foreach ($categories_hierarchy as $key => $value) { if ($value->item_id == $category->parent_id and !empty($value->cat_ids[$i])) { foreach ($value->cat_ids[$i] as $parent) { if (!$j or !$this->options['categories_auto_nested']) { $filtered_cats = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => is_array($parent) ? $parent['name'] : $parent, 'assign' => $category->assign)), $category); foreach ($filtered_cats as $filtered_cat) { $cats[$i][] = $filtered_cat; } } elseif ($this->options['categories_auto_nested']) { $filtered_cats = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => !empty($delimeted_categories[$j - 1]) ? apply_filters('pmxi_parent_category', trim($delimeted_categories[$j - 1]), $category) : false, 'assign' => $category->assign)), $category); foreach ($filtered_cats as $filtered_cat) { $cats[$i][] = $filtered_cat; } } } } } } else { if (!$j or !$this->options['categories_auto_nested']) { $filtered_cats = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => false, 'assign' => $category->assign)), $category); foreach ($filtered_cats as $filtered_cat) { $cats[$i][] = $filtered_cat; } } elseif ($this->options['categories_auto_nested']) { $filtered_cats = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => !empty($delimeted_categories[$j - 1]) ? apply_filters('pmxi_parent_category', trim($delimeted_categories[$j - 1]), $category) : false, 'assign' => $category->assign)), $category); foreach ($filtered_cats as $filtered_cat) { $cats[$i][] = $filtered_cat; } } } } } } if ($count_cats < count($cats[$i])) { $categories_hierarchy[$k]->cat_ids[$i][] = apply_filters('pmxi_single_category', $cats[$i][count($cats[$i]) - 1], $categories_hierarchy[$k]); } } } } else { count($titles) and $cats = array_fill(0, count($titles), ''); } } // [/posts categories] // [custom taxonomies] $taxonomies = array(); $taxonomies_param = $this->options['type'] . '_taxonomies'; if ('page' == $this->options['type']) { $taxonomies_object_type = 'page'; } elseif ('' != $this->options['custom_type']) { $taxonomies_object_type = $this->options['custom_type']; } else { $taxonomies_object_type = 'post'; } if (!empty($this->options[$taxonomies_param]) and is_array($this->options[$taxonomies_param])) { foreach ($this->options[$taxonomies_param] as $tx_name => $tx_template) { if ('' != $tx_template) { $tx = get_taxonomy($tx_name); $taxonomies[$tx_name] = array(); if (!empty($tx->object_type) and in_array($taxonomies_object_type, $tx->object_type)) { $chunk == 1 and $logger and call_user_func($logger, sprintf(__('Composing terms for `%s` taxonomy...', 'pmxi_plugin'), $tx->labels->name)); $txes = array(); $taxonomies_hierarchy = json_decode($tx_template); foreach ($taxonomies_hierarchy as $k => $taxonomy) { if ("" == $taxonomy->xpath) { continue; } $txes_raw = XmlImportParser::factory($xml, $cxpath, str_replace('\'', '"', $taxonomy->xpath), $file)->parse($records); $tmp_files[] = $file; $warned = array(); foreach ($txes_raw as $i => $tx_raw) { if (empty($taxonomies_hierarchy[$k]->txn_names[$i])) { $taxonomies_hierarchy[$k]->txn_names[$i] = array(); } if (empty($taxonomies[$tx_name][$i])) { $taxonomies[$tx_name][$i] = array(); } $count_cats = count($taxonomies[$tx_name][$i]); $delimeted_taxonomies = explode(!empty($taxonomy->delim) ? $taxonomy->delim : ',', $tx_raw); if ('' != $tx_raw) { foreach (explode(!empty($taxonomy->delim) ? $taxonomy->delim : ',', $tx_raw) as $j => $cc) { if ('' != $cc) { $cat = get_term_by('name', trim($cc), $tx_name) or $cat = get_term_by('slug', trim($cc), $tx_name) or ctype_digit($cc) and $cat = get_term_by('id', $cc, $tx_name); if (!empty($taxonomy->parent_id)) { foreach ($taxonomies_hierarchy as $key => $value) { if ($value->item_id == $taxonomy->parent_id and !empty($value->txn_names[$i])) { foreach ($value->txn_names[$i] as $parent) { if (!$j or !$taxonomy->auto_nested) { $filtered_txs = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => $parent, 'assign' => $taxonomy->assign)), $taxonomy); foreach ($filtered_txs as $filtered_tx) { $taxonomies[$tx_name][$i][] = $filtered_tx; } } elseif ($taxonomy->auto_nested) { $filtered_txs = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => !empty($delimeted_taxonomies[$j - 1]) ? apply_filters('pmxi_parent_category', trim($delimeted_taxonomies[$j - 1]), $taxonomy) : false, 'assign' => $taxonomy->assign)), $taxonomy); foreach ($filtered_txs as $filtered_tx) { $taxonomies[$tx_name][$i][] = $filtered_tx; } } } } } } else { if (!$j or !$taxonomy->auto_nested) { $filtered_txs = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => false, 'assign' => $taxonomy->assign)), $taxonomy); foreach ($filtered_txs as $filtered_tx) { $taxonomies[$tx_name][$i][] = $filtered_tx; } } elseif ($taxonomy->auto_nested) { $filtered_txs = apply_filters('pmxi_single_category', array(array('name' => trim($cc), 'parent' => !empty($delimeted_taxonomies[$j - 1]) ? apply_filters('pmxi_parent_category', trim($delimeted_taxonomies[$j - 1]), $taxonomy) : false, 'assign' => $taxonomy->assign)), $taxonomy); foreach ($filtered_txs as $filtered_tx) { $taxonomies[$tx_name][$i][] = $filtered_tx; } } } } } } if ($count_cats < count($taxonomies[$tx_name][$i])) { $taxonomies_hierarchy[$k]->txn_names[$i][] = apply_filters('pmxi_single_category', $taxonomies[$tx_name][$i][count($taxonomies[$tx_name][$i]) - 1], $taxonomies_hierarchy[$k]); } } } } } } } // [/custom taxonomies] // serialized featured images if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $uploads['error']); $logger and call_user_func($logger, __('<b>WARNING</b>: No featured images will be created', 'pmxi_plugin')); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for featured images...', 'pmxi_plugin')); $featured_images = array(); if ($this->options['featured_image']) { $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options['featured_image'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $featured_images = array_fill(0, count($titles), ''); } } // serialized images meta data if ($this->options['set_image_meta_data']) { $uploads = wp_upload_dir(); // serialized images meta titles $chunk == 1 and $logger and call_user_func($logger, __('Composing image meta data (titles)...', 'pmxi_plugin')); $image_meta_titles = array(); if ($this->options['image_meta_title']) { $image_meta_titles = XmlImportParser::factory($xml, $cxpath, $this->options['image_meta_title'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_titles = array_fill(0, count($titles), ''); } // serialized images meta captions $chunk == 1 and $logger and call_user_func($logger, __('Composing image meta data (captions)...', 'pmxi_plugin')); $image_meta_captions = array(); if ($this->options['image_meta_caption']) { $image_meta_captions = XmlImportParser::factory($xml, $cxpath, $this->options['image_meta_caption'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_captions = array_fill(0, count($titles), ''); } // serialized images meta alt text $chunk == 1 and $logger and call_user_func($logger, __('Composing image meta data (alt text)...', 'pmxi_plugin')); $image_meta_alts = array(); if ($this->options['image_meta_alt']) { $image_meta_alts = XmlImportParser::factory($xml, $cxpath, $this->options['image_meta_alt'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_alts = array_fill(0, count($titles), ''); } // serialized images meta description $chunk == 1 and $logger and call_user_func($logger, __('Composing image meta data (description)...', 'pmxi_plugin')); $image_meta_descriptions = array(); if ($this->options['image_meta_description']) { $image_meta_descriptions = XmlImportParser::factory($xml, $cxpath, $this->options['image_meta_description'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_descriptions = array_fill(0, count($titles), ''); } } // Composing images suffix $chunk == 1 and $this->options['auto_rename_images'] and $logger and call_user_func($logger, __('Composing images suffix...', 'pmxi_plugin')); $auto_rename_images = array(); if ($this->options['auto_rename_images'] and !empty($this->options['auto_rename_images_suffix'])) { $auto_rename_images = XmlImportParser::factory($xml, $cxpath, $this->options['auto_rename_images_suffix'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $auto_rename_images = array_fill(0, count($titles), ''); } // serialized attachments if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $uploads['error']); $logger and call_user_func($logger, __('<b>WARNING</b>: No attachments will be created', 'pmxi_plugin')); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session['pmxi_import']['warnings']; } else { $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for attachments files...', 'pmxi_plugin')); $attachments = array(); if ($this->options['attachments']) { // Detect if attachments is separated by comma $atchs = explode(',', $this->options['attachments']); if (!empty($atchs)) { $parse_multiple = true; foreach ($atchs as $atch) { if (!preg_match("/{.*}/", trim($atch))) { $parse_multiple = false; } } if ($parse_multiple) { foreach ($atchs as $atch) { $posts_attachments = XmlImportParser::factory($xml, $cxpath, trim($atch), $file)->parse($records); $tmp_files[] = $file; foreach ($posts_attachments as $i => $val) { $attachments[$i][] = $val; } } } else { $attachments = XmlImportParser::factory($xml, $cxpath, $this->options['attachments'], $file)->parse($records); $tmp_files[] = $file; } } } else { count($titles) and $attachments = array_fill(0, count($titles), ''); } } $chunk == 1 and $logger and call_user_func($logger, __('Composing unique keys...', 'pmxi_plugin')); $unique_keys = XmlImportParser::factory($xml, $cxpath, $this->options['unique_key'], $file)->parse($records); $tmp_files[] = $file; $chunk == 1 and $logger and call_user_func($logger, __('Processing posts...', 'pmxi_plugin')); if ('post' == $this->options['type'] and '' != $this->options['custom_type']) { $post_type = ($this->options['custom_type'] == 'product' and class_exists('PMWI_Plugin')) ? $this->options['custom_type'] : ($this->options['custom_type'] == 'page' ? 'page' : 'post'); } else { $post_type = $this->options['type']; } $addons = array(); $addons_data = array(); // data parsing for WP All Import add-ons $parsingData = array('import' => $this, 'count' => count($titles), 'xml' => $xml, 'logger' => $logger, 'chunk' => $chunk, 'xpath_prefix' => $xpath_prefix); foreach (PMXI_Admin_Addons::get_active_addons() as $class) { $model_class = str_replace("_Plugin", "_Import_Record", $class); if (class_exists($model_class)) { $addons[$class] = new $model_class(); $addons_data[$class] = method_exists($addons[$class], 'parse') ? $addons[$class]->parse($parsingData) : false; } else { $parse_func = $class . '_parse'; if (function_exists($parse_func)) { $addons_data[$class] = call_user_func($parse_func, $parsingData); } } } // save current import state to variables before import $created = $this->created; $updated = $this->updated; $skipped = $this->skipped; $specified_records = array(); if ($this->options['is_import_specified']) { foreach (preg_split('% *, *%', $this->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) { if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) { $specified_records = array_merge($specified_records, range(intval($mtch[1]), intval($mtch[2]))); } else { $specified_records = array_merge($specified_records, array(intval($chank))); } } } foreach ($titles as $i => $void) { wp_cache_flush(); do_action('pmxi_before_post_import', $this->id); if (empty($titles[$i])) { if (!empty($addons_data['PMWI_Plugin']) and !empty($addons_data['PMWI_Plugin']['single_product_parent_ID'][$i])) { $titles[$i] = $addons_data['PMWI_Plugin']['single_product_parent_ID'][$i] . ' Product Variation'; } else { $skipped++; $logger and call_user_func($logger, __('<b>SKIPPED</b>: by empty title', 'pmxi_plugin')); $logger and PMXI_Plugin::$session['pmxi_import']['chunk_number'] = ++PMXI_Plugin::$session->data['pmxi_import']['chunk_number']; $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; pmxi_session_commit(); continue; } } $articleData = array('post_type' => $post_type, 'post_status' => "xpath" == $this->options['status'] ? $post_status[$i] : $this->options['status'], 'comment_status' => $this->options['comment_status'], 'ping_status' => $this->options['ping_status'], 'post_title' => !empty($this->template['is_leave_html']) ? html_entity_decode($titles[$i]) : $titles[$i], 'post_excerpt' => apply_filters('pmxi_the_excerpt', !empty($this->template['is_leave_html']) ? html_entity_decode($post_excerpt[$i]) : $post_excerpt[$i], $this->id), 'post_name' => $post_slug[$i], 'post_content' => apply_filters('pmxi_the_content', !empty($this->template['is_leave_html']) ? html_entity_decode($contents[$i]) : $contents[$i], $this->id), 'post_date' => $dates[$i], 'post_date_gmt' => get_gmt_from_date($dates[$i]), 'post_author' => $post_author[$i], 'tags_input' => $tags[$i]); if ('post' != $articleData['post_type']) { $articleData += array('menu_order' => $this->options['order'], 'post_parent' => $this->options['parent']); } // Re-import Records Matching $post_to_update = false; $post_to_update_id = false; // if Auto Matching re-import option selected if ("manual" != $this->options['duplicate_matching']) { // find corresponding article among previously imported $postRecord->clear(); $postRecord->getBy(array('unique_key' => $unique_keys[$i], 'import_id' => $this->id)); if (!$postRecord->isEmpty()) { $post_to_update = get_post($post_to_update_id = $postRecord->post_id); } // if Manual Matching re-import option seleted } else { $postRecord->clear(); // find corresponding article among previously imported $postRecord->getBy(array('unique_key' => $unique_keys[$i], 'import_id' => $this->id)); if ('custom field' == $this->options['duplicate_indicator']) { $custom_duplicate_value = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_value'], $file)->parse($records); $tmp_files[] = $file; $custom_duplicate_name = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_name'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $custom_duplicate_name = $custom_duplicate_value = array_fill(0, count($titles), ''); } // handle duplicates according to import settings if ($duplicates = pmxi_findDuplicates($articleData, $custom_duplicate_name[$i], $custom_duplicate_value[$i], $this->options['duplicate_indicator'])) { $duplicate_id = array_shift($duplicates); if ($duplicate_id) { $post_to_update = get_post($post_to_update_id = $duplicate_id); } } } if (!empty($specified_records)) { if (!in_array($created + $updated + $skipped + 1, $specified_records)) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } $skipped++; $logger and call_user_func($logger, __('<b>SKIPPED</b>: by specified records option', 'pmxi_plugin')); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $logger and PMXI_Plugin::$session['pmxi_import']['chunk_number'] = ++PMXI_Plugin::$session->data['pmxi_import']['chunk_number']; pmxi_session_commit(); continue; } } // Duplicate record is founded if ($post_to_update) { // Do not update already existing records option selected if ("yes" == $this->options['is_keep_former_posts']) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } do_action('pmxi_do_not_update_existing', $post_to_update_id, $this->id, $this->iteration); $skipped++; $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: Previously imported record found for `%s`', 'pmxi_plugin'), $articleData['post_title'])); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $logger and PMXI_Plugin::$session['pmxi_import']['chunk_number'] = ++PMXI_Plugin::$session->data['pmxi_import']['chunk_number']; pmxi_session_commit(); continue; } $articleData['ID'] = $post_to_update_id; // Choose which data to update if ($this->options['update_all_data'] == 'no') { // preserve date of already existing article when duplicate is found if (!$this->options['is_update_categories'] or $this->options['is_update_categories'] and $this->options['update_categories_logic'] != "full_update") { // preserve categories and tags of already existing article if corresponding setting is specified $cats_list = get_the_category($articleData['ID']); $existing_cats = array(); if (is_wp_error($cats_list)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to get current categories for article #%d, updating with those read from XML file', 'pmxi_plugin'), $articleData['ID'])); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { $cats_new = array(); foreach ($cats_list as $c) { $cats_new[] = $c->slug; } $existing_cats[$i] = $cats_new; } // Re-import Post Tags if (!$this->options['is_update_categories'] or $this->options['update_categories_logic'] == 'add_new' or $this->options['update_categories_logic'] == 'only' and empty($this->options['taxonomies_list']) or !empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and (in_array('post_tag', $this->options['taxonomies_list']) and $this->options['update_categories_logic'] == 'all_except' or !in_array('post_tag', $this->options['taxonomies_list']) and $this->options['update_categories_logic'] == 'only')) { $tags_list = get_the_tags($articleData['ID']); if (is_wp_error($tags_list)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to get current tags for article #%d, updating with those read from XML file', 'pmxi_plugin'), $articleData['ID'])); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { $tags_new = ($this->options['is_update_categories'] and $this->options['update_categories_logic'] == 'add_new') ? array_filter(explode(",", $tags[$i])) : array(); if ($tags_list) { foreach ($tags_list as $t) { if (!in_array($t->name, $tags_new)) { $tags_new[] = $t->name; } } } $articleData['tags_input'] = implode(', ', $tags_new); } } $existing_taxonomies = array(); foreach (array_keys($taxonomies) as $tx_name) { $txes_list = get_the_terms($articleData['ID'], $tx_name); if (is_wp_error($txes_list)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to get current taxonomies for article #%d, updating with those read from XML file', 'pmxi_plugin'), $articleData['ID'])); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { $txes_new = array(); if (!empty($txes_list)) { foreach ($txes_list as $t) { $txes_new[] = $t->slug; } } $existing_taxonomies[$tx_name][$i] = $txes_new; } } } else { //Remove existing taxonomies foreach (array_keys($taxonomies) as $tx_name) { wp_set_object_terms($articleData['ID'], NULL, $tx_name); } } if (!$this->options['is_update_dates']) { // preserve date of already existing article when duplicate is found $articleData['post_date'] = $post_to_update->post_date; $articleData['post_date_gmt'] = $post_to_update->post_date_gmt; } if (!$this->options['is_update_status']) { // preserve status and trashed flag $articleData['post_status'] = $post_to_update->post_status; } if (!$this->options['is_update_content']) { $articleData['post_content'] = $post_to_update->post_content; } if (!$this->options['is_update_title']) { $articleData['post_title'] = $post_to_update->post_title; } if (!$this->options['is_update_slug']) { $articleData['post_name'] = $post_to_update->post_name; } if (!$this->options['is_update_excerpt']) { $articleData['post_excerpt'] = $post_to_update->post_excerpt; } if (!$this->options['is_update_menu_order']) { $articleData['menu_order'] = $post_to_update->menu_order; } if (!$this->options['is_update_parent']) { $articleData['post_parent'] = $post_to_update->post_parent; } } if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_attachments']) { wp_delete_attachments($articleData['ID'], true, 'files'); } // handle obsolete attachments (i.e. delete or keep) according to import settings if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_images'] and $this->options['update_images_logic'] == "full_update") { wp_delete_attachments($articleData['ID'], $this->options['download_images'], 'images'); } } elseif (!$postRecord->isEmpty()) { // existing post not found though it's track was found... clear the leftover, plugin will continue to treat record as new $postRecord->delete(); } // no new records are created. it will only update posts it finds matching duplicates for if (!$this->options['create_new_records'] and empty($articleData['ID'])) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } $logger and call_user_func($logger, __('<b>SKIPPED</b>: by do not create new posts option.', 'pmxi_plugin')); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $logger and PMXI_Plugin::$session['pmxi_import']['chunk_number'] = ++PMXI_Plugin::$session->data['pmxi_import']['chunk_number']; $skipped++; pmxi_session_commit(); continue; } // cloak urls with `WP Wizard Cloak` if corresponding option is set if (!empty($this->options['is_cloak']) and class_exists('PMLC_Plugin')) { if (preg_match_all('%<a\\s[^>]*href=(?(?=")"([^"]*)"|(?(?=\')\'([^\']*)\'|([^\\s>]*)))%is', $articleData['post_content'], $matches, PREG_PATTERN_ORDER)) { $hrefs = array_unique(array_merge(array_filter($matches[1]), array_filter($matches[2]), array_filter($matches[3]))); foreach ($hrefs as $url) { if (preg_match('%^\\w+://%i', $url)) { // mask only links having protocol // try to find matching cloaked link among already registered ones $list = new PMLC_Link_List(); $linkTable = $list->getTable(); $rule = new PMLC_Rule_Record(); $ruleTable = $rule->getTable(); $dest = new PMLC_Destination_Record(); $destTable = $dest->getTable(); $list->join($ruleTable, "{$ruleTable}.link_id = {$linkTable}.id")->join($destTable, "{$destTable}.rule_id = {$ruleTable}.id")->setColumns("{$linkTable}.*")->getBy(array("{$linkTable}.destination_type =" => 'ONE_SET', "{$linkTable}.is_trashed =" => 0, "{$linkTable}.preset =" => '', "{$linkTable}.expire_on =" => '0000-00-00', "{$ruleTable}.type =" => 'ONE_SET', "{$destTable}.weight =" => 100, "{$destTable}.url LIKE" => $url), NULL, 1, 1)->convertRecords(); if ($list->count()) { // matching link found $link = $list[0]; } else { // register new cloaked link global $wpdb; $slug = max(intval($wpdb->get_var("SELECT MAX(CONVERT(name, SIGNED)) FROM {$linkTable}")), intval($wpdb->get_var("SELECT MAX(CONVERT(slug, SIGNED)) FROM {$linkTable}")), 0); $i = 0; do { is_int(++$slug) and $slug > 0 or $slug = 1; $is_slug_found = !intval($wpdb->get_var("SELECT COUNT(*) FROM {$linkTable} WHERE name = '{$slug}' OR slug = '{$slug}'")); } while (!$is_slug_found and $i++ < 100000); if ($is_slug_found) { $link = new PMLC_Link_Record(array('name' => strval($slug), 'slug' => strval($slug), 'header_tracking_code' => '', 'footer_tracking_code' => '', 'redirect_type' => '301', 'destination_type' => 'ONE_SET', 'preset' => '', 'forward_url_params' => 1, 'no_global_tracking_code' => 0, 'expire_on' => '0000-00-00', 'created_on' => date('Y-m-d H:i:s'), 'is_trashed' => 0)); $link->insert(); $rule = new PMLC_Rule_Record(array('link_id' => $link->id, 'type' => 'ONE_SET', 'rule' => '')); $rule->insert(); $dest = new PMLC_Destination_Record(array('rule_id' => $rule->id, 'url' => $url, 'weight' => 100)); $dest->insert(); } else { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to create cloaked link for %s', 'pmxi_plugin'), $url)); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; $link = NULL; } } if ($link) { // cloaked link is found or created for url $articleData['post_content'] = preg_replace('%' . preg_quote($url, '%') . '(?=([\\s\'"]|$))%i', $link->getUrl(), $articleData['post_content']); } } } } } // insert article being imported $pid = $this->options['is_fast_mode'] ? pmxi_insert_post($articleData, true) : wp_insert_post($articleData, true); if (is_wp_error($pid)) { $logger and call_user_func($logger, __('<b>ERROR</b>', 'pmxi_plugin') . ': ' . $pid->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['errors'] = ++PMXI_Plugin::$session->data['pmxi_import']['errors']; } else { if ("manual" != $this->options['duplicate_matching'] or empty($articleData['ID'])) { // associate post with import $postRecord->isEmpty() and $postRecord->set(array('post_id' => $pid, 'import_id' => $this->id, 'unique_key' => $unique_keys[$i], 'product_key' => ($post_type == "product" and PMXI_Admin_Addons::get_addon('PMWI_Plugin')) ? $addons_data['PMWI_Plugin']['single_product_ID'][$i] : ''))->insert(); $postRecord->set(array('iteration' => $this->iteration))->update(); } // [post format] if (current_theme_supports('post-formats') && post_type_supports($post_type, 'post-formats')) { set_post_format($pid, $this->options['post_format']); } // [/post format] // [custom fields] if (empty($articleData['ID']) or $this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_custom_fields'] or $this->options['update_all_data'] == 'no' and $this->options['is_update_attributes']) { // Delete all meta keys if (!empty($articleData['ID'])) { // Get all existing meta keys $existing_meta_keys = array(); foreach (get_post_meta($pid, '') as $cur_meta_key => $cur_meta_val) { $existing_meta_keys[] = $cur_meta_key; } // delete keys which are no longer correspond to import settings foreach ($existing_meta_keys as $cur_meta_key) { // Do not delete post meta for features image if (in_array($cur_meta_key, array('_thumbnail_id', '_product_image_gallery'))) { continue; } $field_to_delete = true; // apply addons filters if (!apply_filters('pmxi_custom_field_to_delete', $field_to_delete, $pid, $post_type, $this->options, $cur_meta_key)) { continue; } // Update all Custom Fields is defined if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_custom_fields'] and $this->options['update_custom_fields_logic'] == "full_update") { delete_post_meta($pid, $cur_meta_key); } elseif ($this->options['update_all_data'] == 'no' and $this->options['is_update_custom_fields'] and $this->options['update_custom_fields_logic'] == "only") { if (!empty($this->options['custom_fields_list']) and is_array($this->options['custom_fields_list']) and in_array($cur_meta_key, $this->options['custom_fields_list'])) { delete_post_meta($pid, $cur_meta_key); } } elseif ($this->options['update_all_data'] == 'no' and $this->options['is_update_custom_fields'] and $this->options['update_custom_fields_logic'] == "all_except") { if (empty($this->options['custom_fields_list']) or !in_array($cur_meta_key, $this->options['custom_fields_list'])) { delete_post_meta($pid, $cur_meta_key); } } } } $encoded_meta = array(); foreach ($serialized_meta as $m_key => $values) { if (!empty($articleData['ID'])) { if ($this->options['update_all_data'] != 'yes') { $field_to_update = false; if ($this->options['is_update_custom_fields'] and $this->options['update_custom_fields_logic'] == "only" and !empty($this->options['custom_fields_list']) and is_array($this->options['custom_fields_list']) and in_array($m_key, $this->options['custom_fields_list'])) { $field_to_update = true; } if ($this->options['is_update_custom_fields'] and $this->options['update_custom_fields_logic'] == "all_except" and (empty($this->options['custom_fields_list']) or !in_array($m_key, $this->options['custom_fields_list']))) { $field_to_update = true; } if ($this->options['update_custom_fields_logic'] == "full_update") { $field_to_update = true; } // apply addons filters $field_to_update = apply_filters('pmxi_custom_field_to_update', $field_to_update, $post_type, $this->options, $m_key); if (!$field_to_update) { continue; } } } update_post_meta($pid, $m_key, apply_filters('pmxi_custom_field', is_serialized($values[$i]) ? unserialize($values[$i]) : $values[$i], $this->id)); do_action('pmxi_update_post_meta', $pid, $m_key, is_serialized($values[$i]) ? unserialize($values[$i]) : $values[$i]); // hook that was triggered after post meta data updated } } // [/custom fields] // [addons import] // prepare data for import $importData = array('pid' => $pid, 'i' => $i, 'import' => $this, 'articleData' => $articleData, 'xml' => $xml, 'is_cron' => $is_cron, 'logger' => $logger, 'xpath_prefix' => $xpath_prefix); // deligate operation to addons foreach (PMXI_Admin_Addons::get_active_addons() as $class) { if (class_exists($class)) { if (method_exists($addons[$class], 'import')) { $addons[$class]->import($importData); } } else { $import_func = $class . '_import'; if (function_exists($import_func)) { call_user_func($import_func, $importData, $addons_data[$class]); } } } // [/addons import] // Page Template if ('post' != $articleData['post_type'] and !empty($this->options['page_template'])) { update_post_meta($pid, '_wp_page_template', $this->options['page_template']); } // [featured image] if (!empty($uploads) and false === $uploads['error'] and !empty($featured_images[$i]) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_images'])) { require_once ABSPATH . 'wp-admin/includes/image.php'; $success_images = false; $gallery_attachment_ids = array(); $_pmxi_images = array(); $imgs = !empty($this->options['featured_delim']) ? str_getcsv($featured_images[$i], $this->options['featured_delim']) : explode("\n", $featured_images[$i]); if (!empty($imgs)) { if ($this->options['set_image_meta_data']) { $img_titles = !empty($this->options['image_meta_title_delim']) ? str_getcsv($image_meta_titles[$i], $this->options['image_meta_title_delim']) : explode("\n", $image_meta_titles[$i]); $img_captions = !empty($this->options['image_meta_caption_delim']) ? str_getcsv($image_meta_captions[$i], $this->options['image_meta_caption_delim']) : explode("\n", $image_meta_captions[$i]); $img_alts = !empty($this->options['image_meta_alt_delim']) ? str_getcsv($image_meta_alts[$i], $this->options['image_meta_alt_delim']) : explode("\n", $image_meta_alts[$i]); $img_descriptions = !empty($this->options['image_meta_description_delim']) ? str_getcsv($image_meta_descriptions[$i], $this->options['image_meta_description_delim']) : explode("\n", $image_meta_descriptions[$i]); } foreach ($imgs as $k => $img_url) { if (empty($img_url)) { continue; } $url = str_replace(" ", "%20", trim($img_url)); $bn = preg_replace('/[\\?|&].*/', '', basename($url)); $img_ext = pmxi_getExtensionFromStr($url); $default_extension = pmxi_getExtension($bn); if ($img_ext == "") { $img_ext = pmxi_get_remote_image_ext($url); } // generate local file name $image_name = urldecode(($this->options['auto_rename_images'] and "" != $auto_rename_images[$i]) ? sanitize_file_name($auto_rename_images[$i] . '_' . ($img_ext ? str_replace("." . $default_extension, "", $bn) : $bn)) : sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $bn) : $bn)) . ("" != $img_ext ? '.' . $img_ext : ''); // if wizard store image data to custom field $create_image = false; $download_image = true; if (base64_decode($url, true) !== false) { $img = @imagecreatefromstring(base64_decode($url)); if ($img) { $image_filename = md5(time()) . '.jpg'; $image_filepath = $uploads['path'] . '/' . $image_filename; imagejpeg($img, $image_filepath); if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'pmxi_plugin'), $image_filepath)); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { $create_image = true; } } } else { $image_filename = wp_unique_filename($uploads['path'], $image_name); $image_filepath = $uploads['path'] . '/' . $image_filename; // keep existing and add newest images if (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no") { $attachment_imgs = get_posts(array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $pid)); if ($attachment_imgs) { foreach ($attachment_imgs as $attachment_img) { if ($attachment_img->guid == $uploads['url'] . '/' . $image_name) { $download_image = false; $success_images = true; if (!has_post_thumbnail($pid)) { set_post_thumbnail($pid, $attachment_img->ID); } else { $gallery_attachment_ids[] = $attachment_img->ID; } $logger and call_user_func($logger, sprintf(__('<b>Image SKIPPED</b>: The image %s is always exists for the %s', 'pmxi_plugin'), basename($attachment_img->guid), $articleData['post_title'])); } } } } if ($download_image) { // do not download images if (!$this->options['download_images']) { $image_filename = $image_name; $image_filepath = $uploads['path'] . '/' . $image_filename; $existing_attachment = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->prefix . "posts WHERE guid = '%s'", $uploads['url'] . '/' . $image_filename)); if (!empty($existing_attachment->ID)) { $download_image = false; $create_image = false; if (!has_post_thumbnail($pid)) { set_post_thumbnail($pid, $existing_attachment->ID); } else { $gallery_attachment_ids[] = $existing_attachment->ID; } do_action('pmxi_gallery_image', $pid, $existing_attachment->ID, $image_filepath); } else { if (@file_exists($image_filepath)) { $download_image = false; if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'pmxi_plugin'), $image_filepath)); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; @unlink($image_filepath); } else { $create_image = true; } } } } if ($download_image) { $request = get_file_curl($url, $image_filepath); if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url))) { @unlink($image_filepath); // delete file since failed upload may result in empty file created } elseif ($image_info = @getimagesize($image_filepath) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $create_image = true; } if (!$create_image) { $url = str_replace(" ", "%20", trim(pmxi_convert_encoding($img_url))); $request = get_file_curl($url, $image_filepath); if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url))) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: File %s cannot be saved locally as %s', 'pmxi_plugin'), $url, $image_filepath)); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; @unlink($image_filepath); // delete file since failed upload may result in empty file created } elseif (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'pmxi_plugin'), $url)); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; @unlink($image_filepath); } else { $create_image = true; } } } } } if ($create_image) { $attachment = array('post_mime_type' => image_type_to_mime_type($image_info[2]), 'guid' => $uploads['url'] . '/' . $image_filename, 'post_title' => $image_filename, 'post_content' => '', 'post_author' => $post_author[$i]); if ($image_meta = wp_read_image_metadata($image_filepath)) { if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $attachment['post_title'] = $image_meta['title']; } if (trim($image_meta['caption'])) { $attachment['post_content'] = $image_meta['caption']; } } $attid = $this->options['is_fast_mode'] ? pmxi_insert_attachment($attachment, $image_filepath, $pid) : wp_insert_attachment($attachment, $image_filepath, $pid); if (is_wp_error($attid)) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $attid->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once ABSPATH . 'wp-admin/includes/image.php'; wp_update_attachment_metadata($attid, wp_generate_attachment_metadata($attid, $image_filepath)); if ($this->options['set_image_meta_data']) { $update_attachment_meta = array(); if (!empty($img_titles[$k])) { $update_attachment_meta['post_title'] = $img_titles[$k]; } if (!empty($img_captions[$k])) { $update_attachment_meta['post_excerpt'] = $img_captions[$k]; } if (!empty($img_descriptions[$k])) { $update_attachment_meta['post_content'] = $img_descriptions[$k]; } if (!empty($img_alts[$k])) { update_post_meta($attid, '_wp_attachment_image_alt', $img_alts[$k]); } if (!empty($update_attachment_meta)) { $this->wpdb->update($this->wpdb->posts, $update_attachment_meta, array('ID' => $attid)); } } do_action('pmxi_gallery_image', $pid, $attid, $image_filepath); $success_images = true; if (!has_post_thumbnail($pid)) { set_post_thumbnail($pid, $attid); } else { $gallery_attachment_ids[] = $attid; } } } } } // Set product gallery images if ($post_type == "product" and !empty($gallery_attachment_ids)) { update_post_meta($pid, '_product_image_gallery', implode(',', $gallery_attachment_ids)); } // Create entry as Draft if no images are downloaded successfully if (!$success_images and "yes" == $this->options['create_draft']) { $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid)); } } // [/featured image] // [attachments] if (!empty($uploads) and false === $uploads['error'] and !empty($attachments[$i]) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_attachments'])) { // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once ABSPATH . 'wp-admin/includes/image.php'; if (!is_array($attachments[$i])) { $attachments[$i] = array($attachments[$i]); } foreach ($attachments[$i] as $attachment) { if ("" == $attachment) { continue; } $atchs = str_getcsv($attachment, $this->options['atch_delim']); if (!empty($atchs)) { foreach ($atchs as $atch_url) { if (empty($atch_url)) { continue; } $atch_url = str_replace(" ", "%20", trim($atch_url)); $attachment_filename = wp_unique_filename($uploads['path'], urldecode(basename(parse_url(trim($atch_url), PHP_URL_PATH)))); $attachment_filepath = $uploads['path'] . '/' . sanitize_file_name($attachment_filename); $request = get_file_curl(trim($atch_url), $attachment_filepath); if ((is_wp_error($request) or $request === false) and !@file_put_contents($attachment_filepath, @file_get_contents(trim($atch_url)))) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Attachment file %s cannot be saved locally as %s', 'pmxi_plugin'), trim($atch_url), $attachment_filepath)); is_wp_error($request) and $logger and call_user_func($logger, sprintf(__('<b>WP Error</b>: %s', 'pmxi_plugin'), $request->get_error_message())); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; unlink($attachment_filepath); // delete file since failed upload may result in empty file created } elseif (!($wp_filetype = wp_check_filetype(basename($attachment_filename), null))) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Can\'t detect attachment file type %s', 'pmxi_plugin'), trim($atch_url))); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { $attachment_data = array('guid' => $uploads['baseurl'] . '/' . _wp_relative_upload_path($attachment_filepath), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($attachment_filepath)), 'post_content' => '', 'post_status' => 'inherit', 'post_author' => $post_author[$i]); $attach_id = $this->options['is_fast_mode'] ? pmxi_insert_attachment($attachment_data, $attachment_filepath, $pid) : wp_insert_attachment($attachment_data, $attachment_filepath, $pid); if (is_wp_error($attach_id)) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $pid->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } else { wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attachment_filepath)); do_action('pmxi_attachment_uploaded', $pid, $attid, $image_filepath); } } } } } } // [/attachments] // [custom taxonomies] if (!empty($taxonomies)) { foreach ($taxonomies as $tx_name => $txes) { // Skip updating product attributes if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) { continue; } if (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_categories']) { if (!empty($articleData['ID'])) { if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "all_except" and !empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and in_array($tx_name, $this->options['taxonomies_list'])) { continue; } if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "only" and (!empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and !in_array($tx_name, $this->options['taxonomies_list']) or empty($this->options['taxonomies_list']))) { continue; } } $assign_taxes = array(); if ($this->options['update_categories_logic'] == "add_new" and !empty($existing_taxonomies[$tx_name][$i])) { $assign_taxes = $existing_taxonomies[$tx_name][$i]; unset($existing_taxonomies[$tx_name][$i]); } elseif (!empty($existing_taxonomies[$tx_name][$i])) { unset($existing_taxonomies[$tx_name][$i]); } // create term if not exists if (!empty($txes[$i])) { foreach ($txes[$i] as $key => $single_tax) { if (is_array($single_tax)) { $parent_id = !empty($single_tax['parent']) ? pmxi_recursion_taxes($single_tax['parent'], $tx_name, $txes[$i], $key) : ''; $term = is_exists_term($tx_name, $single_tax['name'], (int) $parent_id); if (empty($term) and !is_wp_error($term)) { $term_attr = array('parent' => !empty($parent_id) ? $parent_id : 0); $term = wp_insert_term($single_tax['name'], $tx_name, $term_attr); } if (is_wp_error($term)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: `%s`', 'pmxi_plugin'), $term->get_error_message())); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } elseif (!empty($term)) { $cat_id = $term['term_id']; if ($cat_id and $single_tax['assign']) { $term = get_term_by('id', $cat_id, $tx_name); if (!in_array($term->slug, $assign_taxes)) { $assign_taxes[] = $term->slug; } } } } } } if (!empty($assign_taxes)) { // associate taxes with post $term_ids = wp_set_object_terms($pid, $assign_taxes, $tx_name); if (is_wp_error($term_ids)) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $term_ids->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } } } } if (!empty($existing_taxonomies) and $this->options['update_all_data'] == "no" and $this->options['is_update_categories'] and $this->options['update_categories_logic'] != 'full_update') { foreach ($existing_taxonomies as $tx_name => $txes) { // Skip updating product attributes if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) { continue; } if (!empty($txes[$i])) { $term_ids = wp_set_object_terms($pid, $txes[$i], $tx_name); if (is_wp_error($term_ids)) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $term_ids->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } } } } } // [/custom taxonomies] // [categories] if (!empty($cats[$i])) { if (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_categories']) { wp_set_object_terms($pid, NULL, 'category'); $is_update_cats = true; if (!empty($articleData['ID'])) { if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "all_except" and !empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and in_array('category', $this->options['taxonomies_list'])) { $is_update_cats = false; } if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "only" and (!empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and !in_array('category', $this->options['taxonomies_list']) or empty($this->options['taxonomies_list']))) { $is_update_cats = false; } } if ($is_update_cats) { $assign_cats = array(); if ($this->options['update_categories_logic'] == "add_new" and !empty($existing_cats[$i])) { $assign_cats = $existing_cats[$i]; unset($existing_cats[$i]); } elseif (!empty($existing_cats[$i])) { unset($existing_cats[$i]); } // create categories if it's doesn't exists foreach ($cats[$i] as $key => $single_cat) { if (is_array($single_cat)) { $parent_id = !empty($single_cat['parent']) ? pmxi_recursion_taxes($single_cat['parent'], 'category', $cats[$i], $key) : ''; $term = is_exists_term('category', $single_cat['name'], (int) $parent_id); if (empty($term) and !is_wp_error($term)) { $term = wp_insert_term($single_cat['name'], 'category', array('parent' => !empty($parent_id) ? (int) $parent_id : 0)); } if (is_wp_error($term)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: `%s`', 'pmxi_plugin'), $term->get_error_message())); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } elseif (!empty($term)) { $cat_id = $term['term_id']; if ($cat_id and $single_cat['assign']) { $term = get_term_by('id', $cat_id, 'category'); if (!in_array($term->slug, $assign_cats)) { $assign_cats[] = $term->slug; } } } } } // associate categories with post $cats_ids = wp_set_object_terms($pid, $assign_cats, 'category'); if (is_wp_error($cats_ids)) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $cats_ids->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } } } } if (!empty($existing_cats[$i]) and $this->options['update_all_data'] == "no" and (!$this->options['is_update_categories'] or $this->options['is_update_categories'] and $this->options['update_categories_logic'] != 'full_update')) { $cats_ids = wp_set_object_terms($pid, $existing_cats[$i], 'category'); if (is_wp_error($cats_ids)) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'pmxi_plugin') . ': ' . $cats_ids->get_error_message()); $logger and PMXI_Plugin::$session['pmxi_import']['warnings'] = ++PMXI_Plugin::$session->data['pmxi_import']['warnings']; } } // [/categories] if (empty($articleData['ID'])) { $logger and call_user_func($logger, sprintf(__('`%s` post created successfully', 'pmxi_plugin'), $articleData['post_title'])); } else { $logger and call_user_func($logger, sprintf(__('`%s` post updated successfully', 'pmxi_plugin'), $articleData['post_title'])); } // [addons import] // prepare data for import $importData = array('pid' => $pid, 'import' => $this, 'logger' => $logger); // deligate operation to addons foreach (PMXI_Admin_Addons::get_active_addons() as $class) { if (class_exists($class)) { if (method_exists($addons[$class], 'saved_post')) { $addons[$class]->saved_post($importData); } } else { $saved_func = $class . '_saved_post'; if (function_exists($saved_func)) { call_user_func($saved_func, $importData); } } } // [/addons import] do_action('pmxi_saved_post', $pid); // hook that was triggered immediately after post saved if (empty($articleData['ID'])) { $created++; } else { $updated++; } if (!$is_cron and "default" == $this->options['import_processing']) { $processed_records = $created + $updated + $skipped + PMXI_Plugin::$session->data['pmxi_import']['errors']; $logger and call_user_func($logger, sprintf(__('<span class="processing_info"><span class="created_count">%s</span><span class="updated_count">%s</span><span class="percents_count">%s</span></span>', 'pmxi_plugin'), $created, $updated, ceil($processed_records / $this->count * 100))); } } do_action('pmxi_after_post_import', $this->id); $logger and PMXI_Plugin::$session['pmxi_import']['chunk_number'] = ++PMXI_Plugin::$session->data['pmxi_import']['chunk_number']; } wp_cache_flush(); $this->set(array('imported' => $created + $updated, 'created' => $created, 'updated' => $updated, 'skipped' => $skipped, 'queue_chunk_number' => $created + $updated + $skipped))->update(); if (!$is_cron) { pmxi_session_commit(); $records_count = $this->created + $this->updated + $this->skipped + PMXI_Plugin::$session->data['pmxi_import']['errors']; $is_import_complete = $records_count == $this->count; // Delete posts that are no longer present in your file if ($is_import_complete and !empty($this->options['is_delete_missing']) and $this->options['duplicate_matching'] == 'auto') { $logger and call_user_func($logger, 'Removing previously imported posts which are no longer actual...'); $postList = new PMXI_Post_List(); $missing_ids = array(); $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration)); if (!$missingPosts->isEmpty()) { foreach ($missingPosts as $missingPost) { $missing_ids[] = $missingPost['post_id']; // Instead of deletion, set Custom Field if ($this->options['is_update_missing_cf']) { update_post_meta($missingPost['post_id'], $this->options['update_missing_cf_name'], $this->options['update_missing_cf_value']); } // Instead of deletion, change post status to Draft if ($this->options['set_missing_to_draft']) { $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $missingPost['post_id'])); } // Delete posts that are no longer present in your file if (!$this->options['is_update_missing_cf'] and !$this->options['set_missing_to_draft']) { // Remove attachments empty($this->options['is_keep_attachments']) and wp_delete_attachments($missingPost['post_id'], true, 'files'); // Remove images empty($this->options['is_keep_imgs']) and wp_delete_attachments($missingPost['post_id'], $this->options['download_images']); if (!empty($missingPost['id'])) { // Delete record form pmxi_posts $missingRecord = new PMXI_Post_Record(); $missingRecord->getById($missingPost['id'])->delete(); } else { $sql = "DELETE FROM " . PMXI_Plugin::getInstance()->getTablePrefix() . "posts WHERE post_id = " . $missingPost['post_id'] . " AND import_id = " . $missingPost['import_id']; $this->wpdb->query($this->wpdb->prepare($sql, '')); } // Clear post's relationships wp_delete_object_term_relationships($missingPost['post_id'], get_object_taxonomies('' != $this->options['custom_type'] ? $this->options['custom_type'] : 'post')); } } } // Delete posts from database if (!empty($missing_ids) && is_array($missing_ids) and !$this->options['is_update_missing_cf'] and !$this->options['set_missing_to_draft']) { $sql = "delete a,b,c\n\t\t\t\t\t\tFROM " . $this->wpdb->posts . " a\n\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->term_relationships . " b ON ( a.ID = b.object_id )\n\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->postmeta . " c ON ( a.ID = c.post_id )\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $missing_ids) . ")"; $this->wpdb->query($this->wpdb->prepare($sql, '')); do_action('pmxi_delete_post', $missing_ids); } } // Set out of stock status for missing records [Woocommerce add-on option] if ($is_import_complete and empty($this->options['is_delete_missing']) and $post_type == "product" and class_exists('PMWI_Plugin') and !empty($this->options['missing_records_stock_status'])) { $logger and call_user_func($logger, 'Update stock status previously imported posts which are no longer actual...'); $postList = new PMXI_Post_List(); $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration)); if (!$missingPosts->isEmpty()) { foreach ($missingPosts as $missingPost) { update_post_meta($missingPost['post_id'], '_stock_status', 'outofstock'); update_post_meta($missingPost['post_id'], '_stock', 0); } } } } } catch (XmlImportException $e) { $logger and call_user_func($logger, __('<b>ERROR</b>', 'pmxi_plugin') . ': ' . $e->getMessage()); $logger and PMXI_Plugin::$session['pmxi_import']['errors'] = ++PMXI_Plugin::$session->data['pmxi_import']['errors']; } $logger and $is_import_complete and call_user_func($logger, __('Cleaning temporary data...', 'pmxi_plugin')); foreach ($tmp_files as $file) { // remove all temporary files created @unlink($file); } if (($is_cron or $is_import_complete) and $this->options['is_delete_source']) { $logger and call_user_func($logger, __('Deleting source XML file...', 'pmxi_plugin')); // Delete chunks foreach (PMXI_Helper::safe_glob($uploads['path'] . '/pmxi_chunk_*', PMXI_Helper::GLOB_RECURSE | PMXI_Helper::GLOB_PATH) as $filePath) { @file_exists($filePath) and @unlink($filePath); } if ($this->type != "ftp") { if (!@unlink($this->path)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to remove %s', 'pmxi_plugin'), $this->path)); } } else { $file_path_array = PMXI_Helper::safe_glob($this->path, PMXI_Helper::GLOB_NODIR | PMXI_Helper::GLOB_PATH); if (!empty($file_path_array)) { foreach ($file_path_array as $path) { if (!@unlink($path)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to remove %s', 'pmxi_plugin'), $path)); } } } } } if (!$is_cron and $is_import_complete) { $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'registered_on' => date('Y-m-d H:i:s'), 'iteration' => ++$this->iteration))->update(); $logger and call_user_func($logger, 'Done'); } remove_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html')); kses_init(); // return any filtering rules back if they has been disabled for import procedure return $this; }
/** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @global array $_wp_additional_image_sizes * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * @return mixed Metadata for attachment. */ function wp_generate_attachment_metadata($attachment_id, $file) { $attachment = get_post($attachment_id); $metadata = array(); $support = false; if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; // Make the file path relative to the upload dir. $metadata['file'] = _wp_relative_upload_path($file); // Make thumbnails and other intermediate sizes. global $_wp_additional_image_sizes; $sizes = array(); foreach (get_intermediate_image_sizes() as $s) { $sizes[$s] = array('width' => '', 'height' => '', 'crop' => false); if (isset($_wp_additional_image_sizes[$s]['width'])) { $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']); } else { $sizes[$s]['width'] = get_option("{$s}_size_w"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['height'])) { $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']); } else { $sizes[$s]['height'] = get_option("{$s}_size_h"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['crop'])) { $sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop']; } else { $sizes[$s]['crop'] = get_option("{$s}_crop"); } // For default sizes set in options } /** * Filter the image sizes automatically generated when uploading an image. * * @since 2.9.0 * @since 4.4.0 Added the `$metadata` argument. * * @param array $sizes An associative array of image sizes. * @param array $metadata An associative array of image metadata: width, height, file. */ $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes, $metadata); if ($sizes) { $editor = wp_get_image_editor($file); if (!is_wp_error($editor)) { $metadata['sizes'] = $editor->multi_resize($sizes); } } else { $metadata['sizes'] = array(); } // Fetch additional metadata from EXIF/IPTC. $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } elseif (wp_attachment_is('video', $attachment)) { $metadata = wp_read_video_metadata($file); $support = current_theme_supports('post-thumbnails', 'attachment:video') || post_type_supports('attachment:video', 'thumbnail'); } elseif (wp_attachment_is('audio', $attachment)) { $metadata = wp_read_audio_metadata($file); $support = current_theme_supports('post-thumbnails', 'attachment:audio') || post_type_supports('attachment:audio', 'thumbnail'); } if ($support && !empty($metadata['image']['data'])) { // Check for existing cover. $hash = md5($metadata['image']['data']); $posts = get_posts(array('fields' => 'ids', 'post_type' => 'attachment', 'post_mime_type' => $metadata['image']['mime'], 'post_status' => 'inherit', 'posts_per_page' => 1, 'meta_key' => '_cover_hash', 'meta_value' => $hash)); $exists = reset($posts); if (!empty($exists)) { update_post_meta($attachment_id, '_thumbnail_id', $exists); } else { $ext = '.jpg'; switch ($metadata['image']['mime']) { case 'image/gif': $ext = '.gif'; break; case 'image/png': $ext = '.png'; break; } $basename = str_replace('.', '-', basename($file)) . '-image' . $ext; $uploaded = wp_upload_bits($basename, '', $metadata['image']['data']); if (false === $uploaded['error']) { $image_attachment = array('post_mime_type' => $metadata['image']['mime'], 'post_type' => 'attachment', 'post_content' => ''); /** * Filter the parameters for the attachment thumbnail creation. * * @since 3.9.0 * * @param array $image_attachment An array of parameters to create the thumbnail. * @param array $metadata Current attachment metadata. * @param array $uploaded An array containing the thumbnail path and url. */ $image_attachment = apply_filters('attachment_thumbnail_args', $image_attachment, $metadata, $uploaded); $sub_attachment_id = wp_insert_attachment($image_attachment, $uploaded['file']); add_post_meta($sub_attachment_id, '_cover_hash', $hash); $attach_data = wp_generate_attachment_metadata($sub_attachment_id, $uploaded['file']); wp_update_attachment_metadata($sub_attachment_id, $attach_data); update_post_meta($attachment_id, '_thumbnail_id', $sub_attachment_id); } } } // Remove the blob of binary data from the array. if ($metadata) { unset($metadata['image']['data']); } /** * Filter the generated attachment meta data. * * @since 2.1.0 * * @param array $metadata An array of attachment meta data. * @param int $attachment_id Current attachment ID. */ return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id); }
/** * Regenerate missing image dimensions for a particular attachment * @param (int) attachment ID * @return (array) new metadata for actual image **/ public function generate_thumb_missing($att_id) { // Fetch the attachment $att_raw = get_posts(array('include' => $att_id, 'post_type' => 'attachment', 'post_mime_type' => 'image')); $att = $att_raw[0]; $file = get_attached_file($att_id); // COMPLETE THIS SHIT. $metadata = array(); if (preg_match('!^image/!', get_post_mime_type($att)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // make thumbnails and other intermediate sizes global $_wp_additional_image_sizes; foreach (get_intermediate_image_sizes() as $s) { $sizes[$s] = array('width' => '', 'height' => '', 'crop' => FALSE); if (isset($_wp_additional_image_sizes[$s]['width'])) { $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']); } else { $sizes[$s]['width'] = get_option("{$s}_size_w"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['height'])) { $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']); } else { $sizes[$s]['height'] = get_option("{$s}_size_h"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['crop'])) { $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']); } else { $sizes[$s]['crop'] = get_option("{$s}_crop"); } // For default sizes set in options } $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes); // Only generate image if it does not already exist $att_meta = wp_get_attachment_metadata($att_id); foreach ($sizes as $size => $size_data) { // Size already exists if (isset($att_meta['sizes'][$size]) && file_exists($this->imageTrySize($file, $size_data['width'], $size_data['height']))) { $metadata['sizes'][$size] = $att_meta['sizes'][$size]; } else { // Generate new image $resized = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']); if ($resized) { $metadata['sizes'][$size] = $resized; } } } // Get image meta and update database manually $metadata['image_meta'] = wp_read_image_metadata($file); update_post_meta($att_id, "_wp_attachment_metadata", $metadata); } return $att; }
/** * Upload images and create attachments * * @param $url string Url of image */ private function dwsf_add_attachments($post_id, $url, $caption) { $url = str_replace('https', 'http', $url); // get upload directory $upload_dir = wp_upload_dir(); $pathinfo = pathinfo($url); $ext = $pathinfo['extension']; $image_name = time() . '.' . $ext; if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $image_name; } else { $file = $upload_dir['basedir'] . '/' . $image_name; } //http://profile.ak.fbcdn.net/hprofile-ak-snc4/174867_6427302910_1109589_s.jpg @copy($url, $file); @unlink($url); $wp_filetype = wp_check_filetype(basename($file), null); $attachment = array('guid' => $upload_dir['baseurl'] . '/' . _wp_relative_upload_path($file), 'post_mime_type' => $wp_filetype['type'], 'post_title' => $caption, 'post_content' => $caption, 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $file, $post_id); // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $file); wp_update_attachment_metadata($attach_id, $attach_data); return $attach_id; }
public function ajax_multi_upload() { $postID = isset($_REQUEST["postID"]) ? intval($_REQUEST["postID"]) : 0; check_ajax_referer('pe_theme_multi_upload'); $status = wp_handle_upload($_FILES['async-upload'], array('test_form' => true, 'action' => 'pe_theme_multi_upload')); $filename = $status["file"]; $type = $status["type"]; //$wp_filetype = wp_check_filetype(basename($filename), null ); $wp_upload_dir = wp_upload_dir(); $attachment = array('guid' => $wp_upload_dir['baseurl'] . "/" . _wp_relative_upload_path($filename), 'post_mime_type' => $type, 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $filename, $postID); // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); //$post = wp_get_single_post($attach_id); $post = get_post($attach_id); $post->meta = $attach_data; $tags = "Gallery {$postID}"; wp_set_post_terms($attach_id, $tags, PE_MEDIA_TAG, false); $images = array($post); $this->createPreviewThumbs($images); header("Content-Type: application/json"); echo json_encode(array("images" => $images, "upload" => wp_upload_dir())); die; }
function scalia_generate_thumbnail_src($attachment_id, $size) { if (in_array($size, array_keys(scalia_image_sizes()))) { $filepath = get_attached_file($attachment_id); $thumbFilepath = $filepath; $image = wp_get_image_editor($filepath); if (!is_wp_error($image) && $image) { $thumbFilepath = $image->generate_filename($size); if (!file_exists($thumbFilepath)) { $scalia_image_sizes = scalia_image_sizes(); if (!is_wp_error($image) && isset($scalia_image_sizes[$size])) { $image->resize($scalia_image_sizes[$size][0], $scalia_image_sizes[$size][1], $scalia_image_sizes[$size][2]); $image = $image->save($image->generate_filename($size)); } else { $thumbFilepath = $filepath; } } } $image = wp_get_image_editor($thumbFilepath); if (!is_wp_error($image) && $image) { $upload_dir = wp_upload_dir(); $sizes = $image->get_size(); return array($upload_dir['baseurl'] . '/' . _wp_relative_upload_path($thumbFilepath), $sizes['width'], $sizes['height']); } } return wp_get_attachment_url($attachment_id, $size); }
function ajax_plupload_action() { // check ajax noonce $imgid = $_POST["imgid"]; check_ajax_referer($imgid . 'pluploadan'); // handle file upload $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action')); if (!isset($status['error'])) { $filename = $status['file']; $wp_filetype = wp_check_filetype(basename($filename), null); $wp_upload_dir = wp_upload_dir(); $attachment = array('guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path($filename), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $idAttachment = wp_insert_attachment($attachment, $status['file'], $_POST['postID']); if ($idAttachment == 0) { $status = array('error' => 'Cannot attach file to post.'); } else { $status = array('url' => $status['url'], 'idAttachment' => $idAttachment, 'mime' => $wp_filetype['type']); } } echo json_encode($status); exit; }
function cjtheme_file_uploads($field_name, $allowed_width = null, $allowed_height = null, $allowed_file_types = null, $output = 'guid', $allowed_file_size = null) { global $wpdb; $errors = null; $wp_upload_dir = wp_upload_dir(); $tempFile = @$field_name; $targetPath = $wp_upload_dir['path'] . '/'; $targetFile = @$filename; $fileParts = @pathinfo($filename); $ext = explode('.', $tempFile); $ext = $ext[1]; $file_size = @$_FILES[$field_name]['size']; if (!is_null($allowed_file_size) && $file_size > $allowed_file_size * $KB) { $errors[] = sprintf(__('File size must be below %s kilobytes.', 'cjtheme'), $allowed_file_size); } list($img_width, $img_height) = @getimagesize($tempFile); if (!is_null($allowed_width) && $img_width != $allowed_width) { $errors[] = sprintf(__('Image width must be %s pixels.', 'cjtheme'), $allowed_width); } if (!is_null($allowed_height) && $img_width != $allowed_height) { $errors[] = sprintf(__('Image height must be %s pixels.', 'cjtheme'), $allowed_height); } if (!is_null($allowed_file_types) && !in_array(str_replace('.', '', $ext), explode('|', $allowed_file_types))) { $errors[] = __('Invalid file type.', 'cjtheme'); } if (is_array($errors)) { return $errors; } else { //$targetFile = str_replace('//', '/', $targetPath) . 'img_' . sha1(md5(date('M-d-y H:i:s')).rand(5,99999)) . '.'.$ext; $newFileName = wp_unique_filename($targetPath, $targetFile); $targetFile = str_replace('//', '/', $targetPath) . $newFileName; move_uploaded_file($tempFile, $targetFile); $filename = $targetFile; $wp_filetype = wp_check_filetype(basename($filename), null); $attachment = array('guid' => $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($filename), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $filename); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); global $wpdb; $guid = $wpdb->get_row("SELECT * FROM {$wpdb->posts} WHERE ID = '{$attach_id}'"); if ($output == 'guid') { return $guid->guid; } else { return $attach_id; } } }
/** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * @return mixed Metadata for attachment. */ function wp_generate_attachment_metadata_custom($attachment_id, $file, $thumbnails = NULL) { $attachment = get_post($attachment_id); $metadata = array(); if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); $sizes = ajax_thumbnail_rebuild_get_sizes(); $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes); foreach ($sizes as $size => $size_data) { if (isset($thumbnails) && !in_array($size, $thumbnails)) { $intermediate_size = image_get_intermediate_size($attachment_id, $size_data['name']); } else { $intermediate_size = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']); } if ($intermediate_size) { $metadata['sizes'][$size] = $intermediate_size; } } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id); }
/** * generate attachment metadata but DO NOT create thumbnails etc. * @param int $attachment_id * @param string $file * absolute file path */ public static function generate_attachment_metadata($attachment_id, $file) { $attachment = get_post($attachment_id); $metadata = array(); if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // work with some watermark plugin $metadata = apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id); } return $metadata; }
function createImages() { if (get_option('ioa_demo_images')) { return get_option('ioa_demo_images'); } $images = array("d1.jpg" => "d1.jpg", "d2.jpg" => "d2.jpg", "d3.jpg" => "d3.jpg"); foreach ($images as $key => $image) { $path = wp_upload_dir(); $cstatus = copy(PATH . "/sprites/i/demos/" . $key, $path['path'] . '/' . $image); $filename = $path['path'] . '/' . $image; $wp_filetype = wp_check_filetype(basename($filename), null); $attachment = array('guid' => $path['baseurl'] . _wp_relative_upload_path($filename), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $filename); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); $this->attach_ids[] = $attach_id; } update_option('ioa_demo_images', $this->attach_ids); }
/** * Generate meta data for the media * * @since 1.0.0 * * @access private * @param int $attachment_id Media ID to process. * @param string $file Filepath of the Attached image. * * @return mixed Metadata for attachment. */ public function generate_metadata($attachment_id, $file) { $attachment = get_post($attachment_id); $mime_type = get_post_mime_type($attachment); $metadata = array(); if (preg_match('!^image/!', $mime_type) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); //get the registered media sizes $sizes = mpp_get_media_sizes(); $sizes = apply_filters('mpp_intermediate_image_sizes', $sizes, $attachment_id); if ($sizes) { $editor = wp_get_image_editor($file); if (!is_wp_error($editor)) { $metadata['sizes'] = $editor->multi_resize($sizes); } } else { $metadata['sizes'] = array(); } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } elseif (preg_match('#^video/#', $mime_type)) { $metadata = wp_read_video_metadata($file); } elseif (preg_match('#^audio/#', $mime_type)) { $metadata = wp_read_audio_metadata($file); } $dir_path = trailingslashit(dirname($file)) . 'covers'; $url = wp_get_attachment_url($attachment_id); $base_url = str_replace(wp_basename($url), '', $url); //processing for audio/video cover if (!empty($metadata['image']['data'])) { $ext = '.jpg'; switch ($metadata['image']['mime']) { case 'image/gif': $ext = '.gif'; break; case 'image/png': $ext = '.png'; break; } $basename = str_replace('.', '-', basename($file)) . '-image' . $ext; $uploaded = $this->upload_bits($basename, $metadata['image']['data'], array('path' => $dir_path, 'url' => $base_url)); if (false === $uploaded['error']) { $attachment = array('post_mime_type' => $metadata['image']['mime'], 'post_type' => 'attachment', 'post_content' => ''); $sub_attachment_id = wp_insert_attachment($attachment, $uploaded['file']); $attach_data = $this->generate_metadata($sub_attachment_id, $uploaded['file']); wp_update_attachment_metadata($sub_attachment_id, $attach_data); //if the option is set to set post thumbnail if (mpp_get_option('set_post_thumbnail')) { mpp_update_media_meta($attachment_id, '_thumbnail_id', $sub_attachment_id); } //set the cover id mpp_update_media_cover_id($attachment_id, $sub_attachment_id); } } // remove the blob of binary data from the array if (isset($metadata['image']['data'])) { unset($metadata['image']['data']); } return apply_filters('mpp_generate_metadata', $metadata, $attachment_id); }
/** * Builds the GUID for a given file from the media library * @param full/path/to/file.jpg * @return guid */ public function buildGuid($file = null) { // $wp_upload_dir = wp_upload_dir(); return $this->upload_dir['baseurl'] . '/' . _wp_relative_upload_path($file); }
function wp_save_image($post_id) { $return = new stdClass(); $success = $delete = $scaled = $nocrop = false; $post = get_post($post_id); @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT)); $img = load_image_to_edit($post_id, $post->post_mime_type); if (!is_resource($img)) { $return->error = esc_js(__('Unable to create new image.')); return $return; } $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0; $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0; $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : ''; $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do']; if ($scale && $fwidth > 0 && $fheight > 0) { $sX = imagesx($img); $sY = imagesy($img); // check if it has roughly the same w / h ratio $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2); if (-0.1 < $diff && $diff < 0.1) { // scale the full size image $dst = wp_imagecreatetruecolor($fwidth, $fheight); if (imagecopyresampled($dst, $img, 0, 0, 0, 0, $fwidth, $fheight, $sX, $sY)) { imagedestroy($img); $img = $dst; $scaled = true; } } if (!$scaled) { $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.')); return $return; } } elseif (!empty($_REQUEST['history'])) { $changes = json_decode(stripslashes($_REQUEST['history'])); if ($changes) { $img = image_edit_apply_changes($img, $changes); } } else { $return->error = esc_js(__('Nothing to save, the image has not changed.')); return $return; } $meta = wp_get_attachment_metadata($post_id); $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true); if (!is_array($meta)) { $return->error = esc_js(__('Image data does not exist. Please re-upload the image.')); return $return; } if (!is_array($backup_sizes)) { $backup_sizes = array(); } // generate new filename $path = get_attached_file($post_id); $path_parts = pathinfo($path); $filename = $path_parts['filename']; $suffix = time() . rand(100, 999); if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) { if ('thumbnail' == $target) { $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}"; } else { $new_path = $path; } } else { while (true) { $filename = preg_replace('/-e([0-9]+)$/', '', $filename); $filename .= "-e{$suffix}"; $new_filename = "{$filename}.{$path_parts['extension']}"; $new_path = "{$path_parts['dirname']}/{$new_filename}"; if (file_exists($new_path)) { $suffix++; } else { break; } } } // save the full-size file, also needed to create sub-sizes if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) { $return->error = esc_js(__('Unable to save the image.')); return $return; } if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) { $tag = false; if (isset($backup_sizes['full-orig'])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) { $tag = "full-{$suffix}"; } } else { $tag = 'full-orig'; } if ($tag) { $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']); } $success = update_attached_file($post_id, $new_path); $meta['file'] = _wp_relative_upload_path($new_path); $meta['width'] = imagesx($img); $meta['height'] = imagesy($img); list($uwidth, $uheight) = wp_constrain_dimensions($meta['width'], $meta['height'], 128, 96); $meta['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; if ($success && ('nothumb' == $target || 'all' == $target)) { $sizes = get_intermediate_image_sizes(); if ('nothumb' == $target) { $sizes = array_diff($sizes, array('thumbnail')); } } $return->fw = $meta['width']; $return->fh = $meta['height']; } elseif ('thumbnail' == $target) { $sizes = array('thumbnail'); $success = $delete = $nocrop = true; } if (isset($sizes)) { foreach ($sizes as $size) { $tag = false; if (isset($meta['sizes'][$size])) { if (isset($backup_sizes["{$size}-orig"])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) { $tag = "{$size}-{$suffix}"; } } else { $tag = "{$size}-orig"; } if ($tag) { $backup_sizes[$tag] = $meta['sizes'][$size]; } } $crop = $nocrop ? false : get_option("{$size}_crop"); $resized = image_make_intermediate_size($new_path, get_option("{$size}_size_w"), get_option("{$size}_size_h"), $crop); if ($resized) { $meta['sizes'][$size] = $resized; } else { unset($meta['sizes'][$size]); } } } if ($success) { wp_update_attachment_metadata($post_id, $meta); update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes); if ($target == 'thumbnail' || $target == 'all' || $target == 'full') { $file_url = wp_get_attachment_url($post_id); if ($thumb = $meta['sizes']['thumbnail']) { $return->thumbnail = path_join(dirname($file_url), $thumb['file']); } else { $return->thumbnail = "{$file_url}?w=128&h=128"; } } } else { $delete = true; } if ($delete) { $delpath = apply_filters('wp_delete_file', $new_path); @unlink($delpath); } imagedestroy($img); $return->msg = esc_js(__('Image saved')); return $return; }
function gllr_wp_generate_attachment_metadata($attachment_id, $file, $metadata) { $attachment = get_post($attachment_id); $gllr_options = get_option('gllr_options'); add_image_size('album-thumb', $gllr_options['gllr_custom_size_px'][0][0], $gllr_options['gllr_custom_size_px'][0][1], true); add_image_size('photo-thumb', $gllr_options['gllr_custom_size_px'][1][0], $gllr_options['gllr_custom_size_px'][1][1], true); $metadata = array(); if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; /* Make the file path relative to the upload dir */ $metadata['file'] = _wp_relative_upload_path($file); /* Make thumbnails and other intermediate sizes */ global $_wp_additional_image_sizes; $image_size = array('album-thumb', 'photo-thumb', 'thumbnail'); /*get_intermediate_image_sizes();*/ foreach ($image_size as $s) { $sizes[$s] = array('width' => '', 'height' => '', 'crop' => FALSE); if (isset($_wp_additional_image_sizes[$s]['width'])) { $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']); } else { $sizes[$s]['width'] = get_option("{$s}_size_w"); } /* For default sizes set in options */ if (isset($_wp_additional_image_sizes[$s]['height'])) { $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']); } else { $sizes[$s]['height'] = get_option("{$s}_size_h"); } /* For default sizes set in options */ if (isset($_wp_additional_image_sizes[$s]['crop'])) { $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']); } else { $sizes[$s]['crop'] = get_option("{$s}_crop"); } /* For default sizes set in options */ } $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes); foreach ($sizes as $size => $size_data) { $resized = gllr_image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']); if ($resized) { $metadata['sizes'][$size] = $resized; } } /* Fetch additional metadata from exif/iptc */ $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id); }
/** * Saves image to post along with enqueued changes * in $_REQUEST['history'] * * @param int $post_id * @return \stdClass */ function wp_save_image($post_id) { global $_wp_additional_image_sizes; $return = new stdClass(); $success = $delete = $scaled = $nocrop = false; $post = get_post($post_id); $img = wp_get_image_editor(_load_image_to_edit_path($post_id, 'full')); if (is_wp_error($img)) { $return->error = esc_js(__('Unable to create new image.')); return $return; } $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0; $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0; $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : ''; $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do']; if ($scale && $fwidth > 0 && $fheight > 0) { $size = $img->get_size(); $sX = $size['width']; $sY = $size['height']; // Check if it has roughly the same w / h ratio. $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2); if (-0.1 < $diff && $diff < 0.1) { // Scale the full size image. if ($img->resize($fwidth, $fheight)) { $scaled = true; } } if (!$scaled) { $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.')); return $return; } } elseif (!empty($_REQUEST['history'])) { $changes = json_decode(wp_unslash($_REQUEST['history'])); if ($changes) { $img = image_edit_apply_changes($img, $changes); } } else { $return->error = esc_js(__('Nothing to save, the image has not changed.')); return $return; } $meta = wp_get_attachment_metadata($post_id); $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true); if (!is_array($meta)) { $return->error = esc_js(__('Image data does not exist. Please re-upload the image.')); return $return; } if (!is_array($backup_sizes)) { $backup_sizes = array(); } // Generate new filename. $path = get_attached_file($post_id); $path_parts = pathinfo($path); $filename = $path_parts['filename']; $suffix = time() . rand(100, 999); if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) { if ('thumbnail' == $target) { $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}"; } else { $new_path = $path; } } else { while (true) { $filename = preg_replace('/-e([0-9]+)$/', '', $filename); $filename .= "-e{$suffix}"; $new_filename = "{$filename}.{$path_parts['extension']}"; $new_path = "{$path_parts['dirname']}/{$new_filename}"; if (file_exists($new_path)) { $suffix++; } else { break; } } } // Save the full-size file, also needed to create sub-sizes. if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) { $return->error = esc_js(__('Unable to save the image.')); return $return; } if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) { $tag = false; if (isset($backup_sizes['full-orig'])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) { $tag = "full-{$suffix}"; } } else { $tag = 'full-orig'; } if ($tag) { $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']); } $success = $path === $new_path || update_attached_file($post_id, $new_path); $meta['file'] = _wp_relative_upload_path($new_path); $size = $img->get_size(); $meta['width'] = $size['width']; $meta['height'] = $size['height']; if ($success && ('nothumb' == $target || 'all' == $target)) { $sizes = get_intermediate_image_sizes(); if ('nothumb' == $target) { $sizes = array_diff($sizes, array('thumbnail')); } } $return->fw = $meta['width']; $return->fh = $meta['height']; } elseif ('thumbnail' == $target) { $sizes = array('thumbnail'); $success = $delete = $nocrop = true; } if (isset($sizes)) { $_sizes = array(); foreach ($sizes as $size) { $tag = false; if (isset($meta['sizes'][$size])) { if (isset($backup_sizes["{$size}-orig"])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) { $tag = "{$size}-{$suffix}"; } } else { $tag = "{$size}-orig"; } if ($tag) { $backup_sizes[$tag] = $meta['sizes'][$size]; } } if (isset($_wp_additional_image_sizes[$size])) { $width = intval($_wp_additional_image_sizes[$size]['width']); $height = intval($_wp_additional_image_sizes[$size]['height']); $crop = $nocrop ? false : $_wp_additional_image_sizes[$size]['crop']; } else { $height = get_option("{$size}_size_h"); $width = get_option("{$size}_size_w"); $crop = $nocrop ? false : get_option("{$size}_crop"); } $_sizes[$size] = array('width' => $width, 'height' => $height, 'crop' => $crop); } $meta['sizes'] = array_merge($meta['sizes'], $img->multi_resize($_sizes)); } unset($img); if ($success) { wp_update_attachment_metadata($post_id, $meta); update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes); if ($target == 'thumbnail' || $target == 'all' || $target == 'full') { // Check if it's an image edit from attachment edit screen if (!empty($_REQUEST['context']) && 'edit-attachment' == $_REQUEST['context']) { $thumb_url = wp_get_attachment_image_src($post_id, array(900, 600), true); $return->thumbnail = $thumb_url[0]; } else { $file_url = wp_get_attachment_url($post_id); if (!empty($meta['sizes']['thumbnail']) && ($thumb = $meta['sizes']['thumbnail'])) { $return->thumbnail = path_join(dirname($file_url), $thumb['file']); } else { $return->thumbnail = "{$file_url}?w=128&h=128"; } } } } else { $delete = true; } if ($delete) { wp_delete_file($new_path); } $return->msg = esc_js(__('Image saved')); return $return; }
public function upload_image($files_instance) { if (!function_exists('wp_handle_upload')) { include_once ABSPATH . 'wp-admin/includes/file.php'; } # Do Some Tricks... $_POST['action'] = 'simplead_handle_upload'; $override['test_form'] = false; $override['action'] = 'simplead_handle_upload'; $image_path = wp_handle_upload($files_instance, $override); $original_image = $image_path['file']; $images = array(); if ($original_image) { // Generate Sizes foreach ($this->ad_sizes as $prefix => $size) { $w = $size[0]; $h = $size[1]; $new_file = dirname($file) . "/{$prefix}_" . basename($file); #$thumb = image_resize($original_image, $w, $h, true); $thumb = dirname($original_image) . "/{$prefix}_" . basename($original_image); # Zebra Image Ressize $img = new Zebra_Image(); $img->enlarge_smaller_images = FALSE; $img->source_path = $original_image; $img->target_path = $thumb; $img->resize($w, $h, ZEBRA_IMAGE_CROP_CENTER, '#FFF'); $images[$prefix] = _wp_relative_upload_path($thumb); } $images['original'] = _wp_relative_upload_path($original_image); } return $images; }
/** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * * @param null|array $thumbnails: thumbnails to regenerate, if null all * * @return mixed Metadata for attachment. */ public static function wp_generate_attachment_metadata_custom($attachment_id, $file, $thumbnails = null) { $attachment = get_post($attachment_id); $meta_datas = get_post_meta($attachment_id, '_wp_attachment_metadata', true); $metadata = array(); if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) { $imagesize = getimagesize($file); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; // Make the file path relative to the upload dir $metadata['file'] = _wp_relative_upload_path($file); // make thumbnails and other intermediate sizes global $_wp_additional_image_sizes; foreach (get_intermediate_image_sizes() as $s) { $sizes[$s] = array('width' => '', 'height' => '', 'crop' => false); if (isset($_wp_additional_image_sizes[$s]['width'])) { $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']); } else { $sizes[$s]['width'] = get_option("{$s}_size_w"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['height'])) { $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']); } else { $sizes[$s]['height'] = get_option("{$s}_size_h"); } // For default sizes set in options if (isset($_wp_additional_image_sizes[$s]['crop'])) { $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']); } else { $sizes[$s]['crop'] = get_option("{$s}_crop"); } // For default sizes set in options } $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes); // Only if not all sizes if (isset($thumbnails) && is_array($thumbnails) && isset($meta_datas['sizes']) && !empty($meta_datas['sizes'])) { // Fill the array with the other sizes not have to be done foreach ($meta_datas['sizes'] as $name => $fsize) { $metadata['sizes'][$name] = $fsize; } } foreach ($sizes as $size => $size_data) { if (isset($thumbnails)) { if (!in_array($size, $thumbnails)) { continue; } } $resized = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']); if (isset($meta_datas['size'][$size])) { // Remove the size from the orignal sizes for after work unset($meta_datas['size'][$size]); } if ($resized) { $metadata['sizes'][$size] = $resized; } } // fetch additional metadata from exif/iptc $image_meta = wp_read_image_metadata($file); if ($image_meta) { $metadata['image_meta'] = $image_meta; } } return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id); }
static function createImages() { global $easy_metadata; if (!file_exists(EASY_F_PLUGIN_PATH . "/demo_data_here/" . $easy_metadata['image'])) { return; } if (get_option('easy_demo_images')) { return get_option('easy_demo_images'); } $images = array($easy_metadata['image']); $attach_ids = array(); foreach ($images as $image) { $path = wp_upload_dir(); $cstatus = copy(EASY_F_PLUGIN_PATH . "/demo_data_here/" . $image, $path['path'] . '/' . $image); $filename = $path['path'] . '/' . $image; $wp_filetype = wp_check_filetype(basename($filename), null); $attachment = array('guid' => $path['baseurl'] . _wp_relative_upload_path($filename), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $filename); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); $attach_ids[] = $attach_id; } update_option('easy_demo_images', $attach_ids); }
/** * Save Blavatar files to Media Library * * @param string $title * @param string $filename * @param string $file_type * @param boolean $generate_meta * @return int $attactment_id */ public static function save_attachment($title, $file, $file_type, $generate_meta = true) { $filename = _wp_relative_upload_path($file); $wp_upload_dir = wp_upload_dir(); $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($filename), 'post_mime_type' => $file_type, 'post_title' => $title, 'post_content' => '', 'post_status' => 'inherit'); $attachment_id = wp_insert_attachment($attachment, $filename); if (!function_exists('wp_generate_attachment_metadata')) { // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once ABSPATH . 'wp-admin/includes/image.php'; } if (!$generate_meta) { add_filter('intermediate_image_sizes_advanced', array('Jetpack_Site_Icon', 'only_thumbnail_size')); } // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata($attachment_id, $file); wp_update_attachment_metadata($attachment_id, $attach_data); if (!$generate_meta) { remove_filter('intermediate_image_sizes_advanced', array('Jetpack_Site_Icon', 'only_thumbnail_size')); } return $attachment_id; }
/** * AJAX action export processing */ function pmxe_wp_ajax_wpallexport() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(__('Security check', 'wp_all_export_plugin')); } if (!current_user_can(PMXE_Plugin::$capabilities)) { exit(__('Security check', 'wp_all_export_plugin')); } $input = new PMXE_Input(); $export_id = $input->get('id', 0); if (empty($export_id)) { $export_id = !empty(PMXE_Plugin::$session->update_previous) ? PMXE_Plugin::$session->update_previous : 0; } $wp_uploads = wp_upload_dir(); $export = new PMXE_Export_Record(); $export->getById($export_id); if ($export->isEmpty()) { exit(__('Export is not defined.', 'wp_all_export_plugin')); } $exportOptions = $export->options + PMXE_Plugin::get_default_import_options(); wp_reset_postdata(); XmlExportEngine::$exportOptions = $exportOptions; XmlExportEngine::$is_user_export = $exportOptions['is_user_export']; XmlExportEngine::$is_comment_export = $exportOptions['is_comment_export']; XmlExportEngine::$exportID = $export_id; XmlExportEngine::$exportRecord = $export; $errors = new WP_Error(); $engine = new XmlExportEngine($exportOptions, $errors); $posts_per_page = $exportOptions['records_per_iteration']; if ('advanced' == $exportOptions['export_type']) { if (XmlExportEngine::$is_user_export) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Users', 'wp_all_export_plugin')))); } elseif (XmlExportEngine::$is_comment_export) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Comments', 'wp_all_export_plugin')))); } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); remove_all_filters('posts_clauses'); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); $exportQuery = eval('return new WP_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => ' . $export->exported . ', \'posts_per_page\' => ' . $posts_per_page . ' ));'); remove_filter('posts_where', 'wp_all_export_posts_where'); remove_filter('posts_join', 'wp_all_export_posts_join'); } } else { XmlExportEngine::$post_types = $exportOptions['cpt']; // $is_products_export = ($exportOptions['cpt'] == 'product' and class_exists('WooCommerce')); if (in_array('users', $exportOptions['cpt']) or in_array('shop_customer', $exportOptions['cpt'])) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Users', 'wp_all_export_plugin')))); } elseif (in_array('comments', $exportOptions['cpt'])) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Comments', 'wp_all_export_plugin')))); } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); remove_all_filters('posts_clauses'); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); $exportQuery = new WP_Query(array('post_type' => $exportOptions['cpt'], 'post_status' => 'any', 'orderby' => 'ID', 'order' => 'ASC', 'offset' => $export->exported, 'posts_per_page' => $posts_per_page)); remove_filter('posts_where', 'wp_all_export_posts_where'); remove_filter('posts_join', 'wp_all_export_posts_join'); } } XmlExportEngine::$exportQuery = $exportQuery; $engine->init_additional_data(); // get total founded records if (XmlExportEngine::$is_comment_export) { } else { $foundPosts = !XmlExportEngine::$is_user_export ? $exportQuery->found_posts : $exportQuery->get_total(); $postCount = !XmlExportEngine::$is_user_export ? $exportQuery->post_count : count($exportQuery->get_results()); } // [ \get total founded records ] if (!$export->exported) { $attachment_list = $export->options['attachment_list']; if (!empty($attachment_list)) { foreach ($attachment_list as $attachment) { if (!is_numeric($attachment)) { @unlink($attachment); } } } $exportOptions['attachment_list'] = array(); $export->set(array('options' => $exportOptions))->save(); $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); if ($is_secure_import and !empty($exportOptions['filepath'])) { $exportOptions['filepath'] = ''; } PMXE_Plugin::$session->set('count', $foundPosts); PMXE_Plugin::$session->save_data(); } // if posts still exists then export them if ($postCount) { XmlCsvExport::export(); $export->set(array('exported' => $export->exported + $postCount, 'last_activity' => date('Y-m-d H:i:s')))->save(); } if ($posts_per_page != -1 and $postCount) { wp_send_json(array('export_id' => $export->id, 'queue_export' => false, 'exported' => $export->exported, 'percentage' => ceil($export->exported / $foundPosts * 100), 'done' => false, 'records_per_request' => $exportOptions['records_per_iteration'])); } else { if (file_exists(PMXE_Plugin::$session->file)) { if ($exportOptions['export_to'] == 'xml') { $main_xml_tag = apply_filters('wp_all_export_main_xml_tag', $exportOptions['main_xml_tag'], $export->id); file_put_contents(PMXE_Plugin::$session->file, '</' . $main_xml_tag . '>', FILE_APPEND); $xml_footer = apply_filters('wp_all_export_xml_footer', '', $export->id); if (!empty($xml_footer)) { file_put_contents(PMXE_Plugin::$session->file, $xml_footer, FILE_APPEND); } } $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); if (!$is_secure_import) { if (!$export->isEmpty()) { $wp_filetype = wp_check_filetype(basename(PMXE_Plugin::$session->file), null); $attachment_data = array('guid' => $wp_uploads['baseurl'] . '/' . _wp_relative_upload_path(PMXE_Plugin::$session->file), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename(PMXE_Plugin::$session->file)), 'post_content' => '', 'post_status' => 'inherit'); if (empty($export->attch_id)) { $attach_id = wp_insert_attachment($attachment_data, PMXE_Plugin::$session->file); } elseif ($export->options['creata_a_new_export_file']) { $attach_id = wp_insert_attachment($attachment_data, PMXE_Plugin::$session->file); } else { $attach_id = $export->attch_id; $attachment = get_post($attach_id); if ($attachment) { update_attached_file($attach_id, PMXE_Plugin::$session->file); wp_update_attachment_metadata($attach_id, $attachment_data); } else { $attach_id = wp_insert_attachment($attachment_data, PMXE_Plugin::$session->file); } } if (!in_array($attach_id, $exportOptions['attachment_list'])) { $exportOptions['attachment_list'][] = $attach_id; } $export->set(array('attch_id' => $attach_id, 'options' => $exportOptions))->save(); } } else { $exportOptions['filepath'] = wp_all_export_get_relative_path(PMXE_Plugin::$session->file); if (!$export->isEmpty()) { $export->set(array('options' => $exportOptions))->save(); } } PMXE_Wpallimport::generateImportTemplate($export, PMXE_Plugin::$session->file, PMXE_Plugin::$session->count); } $export->set(array('executing' => 0, 'canceled' => 0, 'iteration' => ++$export->iteration))->save(); do_action('pmxe_after_export', $export->id, $export); $queue_exports = empty($export->parent_id) ? array() : get_option('wp_all_export_queue_' . $export->parent_id); if (!empty($queue_exports) and !empty($export->parent_id)) { array_shift($queue_exports); } if (empty($queue_exports)) { delete_option('wp_all_export_queue_' . (empty($export->parent_id) ? $export->id : $export->parent_id)); } else { update_option('wp_all_export_queue_' . (empty($export->parent_id) ? $export->id : $export->parent_id), $queue_exports); } wp_send_json(array('export_id' => $export->id, 'queue_export' => empty($queue_exports) ? false : $queue_exports[0], 'exported' => $export->exported, 'percentage' => 100, 'done' => true, 'records_per_request' => $exportOptions['records_per_iteration'])); } }