Ejemplo n.º 1
0
 function ewww_added_new_image($image, $storage = null)
 {
     global $ewww_debug;
     $ewww_debug .= "<b>ewww_added_new_image()</b><br>";
     if (empty($storage)) {
         // creating the 'registry' object for working with nextgen
         $registry = C_Component_Registry::get_instance();
         // creating a database storage object from the 'registry' object
         $storage = $registry->get_utility('I_Gallery_Storage');
     }
     // find the image id
     if (is_array($image)) {
         $image_id = $image['id'];
         $image = $storage->object->_image_mapper->find($image_id, TRUE);
     } else {
         $image_id = $storage->object->_get_image_id($image);
     }
     $ewww_debug .= "image id: {$image_id}<br>";
     // get an array of sizes available for the $image
     $sizes = $storage->get_image_sizes();
     // run the optimizer on the image for each $size
     foreach ($sizes as $size) {
         if ($size === 'full') {
             $full_size = true;
         } else {
             $full_size = false;
         }
         // get the absolute path
         $file_path = $storage->get_image_abspath($image, $size);
         $ewww_debug .= "optimizing (nextgen): {$file_path}<br>";
         // optimize the image and grab the results
         $res = ewww_image_optimizer($file_path, 2, false, false, $full_size);
         $ewww_debug .= "results " . $res[1] . "<br>";
         // only if we're dealing with the full-size original
         if ($size === 'full') {
             // update the metadata for the optimized image
             $image->meta_data['ewww_image_optimizer'] = $res[1];
         } else {
             $image->meta_data[$size]['ewww_image_optimizer'] = $res[1];
         }
         nggdb::update_image_meta($image_id, $image->meta_data);
         $ewww_debug .= 'storing results for full size image<br>';
     }
     ewww_image_optimizer_debug_log();
     return $image;
 }
