示例#1
0
/**
 * Read the image paths from an attachment's meta data and process each image
 * with ewww_image_optimizer().
 *
 * This method also adds a `ewww_image_optimizer` meta key for use in the media library 
 * and may add a 'converted' and 'orig_file' key if conversion is enabled.
 *
 * Called after `wp_generate_attachment_metadata` is completed.
 */
function ewww_image_optimizer_resize_from_meta_data($meta, $ID = null, $log = true)
{
    global $ewww_debug;
    global $wpdb;
    // may also need to track their attachment ID as well
    $ewww_debug .= "<b>ewww_image_optimizer_resize_from_meta_data()</b><br>";
    $gallery_type = 1;
    $ewww_debug .= "attachment id: {$ID}<br>";
    if (!metadata_exists('post', $ID, '_wp_attachment_metadata')) {
        $ewww_debug .= "this is a newly uploaded image with no metadata yet<br>";
        $new_image = true;
    } else {
        $ewww_debug .= "this image already has metadata, so it is not new<br>";
        $new_image = false;
    }
    list($file_path, $upload_path) = ewww_image_optimizer_attachment_path($meta, $ID);
    // if the attachment has been uploaded via the image store plugin
    if ('ims_image' == get_post_type($ID)) {
        $gallery_type = 6;
    }
    // don't do anything else if the attachment path can't be retrieved
    if (!is_file($file_path)) {
        $ewww_debug .= "could not retrieve path<br>";
        return $meta;
    }
    $ewww_debug .= "retrieved file path: {$file_path}<br>";
    // see if this is a new image and Imsanity resized it (which means it could be already optimized)
    if (!empty($new_image) && function_exists('imsanity_get_max_width_height')) {
        list($maxW, $maxH) = imsanity_get_max_width_height(IMSANITY_SOURCE_LIBRARY);
        list($oldW, $oldH) = getimagesize($file_path);
        list($newW, $newH) = wp_constrain_dimensions($oldW, $oldH, $maxW, $maxH);
        $path_parts = pathinfo($file_path);
        $imsanity_path = trailingslashit($path_parts['dirname']) . $path_parts['filename'] . '-' . $newW . 'x' . $newH . '.' . $path_parts['extension'];
        $ewww_debug .= "imsanity path: {$imsanity_path}<br>";
        $image_size = filesize($file_path);
        $query = $wpdb->prepare("SELECT id,path FROM {$wpdb->ewwwio_images} WHERE path = %s AND image_size = '{$image_size}'", $imsanity_path);
        $optimized_query = $wpdb->get_results($query, ARRAY_A);
        if (!empty($optimized_query)) {
            foreach ($optimized_query as $image) {
                if ($image['path'] != $imsanity_path) {
                    $ewww_debug .= "{$image['path']} does not match {$imsanity_path}, continuing our search<br>";
                } else {
                    $already_optimized = $image;
                }
            }
        }
        if (!empty($already_optimized)) {
            $ewww_debug .= "updating existing record, path: {$file_path}, size: " . $image_size . "<br>";
            // store info on the current image for future reference
            $wpdb->update($wpdb->ewwwio_images, array('path' => $file_path), array('id' => $already_optimized['id']));
        }
    }
    list($file, $msg, $conv, $original) = ewww_image_optimizer($file_path, $gallery_type, false, $new_image, true);
    // update the optimization results in the metadata
    $meta['ewww_image_optimizer'] = $msg;
    if ($file === false) {
        return $meta;
    }
    $meta['file'] = str_replace($upload_path, '', $file);
    // if the file was converted
    if ($conv) {
        // update the filename in the metadata
        $new_file = substr($meta['file'], 0, -3);
        // change extension
        $new_ext = substr($file, -3);
        $meta['file'] = $new_file . $new_ext;
        $ewww_debug .= "image was converted<br>";
        // if we don't already have the update attachment filter
        if (FALSE === has_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment')) {
            // add the update attachment filter
            add_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment', 10, 2);
        }
        // store the conversion status in the metadata
        $meta['converted'] = 1;
        // store the old filename in the database
        $meta['orig_file'] = $original;
    } else {
        remove_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment', 10);
    }
    // resized versions, so we can continue
    if (isset($meta['sizes'])) {
        $disabled_sizes = ewww_image_optimizer_get_option('ewww_image_optimizer_disable_resizes_opt');
        $ewww_debug .= "disabled sizes: " . print_r($disabled_sizes, true) . "<br>";
        $ewww_debug .= "processing resizes<br>";
        // meta sizes don't contain a path, so we calculate one
        if ($gallery_type === 6) {
            $base_ims_dir = dirname($file_path) . '/_resized/';
        }
        $base_dir = dirname($file_path) . '/';
        // process each resized version
        $processed = array();
        foreach ($meta['sizes'] as $size => $data) {
            $ewww_debug .= "processing size: {$size}<br>";
            if (preg_match('/webp/', $size)) {
                continue;
            }
            if (!empty($disabled_sizes[$size])) {
                continue;
            }
            if ($gallery_type === 6) {
                $base_dir = dirname($file_path) . '/';
                $image_path = $base_dir . $data['file'];
                $ims_path = $base_ims_dir . $data['file'];
                if (file_exists($ims_path)) {
                    $ewww_debug .= "ims resize already exists, wahoo<br>";
                    $ewww_debug .= "ims path: {$ims_path}<br>";
                    $image_size = filesize($ims_path);
                    $query = $wpdb->prepare("SELECT id,path FROM {$wpdb->ewwwio_images} WHERE path = %s AND image_size = '{$image_size}'", $image_path);
                    $optimized_query = $wpdb->get_results($query, ARRAY_A);
                    if (!empty($optimized_query)) {
                        foreach ($optimized_query as $image) {
                            if ($image['path'] != $image_path) {
                                $ewww_debug .= "{$image['path']} does not match {$image_path}, continuing our search<br>";
                            } else {
                                $already_optimized = $image;
                            }
                        }
                    }
                    if (!empty($already_optimized)) {
                        $ewww_debug .= "updating existing record, path: {$ims_path}, size: " . $image_size . "<br>";
                        // store info on the current image for future reference
                        $wpdb->update($wpdb->ewwwio_images, array('path' => $ims_path), array('id' => $already_optimized['id']));
                        $base_dir = $base_ims_dir;
                    }
                }
            }
            // initialize $dup_size
            $dup_size = false;
            // check through all the sizes we've processed so far
            foreach ($processed as $proc => $scan) {
                // if a previous resize had identical dimensions
                if ($scan['height'] == $data['height'] && $scan['width'] == $data['width']) {
                    // found a duplicate resize
                    $dup_size = true;
                    // point this resize at the same image as the previous one
                    $meta['sizes'][$size]['file'] = $meta['sizes'][$proc]['file'];
                    // and tell the user we didn't do any further optimization
                    $meta['sizes'][$size]['ewww_image_optimizer'] = __('No savings', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                }
            }
            // if this is a unique size
            if (!$dup_size) {
                $resize_path = $base_dir . $data['file'];
                // run the optimization and store the results
                list($optimized_file, $results, $resize_conv, $original) = ewww_image_optimizer($resize_path, $gallery_type, $conv, $new_image);
                // if the resize was converted, store the result and the original filename in the metadata for later recovery
                if ($resize_conv) {
                    // if we don't already have the update attachment filter
                    if (FALSE === has_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment')) {
                        // add the update attachment filter
                        add_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment', 10, 2);
                    }
                    $meta['sizes'][$size]['converted'] = 1;
                    $meta['sizes'][$size]['orig_file'] = str_replace($base_dir, '', $original);
                    $ewww_debug .= "original filename: {$original}<br>";
                    $meta['sizes'][$size]['real_orig_file'] = str_replace($base_dir, '', $resize_path);
                    $ewww_debug .= "resize path: {$resize_path}<br>";
                }
                if ($optimized_file !== false) {
                    // update the filename
                    $meta['sizes'][$size]['file'] = str_replace($base_dir, '', $optimized_file);
                }
                // update the optimization results
                $meta['sizes'][$size]['ewww_image_optimizer'] = $results;
                // optimize retina images, if they exist
                if (function_exists('wr2x_get_retina') && ($retina_path = wr2x_get_retina($resize_path))) {
                    ewww_image_optimizer($retina_path, 4, false, false);
                }
            }
            // store info on the sizes we've processed, so we can check the list for duplicate sizes
            $processed[$size]['width'] = $data['width'];
            $processed[$size]['height'] = $data['height'];
        }
    }
    if (!empty($new_image)) {
        $meta = ewww_image_optimizer_update_attachment_metadata($meta, $ID);
    }
    if (!preg_match('/' . __('Previously Optimized', EWWW_IMAGE_OPTIMIZER_DOMAIN) . '/', $meta['ewww_image_optimizer']) && class_exists('Amazon_S3_And_CloudFront')) {
        global $as3cf;
        if (method_exists($as3cf, 'wp_update_attachment_metadata')) {
            $as3cf->wp_update_attachment_metadata($meta, $ID);
        } elseif (method_exists($as3cf, 'wp_generate_attachment_metadata')) {
            $as3cf->wp_generate_attachment_metadata($meta, $ID);
        }
        $ewww_debug .= 'uploading to Amazon S3<br>';
    }
    if (class_exists('Cloudinary') && Cloudinary::config_get("api_secret") && ewww_image_optimizer_get_option('ewww_image_optimizer_enable_cloudinary') && !empty($new_image)) {
        try {
            $result = CloudinaryUploader::upload($file, array('use_filename' => True));
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        if (!empty($error)) {
            $ewww_debug .= "Cloudinary error: {$error}<br>";
        } else {
            $ewww_debug .= "successfully uploaded to Cloudinary<br>";
            // register the attachment in the database as a cloudinary attachment
            $old_url = wp_get_attachment_url($ID);
            wp_update_post(array('ID' => $ID, 'guid' => $result['url']));
            update_attached_file($ID, $result['url']);
            $meta['cloudinary'] = TRUE;
            $errors = array();
            // update the image location for the attachment
            CloudinaryPlugin::update_image_src_all($ID, $result, $old_url, $result["url"], TRUE, $errors);
            if (count($errors) > 0) {
                $ewww_debug .= "Cannot migrate the following posts:<br>" . implode("<br>", $errors);
            }
        }
    }
    if ($log) {
        ewww_image_optimizer_debug_log();
    }
    ewwwio_memory(__FUNCTION__);
    // send back the updated metadata
    return $meta;
}
示例#2
0
/**
 * Read the image paths from an attachment's meta data and process each image
 * with ewww_image_optimizer().
 *
 * This method also adds a `ewww_image_optimizer` meta key for use in the media library 
 * and may add a 'converted' and 'orig_file' key if conversion is enabled.
 *
 * Called after `wp_generate_attachment_metadata` is completed.
 */
function ewww_image_optimizer_resize_from_meta_data($meta, $ID = null, $log = true, $background_new = false)
{
    ewwwio_debug_message('<b>' . __FUNCTION__ . '()</b>');
    if (!is_array($meta) && empty($meta)) {
        $meta = array();
    } elseif (!is_array($meta)) {
        if (is_string($meta) && is_int($ID) && 'processing' == $meta) {
            ewwwio_debug_message("attempting to rebuild attachment meta for {$ID}");
            $new_meta = ewww_image_optimizer_rebuild_meta($ID);
            if (!is_array($new_meta)) {
                ewwwio_debug_message('attempt to rebuild attachment meta failed');
                return $meta;
            } else {
                $meta = $new_meta;
            }
        } else {
            ewwwio_debug_message('attachment meta is not a usable array');
            return $meta;
        }
    } elseif (is_array($meta) && !empty($meta[0]) && 'processing' == $meta[0]) {
        ewwwio_debug_message("attempting to rebuild attachment meta for {$ID}");
        $new_meta = ewww_image_optimizer_rebuild_meta($ID);
        if (!is_array($new_meta)) {
            ewwwio_debug_message('attempt to rebuild attachment meta failed');
            return $meta;
        } else {
            $meta = $new_meta;
        }
    }
    global $wpdb;
    global $ewww_defer;
    global $ewww_new_image;
    $gallery_type = 1;
    ewwwio_debug_message("attachment id: {$ID}");
    session_write_close();
    //if ( ! metadata_exists( 'post', $ID, '_wp_attachment_metadata' ) ) {
    if (!empty($ewww_new_image)) {
        ewwwio_debug_message('this is a newly uploaded image with no metadata yet');
        $new_image = true;
    } else {
        ewwwio_debug_message('this image already has metadata, so it is not new');
        $new_image = false;
    }
    list($file_path, $upload_path) = ewww_image_optimizer_attachment_path($meta, $ID);
    // if the attachment has been uploaded via the image store plugin
    if ('ims_image' == get_post_type($ID)) {
        $gallery_type = 6;
    }
    if (!$new_image && class_exists('Amazon_S3_And_CloudFront') && strpos($file_path, 's3') === 0) {
        ewww_image_optimizer_check_table_as3cf($meta, $ID, $file_path);
    }
    // if the local file is missing and we have valid metadata, see if we can fetch via CDN
    if (!is_file($file_path) || strpos($file_path, 's3') === 0) {
        $file_path = ewww_image_optimizer_remote_fetch($ID, $meta);
        if (!$file_path) {
            ewwwio_debug_message('could not retrieve path');
            $meta['ewww_image_optimizer'] = __('Could not find image', EWWW_IMAGE_OPTIMIZER_DOMAIN);
            return $meta;
        }
    }
    ewwwio_debug_message("retrieved file path: {$file_path}");
    $type = ewww_image_optimizer_mimetype($file_path, 'i');
    $supported_types = array('image/jpeg', 'image/png', 'image/gif', 'application/pdf');
    if (!in_array($type, $supported_types)) {
        ewwwio_debug_message("mimetype not supported: {$ID}");
        return $meta;
    }
    // see if this is a new image and Imsanity resized it (which means it could be already optimized)
    if (!empty($new_image) && function_exists('imsanity_get_max_width_height')) {
        list($maxW, $maxH) = imsanity_get_max_width_height(IMSANITY_SOURCE_LIBRARY);
        list($oldW, $oldH) = getimagesize($file_path);
        list($newW, $newH) = wp_constrain_dimensions($oldW, $oldH, $maxW, $maxH);
        $path_parts = pathinfo($file_path);
        $imsanity_path = trailingslashit($path_parts['dirname']) . $path_parts['filename'] . '-' . $newW . 'x' . $newH . '.' . $path_parts['extension'];
        ewwwio_debug_message("imsanity path: {$imsanity_path}");
        $image_size = ewww_image_optimizer_filesize($file_path);
        $already_optimized = ewww_image_optimizer_find_already_optimized($imsanity_path);
        if (is_array($already_optimized)) {
            ewwwio_debug_message("updating existing record, path: {$file_path}, size: " . $image_size);
            // store info on the current image for future reference
            $wpdb->update($wpdb->ewwwio_images, array('path' => $file_path), array('id' => $already_optimized['id']));
        }
    }
    if ((!empty($new_image) || ewww_image_optimizer_get_option('ewww_image_optimizer_resize_existing')) && !function_exists('imsanity_get_max_width_height')) {
        $new_dimensions = ewww_image_optimizer_resize_upload($file_path);
        if (is_array($new_dimensions)) {
            $meta['width'] = $new_dimensions[0];
            $meta['height'] = $new_dimensions[1];
        }
    }
    if ($ewww_defer && !ewww_image_optimizer_detect_wpsf_location_lock()) {
        add_filter('http_headers_useragent', 'ewww_image_optimizer_cloud_useragent', PHP_INT_MAX);
        global $ewwwio_media_background;
        if (!class_exists('WP_Background_Process')) {
            require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'background.php';
        }
        if (!is_object($ewwwio_media_background)) {
            $ewwwio_media_background = new EWWWIO_Media_Background_Process();
        }
        ewwwio_debug_message("backgrounding optimization for {$ID}");
        $ewwwio_media_background->push_to_queue(array('id' => $ID, 'new' => $new_image, 'type' => $type));
        $ewwwio_media_background->save()->dispatch();
        set_transient('ewwwio-background-in-progress-' . $ID, true, 24 * HOUR_IN_SECONDS);
        ewww_image_optimizer_debug_log();
        return $meta;
    }
    if ($background_new) {
        $new_image = true;
    }
    if (ewww_image_optimizer_test_parallel_opt($ID) && $type != 'application/pdf') {
        ewwwio_debug_message('running in parallel');
        $parallel_opt = true;
    } else {
        ewwwio_debug_message('running in sequence');
        $parallel_opt = false;
    }
    $parallel_sizes = array();
    if ($parallel_opt) {
        touch($file_path . '.processing');
        if (!empty($_REQUEST['ewww_force'])) {
            $force = true;
        } else {
            $force = false;
        }
        add_filter('http_headers_useragent', 'ewww_image_optimizer_cloud_useragent', PHP_INT_MAX);
        global $ewwwio_async_optimize_media;
        if (!class_exists('WP_Background_Process')) {
            require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'background.php';
        }
        if (!is_object($ewwwio_async_optimize_media)) {
            $ewwwio_async_optimize_media = new EWWWIO_Async_Request();
        }
        $async_path = str_replace($upload_path, '', $file_path);
        $ewwwio_async_optimize_media->data(array('ewwwio_path' => $async_path, 'ewwwio_size' => 'full', 'ewww_force' => $force))->dispatch();
        $parallel_sizes['full'] = $file_path;
    } else {
        list($file, $msg, $conv, $original) = ewww_image_optimizer($file_path, $gallery_type, false, $new_image, true);
        // update the optimization results in the metadata
        $meta['ewww_image_optimizer'] = $msg;
        if ($file === false) {
            return $meta;
        }
        $meta['file'] = str_replace($upload_path, '', $file);
        // if the file was converted
        if ($conv) {
            // update the filename in the metadata
            $new_file = substr($meta['file'], 0, -3);
            // change extension
            $new_ext = substr($file, -3);
            $meta['file'] = $new_file . $new_ext;
            ewwwio_debug_message('image was converted');
            // if we don't already have the update attachment filter
            if (FALSE === has_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment')) {
                // add the update attachment filter
                add_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment', 10, 2);
            }
            // store the conversion status in the metadata
            $meta['converted'] = 1;
            // store the old filename in the database
            $meta['orig_file'] = $original;
        } else {
            remove_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment', 10);
        }
    }
    ewww_image_optimizer_hidpi_optimize($file_path);
    // resized versions, so we can continue
    if (isset($meta['sizes'])) {
        $disabled_sizes = ewww_image_optimizer_get_option('ewww_image_optimizer_disable_resizes_opt');
        //		ewwwio_debug_message( "disabled sizes: " . print_r( $disabled_sizes, true ) );
        ewwwio_debug_message('processing resizes');
        // meta sizes don't contain a path, so we calculate one
        if ($gallery_type === 6) {
            $base_ims_dir = trailingslashit(dirname($file_path)) . '_resized/';
        }
        $base_dir = trailingslashit(dirname($file_path));
        // process each resized version
        $processed = array();
        foreach ($meta['sizes'] as $size => $data) {
            ewwwio_debug_message("processing size: {$size}");
            if (strpos($size, 'webp') === 0) {
                continue;
            }
            if (!empty($disabled_sizes[$size])) {
                continue;
            }
            if ($gallery_type === 6) {
                $base_dir = dirname($file_path) . '/';
                $image_path = $base_dir . $data['file'];
                $ims_path = $base_ims_dir . $data['file'];
                if (file_exists($ims_path)) {
                    ewwwio_debug_message('ims resize already exists, wahoo');
                    ewwwio_debug_message("ims path: {$ims_path}");
                    $image_size = ewww_image_optimizer_filesize($ims_path);
                    $already_optimized = ewww_image_optimizer_find_already_optimized($image_path);
                    if (is_array($already_optimized)) {
                        ewwwio_debug_message("updating existing record, path: {$ims_path}, size: " . $image_size);
                        // store info on the current image for future reference
                        $wpdb->update($wpdb->ewwwio_images, array('path' => $ims_path), array('id' => $already_optimized['id']));
                    }
                    $base_dir = $base_ims_dir;
                }
            }
            // initialize $dup_size
            $dup_size = false;
            // check through all the sizes we've processed so far
            foreach ($processed as $proc => $scan) {
                // if a previous resize had identical dimensions
                if ($scan['height'] == $data['height'] && $scan['width'] == $data['width']) {
                    // found a duplicate resize
                    $dup_size = true;
                    // point this resize at the same image as the previous one
                    $meta['sizes'][$size]['file'] = $meta['sizes'][$proc]['file'];
                    // and tell the user we didn't do any further optimization
                    $meta['sizes'][$size]['ewww_image_optimizer'] = __('No savings', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                }
            }
            // if this is a unique size
            if (!$dup_size) {
                $resize_path = $base_dir . $data['file'];
                // run the optimization and store the results
                if ($parallel_opt) {
                    touch($resize_path . '.processing');
                    $async_path = str_replace($upload_path, '', $resize_path);
                    add_filter('http_headers_useragent', 'ewww_image_optimizer_cloud_useragent', PHP_INT_MAX);
                    $ewwwio_async_optimize_media->data(array('ewwwio_path' => $async_path, 'ewwwio_size' => $size, 'ewww_force' => $force))->dispatch();
                    $parallel_sizes[$size] = $resize_path;
                } else {
                    list($optimized_file, $results, $resize_conv, $original) = ewww_image_optimizer($resize_path, $gallery_type, $conv, $new_image);
                    // if the resize was converted, store the result and the original filename in the metadata for later recovery
                    if ($resize_conv) {
                        // if we don't already have the update attachment filter
                        if (FALSE === has_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment')) {
                            // add the update attachment filter
                            add_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_attachment', 10, 2);
                        }
                        $meta['sizes'][$size]['converted'] = 1;
                        $meta['sizes'][$size]['orig_file'] = str_replace($base_dir, '', $original);
                        ewwwio_debug_message("original filename: {$original}");
                        $meta['sizes'][$size]['real_orig_file'] = str_replace($base_dir, '', $resize_path);
                        ewwwio_debug_message("resize path: {$resize_path}");
                    }
                    if ($optimized_file !== false) {
                        // update the filename
                        $meta['sizes'][$size]['file'] = str_replace($base_dir, '', $optimized_file);
                    }
                    // update the optimization results
                    $meta['sizes'][$size]['ewww_image_optimizer'] = $results;
                }
                // optimize retina images, if they exist
                if (function_exists('wr2x_get_retina') && ($retina_path = wr2x_get_retina($resize_path))) {
                    if ($parallel_opt) {
                        add_filter('http_headers_useragent', 'ewww_image_optimizer_cloud_useragent', PHP_INT_MAX);
                        $async_path = str_replace($upload_path, '', $retina_path);
                        $ewwwio_async_optimize_media->data(array('path' => $async_path, 'size' => '', 'ewww_force' => $force))->dispatch();
                    } else {
                        ewww_image_optimizer($retina_path);
                    }
                } else {
                    ewww_image_optimizer_hidpi_optimize($resize_path);
                }
            }
            // store info on the sizes we've processed, so we can check the list for duplicate sizes
            $processed[$size]['width'] = $data['width'];
            $processed[$size]['height'] = $data['height'];
        }
    }
    if (!empty($new_dimensions)) {
        $prev_string = " - " . __('Previously Optimized', EWWW_IMAGE_OPTIMIZER_DOMAIN);
        $meta['ewww_image_optimizer'] = preg_replace("/{$prev_string}/", '', $meta['ewww_image_optimizer']);
    }
    // process size from a custom theme
    if (isset($meta['image_meta']['resized_images'])) {
        $imagemeta_resize_pathinfo = pathinfo($file_path);
        $imagemeta_resize_path = '';
        foreach ($meta['image_meta']['resized_images'] as $imagemeta_resize) {
            $imagemeta_resize_path = $imagemeta_resize_pathinfo['dirname'] . '/' . $imagemeta_resize_pathinfo['filename'] . '-' . $imagemeta_resize . '.' . $imagemeta_resize_pathinfo['extension'];
            if ($parallel_opt) {
                add_filter('http_headers_useragent', 'ewww_image_optimizer_cloud_useragent', PHP_INT_MAX);
                $async_path = str_replace($upload_path, '', $imagemeta_resize_path);
                $ewwwio_async_optimize_media->data(array('path' => $async_path, 'size' => '', 'ewww_force' => $force))->dispatch();
            } else {
                ewww_image_optimizer($imagemeta_resize_path);
            }
        }
    }
    // and another custom theme
    if (isset($meta['custom_sizes'])) {
        $custom_sizes_pathinfo = pathinfo($file_path);
        $custom_size_path = '';
        foreach ($meta['custom_sizes'] as $custom_size) {
            $custom_size_path = $custom_sizes_pathinfo['dirname'] . '/' . $custom_size['file'];
            if ($parallel_opt) {
                add_filter('http_headers_useragent', 'ewww_image_optimizer_cloud_useragent', PHP_INT_MAX);
                $async_path = str_replace($upload_path, '', $custom_size_path);
                $ewwwio_async_optimize_media->data(array('path' => $async_path, 'size' => '', 'ewww_force' => $force))->dispatch();
            } else {
                ewww_image_optimizer($custom_size_path);
            }
        }
    }
    // OK, here we start checking to see what sizes are done, and populate the metadata with the results
    $processing = true;
    $timer = apply_filters('ewww_image_optimizer_background_timer_init', 1);
    $increment = apply_filters('ewww_image_optimizer_background_timer_increment', 1);
    while ($parallel_opt && $processing) {
        $processing = false;
        foreach ($parallel_sizes as $size => $filename) {
            if (is_file($filename . '.processing')) {
                ewwwio_debug_message("still processing {$size}");
                $processing = true;
                continue;
            }
            if ($size == 'full') {
                $image = ewww_image_optimizer_find_already_optimized($filename);
                $meta['ewww_image_optimizer'] = $image['results'];
                unset($parallel_sizes[$size]);
                ewwwio_debug_message('got results for full size');
            } else {
                $image = ewww_image_optimizer_find_already_optimized($filename);
                $meta['sizes'][$size]['ewww_image_optimizer'] = $image['results'];
                unset($parallel_sizes[$size]);
                ewwwio_debug_message("got results for {$size} size");
            }
        }
        if ($processing) {
            ewwwio_debug_message("sleeping for {$timer} seconds");
            sleep($timer);
            $timer += $increment;
            clearstatcache();
        }
        if ($timer > 35) {
            foreach ($parallel_sizes as $filename) {
                if (is_file($filename . '.processing')) {
                    unlink($filename . '.processing');
                }
            }
            $meta['processing'] = 1;
            ewww_image_optimizer_debug_log();
            return $meta;
        }
        //		ewww_image_optimizer_debug_log();
    }
    unset($meta['processing']);
    if (!empty($new_image)) {
        $meta = ewww_image_optimizer_update_attachment_metadata($meta, $ID);
    }
    if (!preg_match('/' . __('Previously Optimized', EWWW_IMAGE_OPTIMIZER_DOMAIN) . '/', $meta['ewww_image_optimizer']) && class_exists('Amazon_S3_And_CloudFront')) {
        global $as3cf;
        if (method_exists($as3cf, 'wp_update_attachment_metadata')) {
            $as3cf->wp_update_attachment_metadata($meta, $ID);
        } elseif (method_exists($as3cf, 'wp_generate_attachment_metadata')) {
            $as3cf->wp_generate_attachment_metadata($meta, $ID);
        }
        ewwwio_debug_message('uploading to Amazon S3');
    }
    if (!preg_match('/' . __('Previously Optimized', EWWW_IMAGE_OPTIMIZER_DOMAIN) . '/', $meta['ewww_image_optimizer']) && class_exists('DreamSpeed_Services')) {
        global $dreamspeed;
        $dreamspeed->wp_generate_attachment_metadata($meta, $ID);
        ewwwio_debug_message('uploading to Dreamspeed');
    }
    if (class_exists('Cloudinary') && Cloudinary::config_get("api_secret") && ewww_image_optimizer_get_option('ewww_image_optimizer_enable_cloudinary') && !empty($new_image)) {
        try {
            $result = CloudinaryUploader::upload($file, array('use_filename' => true));
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        if (!empty($error)) {
            ewwwio_debug_message("Cloudinary error: {$error}");
        } else {
            ewwwio_debug_message('successfully uploaded to Cloudinary');
            // register the attachment in the database as a cloudinary attachment
            $old_url = wp_get_attachment_url($ID);
            wp_update_post(array('ID' => $ID, 'guid' => $result['url']));
            update_attached_file($ID, $result['url']);
            $meta['cloudinary'] = TRUE;
            $errors = array();
            // update the image location for the attachment
            CloudinaryPlugin::update_image_src_all($ID, $result, $old_url, $result['url'], TRUE, $errors);
            if (count($errors) > 0) {
                ewwwio_debug_message("Cannot migrate the following posts:");
                foreach ($errors as $error) {
                    ewwwio_debug_message($error);
                }
            }
        }
    }
    if ($log) {
        ewww_image_optimizer_debug_log();
    }
    ewwwio_memory(__FUNCTION__);
    // send back the updated metadata
    return $meta;
}