Ejemplo n.º 2
0
function ewww_image_optimizer_bulk_next($delay, $attachments)
{
    // toggle the resume flag to indicate an operation is in progress
    update_option('ewww_image_optimizer_bulk_ngg_resume', 'true');
    // need this file to work with metadata
    require_once WP_CONTENT_DIR . '/plugins/nextcellent-gallery-nextgen-legacy/lib/meta.php';
    foreach ($attachments as $id) {
        sleep($delay);
        // find out what time we started, in microseconds
        $started = microtime(true);
        // get the metadata
        $meta = new nggMeta($id);
        // retrieve the filepath
        $file_path = $meta->image->imagePath;
        // run the optimizer on the current image
        $fres = ewww_image_optimizer($file_path, 2, false, false, true);
        // update the metadata of the optimized image
        nggdb::update_image_meta($id, array('ewww_image_optimizer' => $fres[1]));
        // output the results of the optimization
        WP_CLI::line(__('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . $meta->image->filename);
        WP_CLI::line(sprintf(__('Full size - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN), html_entity_decode($fres[1])));
        // get the filepath of the thumbnail image
        $thumb_path = $meta->image->thumbPath;
        // run the optimization on the thumbnail
        $tres = ewww_image_optimizer($thumb_path, 2, false, true);
        // output the results of the thumb optimization
        WP_CLI::line(sprintf(__('Thumbnail - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN), html_entity_decode($tres[1])));
        // outupt how much time we spent
        $elapsed = microtime(true) - $started;
        WP_CLI::line(sprintf(__('Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN), $elapsed));
        // get the list of attachments remaining from the db
        $attachments = get_option('ewww_image_optimizer_bulk_ngg_attachments');
        // remove the first item
        if (!empty($attachments)) {
            array_shift($attachments);
        }
        // and store the list back in the db
        update_option('ewww_image_optimizer_bulk_ngg_attachments', $attachments, false);
    }
    // reset all the bulk options in the db
    update_option('ewww_image_optimizer_bulk_ngg_resume', '');
    update_option('ewww_image_optimizer_bulk_ngg_attachments', '', false);
    // and let the user know we are done
    WP_CLI::success(__('Finished Optimization!', EWWW_IMAGE_OPTIMIZER_DOMAIN));
}
 function ewww_flag_bulk_loop()
 {
     if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'ewww-image-optimizer-bulk') || !current_user_can('edit_others_posts')) {
         wp_die(__('Cheatin&#8217; eh?', EWWW_IMAGE_OPTIMIZER_DOMAIN));
     }
     if (!empty($_REQUEST['sleep'])) {
         sleep($_REQUEST['sleep']);
     }
     // need this file to work with flag meta
     require_once WP_CONTENT_DIR . '/plugins/flash-album-gallery/lib/meta.php';
     // record the starting time for the current image (in microseconds)
     $started = microtime(true);
     $id = $_POST['attachment'];
     // get the image meta for the current ID
     $meta = new flagMeta($id);
     $file_path = $meta->image->imagePath;
     // optimize the full-size version
     $fres = ewww_image_optimizer($file_path, 3, false, false, ewww_image_optimizer_get_option('ewww_image_optimizer_lossy_skip_full'));
     $meta->image->meta_data['ewww_image_optimizer'] = $fres[1];
     // let the user know what happened
     printf("<p>" . __('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " <strong>%s</strong><br>", esc_html($meta->image->filename));
     printf(__('Full size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $fres[1]);
     $thumb_path = $meta->image->thumbPath;
     // optimize the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 3, false, true);
     $meta->image->meta_data['thumbnail']['ewww_image_optimizer'] = $tres[1];
     // and let the user know the results
     printf(__('Thumbnail – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $tres[1]);
     flagdb::update_image_meta($id, $meta->image->meta_data);
     // determine how much time the image took to process
     $elapsed = microtime(true) - $started;
     // and output it to the user
     printf(__('Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "</p>", $elapsed);
     // retrieve the list of attachments left to work on
     $attachments = get_option('ewww_image_optimizer_bulk_flag_attachments');
     // take the first image off the list
     if (!empty($attachments)) {
         array_shift($attachments);
     }
     // and send the list back to the db
     update_option('ewww_image_optimizer_bulk_flag_attachments', $attachments);
     die;
 }
Ejemplo n.º 4
0
 function ewww_flag_bulk_loop()
 {
     global $ewww_defer;
     $ewww_defer = false;
     $output = array();
     $permissions = apply_filters('ewww_image_optimizer_bulk_permissions', '');
     if (!wp_verify_nonce($_REQUEST['ewww_wpnonce'], 'ewww-image-optimizer-bulk') || !current_user_can($permissions)) {
         $output['error'] = esc_html__('Access token has expired, please reload the page.', EWWW_IMAGE_OPTIMIZER_DOMAIN);
         echo json_encode($output);
         die;
     }
     session_write_close();
     // find out if our nonce is on it's last leg/tick
     $tick = wp_verify_nonce($_REQUEST['ewww_wpnonce'], 'ewww-image-optimizer-bulk');
     if ($tick === 2) {
         $output['new_nonce'] = wp_create_nonce('ewww-image-optimizer-bulk');
     } else {
         $output['new_nonce'] = '';
     }
     // need this file to work with flag meta
     require_once WP_CONTENT_DIR . '/plugins/flash-album-gallery/lib/meta.php';
     // record the starting time for the current image (in microseconds)
     $started = microtime(true);
     // retrieve the list of attachments left to work on
     $attachments = get_option('ewww_image_optimizer_bulk_flag_attachments');
     $id = array_shift($attachments);
     // get the image meta for the current ID
     $meta = new flagMeta($id);
     $file_path = $meta->image->imagePath;
     // optimize the full-size version
     $fres = ewww_image_optimizer($file_path, 3, false, false, true);
     $ewww_status = get_transient('ewww_image_optimizer_cloud_status');
     if (!empty($ewww_status) && preg_match('/exceeded/', $ewww_status)) {
         $output['error'] = esc_html__('License Exceeded', EWWW_IMAGE_OPTIMIZER_DOMAIN);
         echo json_encode($output);
         die;
     }
     $meta->image->meta_data['ewww_image_optimizer'] = $fres[1];
     // let the user know what happened
     $output['results'] = sprintf("<p>" . esc_html__('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " <strong>%s</strong><br>", esc_html($meta->image->filename));
     $output['results'] .= sprintf(esc_html__('Full size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", esc_html($fres[1]));
     if (!empty($meta->image->meta_data['webview'])) {
         // determine path of the webview
         $web_path = $meta->image->webimagePath;
         $wres = ewww_image_optimizer($web_path, 3, false, true);
         $meta->image->meta_data['webview']['ewww_image_optimizer'] = $wres[1];
         $output['results'] .= sprintf(esc_html__('Optimized size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", esc_html($wres[1]));
     }
     $thumb_path = $meta->image->thumbPath;
     // optimize the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 3, false, true);
     $meta->image->meta_data['thumbnail']['ewww_image_optimizer'] = $tres[1];
     // and let the user know the results
     $output['results'] .= sprintf(esc_html__('Thumbnail – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", esc_html($tres[1]));
     flagdb::update_image_meta($id, $meta->image->meta_data);
     // determine how much time the image took to process
     $elapsed = microtime(true) - $started;
     // and output it to the user
     $output['results'] .= sprintf(esc_html__('Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "</p>", $elapsed);
     // send the list back to the db
     update_option('ewww_image_optimizer_bulk_flag_attachments', $attachments, false);
     if (!empty($attachments)) {
         $next_attachment = array_shift($attachments);
         $next_file = $this->ewww_flag_bulk_filename($next_attachment);
         $loading_image = plugins_url('/images/wpspin.gif', __FILE__);
         if ($next_file) {
             $output['next_file'] = "<p>" . esc_html__('Optimizing', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " <b>{$next_file}</b>&nbsp;<img src='{$loading_image}' alt='loading'/></p>";
         } else {
             $output['next_file'] = "<p>" . esc_html__('Optimizing', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "&nbsp;<img src='{$loading_image}' alt='loading'/></p>";
         }
     }
     echo json_encode($output);
     die;
 }
Ejemplo n.º 5
0
function wppa_optimize_image_file($file)
{
    if (!wppa_switch('optimize_new')) {
        return;
    }
    if (function_exists('ewww_image_optimizer')) {
        ewww_image_optimizer($file, 4, false, false, false);
    }
}
 function ewww_ngg_optimize($id)
 {
     // retrieve the metadata for the image
     $meta = new nggMeta($id);
     // retrieve the image path
     $file_path = $meta->image->imagePath;
     // run the optimizer on the current image
     $fres = ewww_image_optimizer($file_path, 2, false, false, true);
     // update the metadata for the optimized image
     nggdb::update_image_meta($id, array('ewww_image_optimizer' => $fres[1]));
     // get the filepath of the thumbnail image
     $thumb_path = $meta->image->thumbPath;
     // run the optimization on the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 2, false, true);
     return array($fres, $tres);
 }
 function ewww_flag_bulk_loop()
 {
     if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'ewww-image-optimizer-bulk') || !current_user_can('edit_others_posts')) {
         wp_die(__('Cheatin&#8217; eh?'));
     }
     // need this file to work with flag meta
     require_once WP_CONTENT_DIR . '/plugins/flash-album-gallery/lib/meta.php';
     // record the starting time for the current image (in microseconds)
     $started = microtime(true);
     $id = $_POST['attachment'];
     // get the image meta for the current ID
     $meta = new flagMeta($id);
     $file_path = $meta->image->imagePath;
     // optimize the full-size version
     $fres = ewww_image_optimizer($file_path, 3, false, false);
     // and store the results in the metadata
     flagdb::update_image_meta($id, array('ewww_image_optimizer' => $fres[1]));
     // let the user know what happened
     printf("<p>Optimized image: <strong>%s</strong><br>", esc_html($meta->image->filename));
     printf("Full size – %s<br>", $fres[1]);
     $thumb_path = $meta->image->thumbPath;
     // optimize the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 3, false, true);
     // and let the user know the results
     printf("Thumbnail – %s<br>", $tres[1]);
     // determine how much time the image took to process
     $elapsed = microtime(true) - $started;
     // and output it to the user
     echo "Elapsed: " . round($elapsed, 3) . " seconds</p>";
     // retrieve the list of attachments left to work on
     $attachments = get_option('ewww_image_optimizer_bulk_flag_attachments');
     // take the first image off the list
     array_shift($attachments);
     // and send the list back to the db
     update_option('ewww_image_optimizer_bulk_flag_attachments', $attachments);
     die;
 }
Ejemplo n.º 8
0
 protected function handle()
 {
     session_write_close();
     if (empty($_POST['ewwwio_size'])) {
         $size = '';
     } else {
         $size = $_POST['ewwwio_size'];
     }
     if (!empty($_POST['ewwwio_path']) && $size == 'full') {
         $file_path = $this->find_file($_POST['ewwwio_path']);
         if (!empty($file_path)) {
             ewwwio_debug_message('processing async optimization request');
             list($file, $msg, $conv, $original) = ewww_image_optimizer($file_path, 1, false, false, true);
         } else {
             ewwwio_debug_message("could not process async optimization request for {$_POST['ewwwio_path']}");
         }
     } elseif (!empty($_POST['ewwwio_path'])) {
         $file_path = $this->find_file($_POST['ewwwio_path']);
         if (!empty($file_path)) {
             ewwwio_debug_message('processing async optimization request');
             list($file, $msg, $conv, $original) = ewww_image_optimizer($file_path);
         } else {
             ewwwio_debug_message("could not process async optimization request for {$_POST['ewwwio_path']}");
         }
     } else {
         ewwwio_debug_message('ignored async optimization request');
         return;
     }
     ewww_image_optimizer_hidpi_optimize($file_path);
     ewwwio_debug_message('checking for: ' . $file_path . '.processing');
     if (is_file($file_path . '.processing')) {
         ewwwio_debug_message('removing ' . $file_path . '.processing');
         unlink($file_path . '.processing');
     }
     ewww_image_optimizer_debug_log();
 }
Ejemplo n.º 9
0
 function generate_image_size($image, $size, $params = null, $skip_defaults = false)
 {
     global $ewww_debug;
     if (!defined('EWWW_IMAGE_OPTIMIZER_CLOUD')) {
         ewww_image_optimizer_init();
     }
     $success = $this->call_parent('generate_image_size', $image, $size, $params, $skip_defaults);
     if ($success) {
         //$filename = $this->object->get_image_abspath($image, $size);
         $filename = $success->fileName;
         ewww_image_optimizer($filename);
         //				ewww_image_optimizer_aux_images_loop( $filename, true );
         $ewww_debug .= "nextgen dynamic thumb saved: {$filename} <br>";
         $image_size = filesize($filename);
         $ewww_debug .= "optimized size: {$image_size} <br>";
     }
     ewww_image_optimizer_debug_log();
     ewwwio_memory(__FUNCTION__);
     return $success;
 }
Ejemplo n.º 10
0
 function ewww_flag_bulk_loop()
 {
     global $ewww_defer;
     $ewww_defer = false;
     $permissions = apply_filters('ewww_image_optimizer_bulk_permissions', '');
     if (!wp_verify_nonce($_REQUEST['ewww_wpnonce'], 'ewww-image-optimizer-bulk') || !current_user_can($permissions)) {
         wp_die(__('Access token has expired, please reload the page.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
     }
     if (!empty($_REQUEST['ewww_sleep'])) {
         sleep($_REQUEST['ewww_sleep']);
     }
     // need this file to work with flag meta
     require_once WP_CONTENT_DIR . '/plugins/flash-album-gallery/lib/meta.php';
     // record the starting time for the current image (in microseconds)
     $started = microtime(true);
     $id = $_POST['ewww_attachment'];
     // get the image meta for the current ID
     $meta = new flagMeta($id);
     $file_path = $meta->image->imagePath;
     // optimize the full-size version
     $fres = ewww_image_optimizer($file_path, 3, false, false, true);
     global $ewww_exceed;
     if (!empty($ewww_exceed)) {
         echo '-9exceeded';
         die;
     }
     $meta->image->meta_data['ewww_image_optimizer'] = $fres[1];
     // let the user know what happened
     printf("<p>" . __('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " <strong>%s</strong><br>", esc_html($meta->image->filename));
     printf(__('Full size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $fres[1]);
     if (!empty($meta->image->meta_data['webview'])) {
         // determine path of the webview
         $web_path = $meta->image->webimagePath;
         $wres = ewww_image_optimizer($web_path, 3, false, true);
         $meta->image->meta_data['webview']['ewww_image_optimizer'] = $wres[1];
         printf(__('Optimized size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $wres[1]);
     }
     $thumb_path = $meta->image->thumbPath;
     // optimize the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 3, false, true);
     $meta->image->meta_data['thumbnail']['ewww_image_optimizer'] = $tres[1];
     // and let the user know the results
     printf(__('Thumbnail – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $tres[1]);
     flagdb::update_image_meta($id, $meta->image->meta_data);
     // determine how much time the image took to process
     $elapsed = microtime(true) - $started;
     // and output it to the user
     printf(__('Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "</p>", $elapsed);
     // retrieve the list of attachments left to work on
     $attachments = get_option('ewww_image_optimizer_bulk_flag_attachments');
     // take the first image off the list
     if (!empty($attachments)) {
         array_shift($attachments);
     }
     // and send the list back to the db
     update_option('ewww_image_optimizer_bulk_flag_attachments', $attachments);
     die;
 }
Ejemplo n.º 11
0
function flickr_image_attach_deprecated($flickrurl, $post_id)
{
    preg_match('/http\\:\\/\\/www\\.flickr\\.com\\/photos\\/(.*?)\\/([0-9]+)\\//si', $flickrurl, $m);
    if ($m) {
        $flickruser = $m[1];
        $photo_id = $m[2];
    } else {
        return;
    }
    //$flickruser = getFlickrUser($photo_id);
    $file = getFlickrURL($photo_id);
    if (!empty($file)) {
        // Download file to temp location
        $tmp = download_url($file);
        // Set variables for storage
        // fix file filename for query strings
        preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches);
        $file_array['name'] = basename($matches[0]);
        $file_array['tmp_name'] = $tmp;
        // If error storing temporarily, unlink
        if (is_wp_error($tmp)) {
            @unlink($file_array['tmp_name']);
            $file_array['tmp_name'] = '';
        }
        // do the validation and storage stuff
        $id = media_handle_sideload($file_array, $post_id, $desc = null);
        // If error storing permanently, unlink
        if (is_wp_error($id)) {
            @unlink($file_array['tmp_name']);
            return $id;
        }
        $fullsize_path = get_attached_file($id);
        // Full path
        if (function_exists('ewww_image_optimizer')) {
            ewww_image_optimizer($fullsize_path, $gallery_type = 4, $converted = false, $new = true, $fullsize = true);
        }
        $src = wp_get_attachment_url($id);
    }
    if (!empty($src)) {
        update_post_meta($post_id, 'image_url_value', $flickrurl);
        update_post_meta($post_id, 'image_author_t_value', $flickruser);
        update_post_meta($post_id, 'image_value', $src);
        set_post_thumbnail($post_id, $id);
        return update_post_meta($post_id, 'Thumbnail', $src);
    } else {
        return false;
    }
}
 function ewww_ngg_bulk_loop()
 {
     if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'ewww-image-optimizer-bulk') || !current_user_can('edit_others_posts')) {
         wp_die(__('Cheatin&#8217; eh?'));
     }
     // need this file to work with metadata
     require_once WP_CONTENT_DIR . '/plugins/nextgen-gallery/lib/meta.php';
     // find out what time we started, in microseconds
     $started = microtime(true);
     $id = $_POST['attachment'];
     // get the metadata
     $meta = new nggMeta($id);
     // retrieve the filepath
     $file_path = $meta->image->imagePath;
     // run the optimizer on the current image
     $fres = ewww_image_optimizer($file_path, 2, false, false);
     // update the metadata of the optimized image
     nggdb::update_image_meta($id, array('ewww_image_optimizer' => $fres[1]));
     // output the results of the optimization
     printf("<p>Optimized image: <strong>%s</strong><br>", $meta->image->filename);
     printf("Full size - %s<br>", $fres[1]);
     // get the filepath of the thumbnail image
     $thumb_path = $meta->image->thumbPath;
     // run the optimization on the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 2, false, true);
     // output the results of the thumb optimization
     printf("Thumbnail - %s<br>", $tres[1]);
     // outupt how much time we spent
     $elapsed = microtime(true) - $started;
     echo "Elapsed: " . round($elapsed, 3) . " seconds</p>";
     // get the list of attachments remaining from the db
     $attachments = get_option('ewww_image_optimizer_bulk_ngg_attachments');
     // remove the first item
     array_shift($attachments);
     // and store the list back in the db
     update_option('ewww_image_optimizer_bulk_ngg_attachments', $attachments);
     die;
 }
Ejemplo n.º 13
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;
}
/**
 * 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)
{
    global $ewww_debug;
    $ewww_debug = "{$ewww_debug} <b>ewww_image_optimizer_resize_from_meta_data()</b><br>";
    // don't do anything else if the attachment has no metadata
    if (!isset($meta['file'])) {
        $ewww_debug = "{$ewww_debug} file has no meta<br>";
        return $meta;
    }
    if (FALSE === has_filter('wp_update_attachment_metadata', 'ewww_image_optimizer_update_saved_file')) {
        $gallery_type = 1;
    } else {
        $gallery_type = 5;
    }
    // get the filepath from the metadata
    $file_path = $meta['file'];
    $ewww_debug = "{$ewww_debug} meta file path: {$file_path}<br>";
    // store absolute paths for older wordpress versions
    $store_absolute_path = true;
    // retrieve the location of the wordpress upload folder
    $upload_dir = wp_upload_dir();
    // retrieve the path of the upload folder
    $upload_path = trailingslashit($upload_dir['basedir']);
    // if the path given is not the absolute path
    if (FALSE == file_exists($file_path)) {
        // don't store absolute paths
        $store_absolute_path = false;
        // generate the absolute path
        $file_path = $upload_path . $file_path;
        $ewww_debug = "{$ewww_debug} generated absolute path: {$file_path}<br>";
    }
    // run the image optimizer on the file, and store the results
    list($file, $msg, $conv, $original) = ewww_image_optimizer($file_path, $gallery_type, false, false);
    // update the filename in the metadata
    $meta['file'] = $file;
    // update the optimization results in the metadata
    $meta['ewww_image_optimizer'] = $msg;
    // strip absolute path for Wordpress >= 2.6.2
    if (FALSE === $store_absolute_path) {
        $meta['file'] = str_replace($upload_path, '', $meta['file']);
    }
    // if the file was converted
    if ($conv) {
        $ewww_debug = "{$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'])) {
        $ewww_debug = "{$ewww_debug} processing resizes<br>";
        // meta sizes don't contain a path, so we calculate one
        $base_dir = dirname($file_path) . '/';
        // process each resized version
        $processed = array();
        foreach ($meta['sizes'] as $size => $data) {
            // 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';
                }
            }
            // if this is a unique size
            if (!$dup_size) {
                // run the optimization and store the results
                list($optimized_file, $results, $resize_conv, $original) = ewww_image_optimizer($base_dir . $data['file'], $gallery_type, $conv, true);
                // 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);
                }
                // update the filename
                $meta['sizes'][$size]['file'] = str_replace($base_dir, '', $optimized_file);
                // update the optimization results
                $meta['sizes'][$size]['ewww_image_optimizer'] = $results;
            }
            // 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'];
        }
    }
    // send back the updated metadata
    return $meta;
}
Ejemplo n.º 15
0
 function generate_image_size($image, $size, $params = null, $skip_defaults = false)
 {
     ewwwio_debug_message('<b>' . __FUNCTION__ . '()</b>');
     global $ewww_defer;
     if (!defined('EWWW_IMAGE_OPTIMIZER_CLOUD')) {
         ewww_image_optimizer_init();
     }
     $success = $this->call_parent('generate_image_size', $image, $size, $params, $skip_defaults);
     if ($success) {
         $filename = $success->fileName;
         if ($ewww_defer && ewww_image_optimizer_get_option('ewww_image_optimizer_defer')) {
             ewww_image_optimizer_add_deferred_attachment("file,{$filename}");
             return $saved;
         }
         ewww_image_optimizer($filename);
         ewwwio_debug_message("nextgen dynamic thumb saved: {$filename}");
         $image_size = ewww_image_optimizer_filesize($filename);
         ewwwio_debug_message("optimized size: {$image_size}");
     }
     ewww_image_optimizer_debug_log();
     ewwwio_memory(__FUNCTION__);
     return $success;
 }
Ejemplo n.º 16
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;
}
Ejemplo n.º 17
0
function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $thumb;
    global $wppa_opt;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('wppa_maint_ignore_concurrency_error')) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wppa') . '||' . $slug . '||' . __('Error', 'wppa') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    update_option($slug . '_user', wppa_get_user());
    // Initialize
    $endtime = time() + '5';
    // Allow for 5 seconds
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    // Pre-processing needed?
    if ($lastid == '0') {
        switch ($slug) {
            case 'wppa_remake_index_albums':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                break;
            case 'wppa_remake_index_photos':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wppa'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wppa')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
        }
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
            $chunksize = '100';
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = $wppa_opt['wppa_newphoto_description'];
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim($wppa_opt['wppa_append_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim($wppa_opt['wppa_remove_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            if (wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('wppa_zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    $status = $togo ? 'Pending' : 'Ready';
    if ($togo) {
        update_option($slug . '_togo', $togo);
        update_option($slug . '_status', $status);
    } else {
        // Really done
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        // Re-Init options
        delete_option($slug . '_togo', '');
        delete_option($slug . '_status', '');
        delete_option($slug . '_last', '0');
        delete_option($slug . '_user', '');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wppa'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                $reload = 'reload';
                break;
        }
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}
Ejemplo n.º 18
0
 function ewww_ngg_bulk_loop()
 {
     if (!wp_verify_nonce($_REQUEST['ewww_wpnonce'], 'ewww-image-optimizer-bulk') || !current_user_can('edit_others_posts')) {
         wp_die(__('Access token has expired, please reload the page.', EWWW_IMAGE_OPTIMIZER_DOMAIN));
     }
     // need this file to work with metadata
     ewww_image_optimizer_require(WP_CONTENT_DIR . '/plugins/nextgen-gallery/lib/meta.php');
     // find out what time we started, in microseconds
     $started = microtime(true);
     $id = $_POST['ewww_attachment'];
     // get the metadata
     $meta = new nggMeta($id);
     // retrieve the filepath
     $file_path = $meta->image->imagePath;
     // run the optimizer on the current image
     $fres = ewww_image_optimizer($file_path, 2, false, false, true);
     global $ewww_exceed;
     if (!empty($ewww_exceed)) {
         echo '-9exceeded';
         die;
     }
     // update the metadata of the optimized image
     nggdb::update_image_meta($id, array('ewww_image_optimizer' => $fres[1]));
     // output the results of the optimization
     printf("<p>" . __('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " <strong>%s</strong><br>", $meta->image->filename);
     printf(__('Full size - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $fres[1]);
     // get the filepath of the thumbnail image
     $thumb_path = $meta->image->thumbPath;
     // run the optimization on the thumbnail
     $tres = ewww_image_optimizer($thumb_path, 2, false, true);
     // output the results of the thumb optimization
     printf(__('Thumbnail - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "<br>", $tres[1]);
     // outupt how much time we spent
     $elapsed = microtime(true) - $started;
     printf(__('Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN) . "</p>", $elapsed);
     // get the list of attachments remaining from the db
     $attachments = get_option('ewww_image_optimizer_bulk_ngg_attachments');
     // remove the first item
     if (!empty($attachments)) {
         array_shift($attachments);
     }
     // and store the list back in the db
     update_option('ewww_image_optimizer_bulk_ngg_attachments', $attachments);
     die;
 }
function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('maint_ignore_concurrency_error') && !wppa_is_cron()) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_all_ext_to_lower', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_delete_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag', 'wppa_sync_cloud', 'wppa_sanitize_tags', 'wppa_sanitize_cats', 'wppa_test_proc', 'wppa_crypt_photos', 'wppa_crypt_albums', 'wppa_create_o1_files', 'wppa_owner_to_name_proc', 'wppa_move_all_photos');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wp-photo-album-plus') . '||' . $slug . '||' . __('Error', 'wp-photo-album-plus') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    if (wppa_is_cron()) {
        update_option($slug . '_user', 'cron-job');
        update_option($slug . '_lasttimestamp', time());
    } else {
        update_option($slug . '_user', wppa_get_user());
    }
    // Extend session
    wppa_extend_session();
    // Initialize
    // Cron job: 30 sec, realtime: 5 sec
    $endtime = wppa_is_cron() ? time() + '30' : time() + '5';
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    $to_delete_from_cloudinary = array();
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_added'])) {
        $wppa_session[$slug . '_added'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    wppa_save_session();
    // Pre-processing needed?
    if ($lastid == '0') {
        if (wppa_is_cron()) {
            wppa_log('Obs', 'Cron job ' . $slug . ' started.');
        } else {
            wppa_log('Obs', 'Maintenance proc ' . $slug . ' started.');
        }
        switch ($slug) {
            case 'wppa_remake_index_albums':
                // Pre-Clear album index only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                }
                break;
            case 'wppa_remake_index_photos':
                // Pre-Clear photo index only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                }
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                // Pre-Clear exif and iptc tables only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                    $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                }
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wp-photo-album-plus'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wp-photo-album-plus')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
            case 'wppa_sync_cloud':
                if (!wppa_get_present_at_cloudinary_a()) {
                    // Still Initializing
                    $status = 'Initializing';
                    if (!isset($wppa_session['fun-count'])) {
                        $wppa_session['fun-count'] = 0;
                    }
                    $wppa_session['fun-count'] = ($wppa_session['fun-count'] + 1) % 3;
                    for ($i = 0; $i < $wppa_session['fun-count']; $i++) {
                        $status .= '.';
                    }
                    $togo = 'all';
                    $reload = false;
                    echo '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
                    wppa_exit();
                }
                break;
            case 'wppa_crypt_albums':
                update_option('wppa_album_crypt_0', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_1', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_2', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_3', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_9', wppa_get_unique_album_crypt());
                break;
            case 'wppa_owner_to_name_proc':
                if (!wppa_switch('owner_to_name')) {
                    echo __('Feature must be enabled in Table IV-A28 first', 'wp-photo-album-plus') . '||' . $slug . '||||||';
                    wppa_exit();
                }
                break;
            case 'wppa_move_all_photos':
                $fromalb = get_option('wppa_move_all_photos_from');
                if (!wppa_album_exists($fromalb)) {
                    echo sprintf(__('From album %d does not exist', 'wp-photo-album-plus'), $fromalb);
                    wppa_exit();
                }
                $toalb = get_option('wppa_move_all_photos_to');
                if (!wppa_album_exists($toalb)) {
                    echo sprintf(__('To album %d does not exist', 'wp-photo-album-plus'), $toalb);
                    wppa_exit();
                }
                if ($fromalb == $toalb) {
                    echo __('From and To albums are identical', 'wp-photo-album-plus');
                    wppa_exit();
                }
                break;
        }
        wppa_save_session();
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
        case 'wppa_sanitize_cats':
        case 'wppa_crypt_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            // If done as cron job, no initial clear has been done
                            if (wppa_is_cron()) {
                                wppa_index_remove('album', $id);
                            }
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                        case 'wppa_sanitize_cats':
                            $cats = $album['cats'];
                            if ($cats) {
                                wppa_update_album(array('id' => $album['id'], 'cats' => wppa_sanitize_tags($cats)));
                            }
                            break;
                        case 'wppa_crypt_albums':
                            wppa_update_album(array('id' => $album['id'], 'crypt' => wppa_get_unique_album_crypt()));
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_all_ext_to_lower':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_delete_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
        case 'wppa_sync_cloud':
        case 'wppa_sanitize_tags':
        case 'wppa_crypt_photos':
        case 'wppa_test_proc':
        case 'wppa_create_o1_files':
        case 'wppa_owner_to_name_proc':
        case 'wppa_move_all_photos':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            // If done as cron job, no initial clear has been done
                            if (wppa_is_cron()) {
                                wppa_index_remove('photo', $id);
                            }
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = wppa_opt('newphoto_description');
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim(wppa_opt('append_text'));
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim(wppa_opt('remove_text'));
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_all_ext_to_lower':
                            $EXT = wppa_get_photo_item($id, 'ext');
                            $ext = strtolower($EXT);
                            if ($EXT != $ext) {
                                wppa_update_photo(array('id' => $id, 'ext' => $ext));
                                $fixed_this = true;
                            }
                            $EXT = strtoupper($ext);
                            $rawpath = wppa_strip_ext(wppa_get_photo_path($id));
                            $rawthumb = wppa_strip_ext(wppa_get_thumb_path($id));
                            $fixed_this = false;
                            if (wppa_is_multi($id)) {
                            } else {
                                if (is_file($rawpath . '.' . $EXT)) {
                                    if (is_file($rawpath . '.' . $ext)) {
                                        unlink($rawpath . '.' . $EXT);
                                    } else {
                                        rename($rawpath . '.' . $EXT, $rawpath . '.' . $ext);
                                    }
                                    $fixed_this = true;
                                }
                                if (is_file($rawthumb . '.' . $EXT)) {
                                    if (is_file($rawthumb . '.' . $ext)) {
                                        unlink($rawthumb . '.' . $EXT);
                                    } else {
                                        rename($rawthumb . '.' . $EXT, $rawthumb . '.' . $ext);
                                    }
                                    $fixed_this = true;
                                }
                            }
                            if ($fixed_this) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            $doit = true;
                            if (wppa_switch('remake_orientation_only')) {
                                $ori = wppa_get_exif_orientation(wppa_get_source_path($id));
                                if ($ori < '2') {
                                    $doit = false;
                                }
                            }
                            if (wppa_switch('remake_missing_only')) {
                                if (is_file(wppa_get_thumb_path($id)) && is_file(wppa_get_photo_path($id))) {
                                    $doit = false;
                                }
                            }
                            if ($doit && wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_delete_all_autopages':
                            wppa_remove_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_sync_cloud':
                            $is_old = wppa_opt('max_cloud_life') && time() > $photo['timestamp'] + wppa_opt('max_cloud_life');
                            //	$is_in_cloud = @ getimagesize( wppa_get_cloudinary_url( $photo['id'], 'test_only' ) );
                            $is_in_cloud = isset($wppa_session['cloudinary_ids'][$photo['id']]);
                            //	wppa_log('Obs', 'Id='.$photo['id'].', is old='.$is_old.', in cloud='.$is_in_cloud);
                            if ($is_old && $is_in_cloud) {
                                $to_delete_from_cloudinary[] = strval($photo['id']);
                                if (count($to_delete_from_cloudinary) == 10) {
                                    wppa_delete_from_cloudinary($to_delete_from_cloudinary);
                                    $to_delete_from_cloudinary = array();
                                }
                                $wppa_session[$slug . '_deleted']++;
                            }
                            if (!$is_old && !$is_in_cloud) {
                                wppa_upload_to_cloudinary($photo['id']);
                                $wppa_session[$slug . '_added']++;
                            }
                            if ($is_old && !$is_in_cloud) {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            if (!$is_old && $is_in_cloud) {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_sanitize_tags':
                            $tags = $photo['tags'];
                            if ($tags) {
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => wppa_sanitize_tags($tags)));
                            }
                            break;
                        case 'wppa_crypt_photos':
                            wppa_update_photo(array('id' => $photo['id'], 'crypt' => wppa_get_unique_photo_crypt()));
                            break;
                        case 'wppa_create_o1_files':
                            wppa_make_o1_source($photo['id']);
                            break;
                        case 'wppa_owner_to_name_proc':
                            $iret = wppa_set_owner_to_name($id);
                            if ($iret === true) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($iret === '0') {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_move_all_photos':
                            $fromalb = get_option('wppa_move_all_photos_from');
                            $toalb = get_option('wppa_move_all_photos_to');
                            $alb = wppa_get_photo_item($id, 'album');
                            if ($alb == $fromalb) {
                                wppa_update_photo(array('id' => $id, 'album' => $toalb));
                                wppa_move_source(wppa_get_photo_item($id, 'filename'), $fromalb, $toalb);
                                wppa_flush_treecounts($fromalb);
                                wppa_flush_treecounts($toalb);
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_test_proc':
                            $tags = '';
                            $albid = $photo['album'];
                            $albnam = wppa_get_album_item($albid, 'name');
                            $tags .= $albnam;
                            while ($albid > '0') {
                                $albid = wppa_get_album_item($albid, 'a_parent');
                                if ($albid > '0') {
                                    $tags .= ',' . wppa_get_album_item($albid, 'name');
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'tags' => wppa_sanitize_tags($tags)));
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    // Post proc this try:
    switch ($slug) {
        case 'wppa_sync_cloud':
            if (count($to_delete_from_cloudinary) > 0) {
                wppa_delete_from_cloudinary($to_delete_from_cloudinary);
            }
            break;
    }
    // Find togo
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    // Find status
    if (!$errtxt) {
        $status = $togo ? 'Working' : 'Ready';
    } else {
        $status = 'Error';
    }
    // Not done yet?
    if ($togo) {
        // If a cron job, reschedule next chunk
        if (wppa_is_cron()) {
            update_option($slug . '_togo', $togo);
            update_option($slug . '_status', 'Running cron');
            wppa_schedule_maintenance_proc($slug);
        } else {
            update_option($slug . '_togo', $togo);
            update_option($slug . '_status', 'Pending');
        }
    } else {
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_added']) {
            $status .= ' added:' . $wppa_session[$slug . '_added'];
            unset($wppa_session[$slug . '_added']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        // Re-Init options
        update_option($slug . '_togo', '');
        update_option($slug . '_status', '');
        update_option($slug . '_last', '0');
        update_option($slug . '_user', '');
        update_option($slug . '_lasttimestamp', '0');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                if (wppa_switch('search_tags')) {
                    update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                }
                $reload = 'reload';
                break;
            case 'wppa_sanitize_tags':
                wppa_clear_taglist();
                break;
            case 'wppa_sanitize_cats':
                wppa_clear_catlist();
                break;
            case 'wppa_test_proc':
                wppa_clear_taglist();
                break;
            case 'wppa_sync_cloud':
                unset($wppa_session['cloudinary_ids']);
                break;
        }
        wppa_log('Obs', 'Maintenance proc ' . $slug . ' completed');
    }
    wppa_save_session();
    if (wppa_is_cron()) {
        wppa_log('obs', $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload);
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}