Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closes #796: Auto generation of AVIF on save #806

Merged
merged 6 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 33 additions & 22 deletions classes/Bulk/Bulk.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,17 +175,28 @@ public function run_optimize( string $context, int $optimization_level ) {
'message' => 'over-quota',
];
}
$formats = imagify_nextgen_images_formats();
$media_ids = [
'ids' => [],
'errors' => [
'no_file_path' => [],
'no_backup' => [],
],
];
foreach ( $formats as $format ) {
$result = $this->get_bulk_instance( $context )->get_optimized_media_ids_without_format( $format );
$media_ids['ids'] = array_merge( $media_ids['ids'], $result['ids'] );
}

$media_ids = $this->get_bulk_instance( $context )->get_unoptimized_media_ids( $optimization_level );

if ( empty( $media_ids ) ) {
if ( empty( $media_ids['ids'] ) ) {
return [
'success' => false,
'message' => 'no-images',
];
}
$media_ids['ids'] = array_unique( $media_ids['ids'] );

foreach ( $media_ids as $media_id ) {
foreach ( $media_ids['ids'] as $media_id ) {
try {
as_enqueue_async_action(
'imagify_optimize_media',
Expand Down Expand Up @@ -235,23 +246,24 @@ public function run_generate_nextgen( array $contexts, array $formats ) {
$medias = [];

foreach ( $contexts as $context ) {
$media = $this->get_bulk_instance( $context )->get_optimized_media_ids_without_webp();
foreach ( $formats as $format ) {
$media = $this->get_bulk_instance( $context )->get_optimized_media_ids_without_format( $format );
if ( ! $media['ids'] && $media['errors']['no_backup'] ) {
// No backup, no WebP.
return [
'success' => false,
'message' => 'no-backup',
];
} elseif ( ! $media['ids'] && $media['errors']['no_file_path'] ) {
// Error.
return [
'success' => false,
'message' => __( 'The path to the selected files could not be retrieved.', 'imagify' ),
];
}

if ( ! $media['ids'] && $media['errors']['no_backup'] ) {
// No backup, no WebP.
return [
'success' => false,
'message' => 'no-backup',
];
} elseif ( ! $media['ids'] && $media['errors']['no_file_path'] ) {
// Error.
return [
'success' => false,
'message' => __( 'The path to the selected files could not be retrieved.', 'imagify' ),
];
$medias[ $context ] = $media['ids'];
}

$medias[ $context ] = $media['ids'];
}

if ( empty( $medias ) ) {
Expand Down Expand Up @@ -510,14 +522,14 @@ public function bulk_optimize_callback() {
}

/**
* Launch the missing WebP versions generation
* Launch the missing Next-gen versions generation
*
* @return void
*/
public function missing_nextgen_callback() {
imagify_check_nonce( 'imagify-bulk-optimize' );

$contexts = explode( '_', sanitize_key( wp_unslash( $_GET['context'] ) ) );
$contexts = $this->get_contexts();

foreach ( $contexts as $context ) {
if ( ! imagify_get_context( $context )->current_user_can( 'bulk-optimize' ) ) {
Expand All @@ -528,7 +540,6 @@ public function missing_nextgen_callback() {
$formats = imagify_nextgen_images_formats();

$data = $this->run_generate_nextgen( $contexts, $formats );

if ( false === $data['success'] ) {
wp_send_json_error( [ 'message' => $data['message'] ] );
}
Expand Down
18 changes: 18 additions & 0 deletions classes/Bulk/BulkInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,24 @@
*/
public function get_optimized_media_ids_without_webp();

/**
* Get ids of all optimized media without Next gen versions.
*
* @since 2.2
*
* @param string $format Format we are looking for. (webp|avif).
*
* @return array {
* @type array $ids A list of media IDs.
* @type array $errors {
* @type array $no_file_path A list of media IDs.
* @type array $no_backup A list of media IDs.
* }
* }
*/
public function get_optimized_media_ids_without_format( $format);

Check notice on line 51 in classes/Bulk/BulkInterface.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

classes/Bulk/BulkInterface.php#L51

Expected 1 spaces after opening parenthesis; 0 found


/**
* Tell if there are optimized media without WebP versions.
*
Expand Down
91 changes: 91 additions & 0 deletions classes/Bulk/CustomFolders.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,97 @@ public function get_optimized_media_ids_without_webp() {
return $data;
}

/**
* Get ids of all optimized media without Next gen versions.
*
* @since 2.2
*
* @param string $format Format we are looking for. (webp|avif).
*
* @return array {
* @type array $ids A list of media IDs.
* @type array $errors {
* @type array $no_file_path A list of media IDs.
* @type array $no_backup A list of media IDs.
* }
* }
*/
public function get_optimized_media_ids_without_format( $format ) {
global $wpdb;

$this->set_no_time_limit();

$files_table = Imagify_Files_DB::get_instance()->get_table_name();
$folders_table = Imagify_Folders_DB::get_instance()->get_table_name();
$mime_types = Imagify_DB::get_mime_types( 'image' );
// Remove single quotes and explode string into array.
$mime_types_array = explode( ',', str_replace( "'", '', $mime_types ) );

// Iterate over array and check if string contains input.
foreach ( $mime_types_array as $item ) {
if ( strpos( $item, $format ) !== false ) {
$mime = $item;
break;
}
}
if ( ! isset( $mime ) && empty( $mime ) ) {
$mime = 'image/webp';
}
$mime_types = str_replace( ",'" . $mime . "'", '', $mime_types );
$nextgen_suffix = constant( imagify_get_optimization_process_class_name( 'custom-folders' ) . '::' . strtoupper( $format ) . '_SUFFIX' );
$files = $wpdb->get_results( $wpdb->prepare( // WPCS: unprepared SQL ok.
"
SELECT fi.file_id, fi.path
FROM $files_table as fi
INNER JOIN $folders_table AS fo
ON ( fi.folder_id = fo.folder_id )
WHERE
fi.mime_type IN ( $mime_types )
AND ( fi.status = 'success' OR fi.status = 'already_optimized' )
AND ( fi.data NOT LIKE %s OR fi.data IS NULL )
ORDER BY fi.file_id DESC",
'%' . $wpdb->esc_like( $nextgen_suffix . '";a:4:{s:7:"success";b:1;' ) . '%'
) );

$wpdb->flush();
unset( $mime_types, $files_table, $folders_table, $nextgen_suffix, $mime );

$data = [
'ids' => [],
'errors' => [
'no_file_path' => [],
'no_backup' => [],
],
];

if ( ! $files ) {
return $data;
}

foreach ( $files as $file ) {
$file_id = absint( $file->file_id );

if ( empty( $file->path ) ) {
// Problem.
$data['errors']['no_file_path'][] = $file_id;
continue;
}

$file_path = Imagify_Files_Scan::remove_placeholder( $file->path );
$backup_path = Imagify_Custom_Folders::get_file_backup_path( $file_path );

if ( ! $this->filesystem->exists( $backup_path ) ) {
// No backup, no WebP.
$data['errors']['no_backup'][] = $file_id;
continue;
}

$data['ids'][] = $file_id;
} // End foreach().

return $data;
}

/**
* Get the context data.
*
Expand Down
25 changes: 25 additions & 0 deletions classes/Bulk/Noop.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,31 @@
];
}

/**
* * Get ids of all optimized media without Next gen versions.
*
* @since 2.2
*
* @param string $format Format we are looking for. (webp|avif).
*
* @return array {
* @type array $ids A list of media IDs.
* @type array $errors {
* @type array $no_file_path A list of media IDs.
* @type array $no_backup A list of media IDs.
* }
* }
*/
public function get_optimized_media_ids_without_format( $format ) {

Check warning on line 61 in classes/Bulk/Noop.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

classes/Bulk/Noop.php#L61

Avoid unused parameters such as '$format'.
return [
'ids' => [],
'errors' => [
'no_file_path' => [],
'no_backup' => [],
],
];
}

/**
* Get the context data.
*
Expand Down
127 changes: 127 additions & 0 deletions classes/Bulk/WP.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,133 @@
return $data;
}

/**
* Get ids of all optimized media without Next gen versions.
*
* @since 2.2
*
* @param string $format Format we are looking for. (webp|avif).
*
* @return array {
* @type array $ids A list of media IDs.
* @type array $errors {
* @type array $no_file_path A list of media IDs.
* @type array $no_backup A list of media IDs.
* }
* }
*/
public function get_optimized_media_ids_without_format( $format ) {

Check warning on line 292 in classes/Bulk/WP.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

classes/Bulk/WP.php#L292

The method get_optimized_media_ids_without_format() has 112 lines of code. Current threshold is set to 100. Avoid really long methods.

Check warning on line 292 in classes/Bulk/WP.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

classes/Bulk/WP.php#L292

The method get_optimized_media_ids_without_format() has a Cyclomatic Complexity of 10. The configured cyclomatic complexity threshold is 10.
global $wpdb;

$this->set_no_time_limit();

$mime_types = Imagify_DB::get_mime_types( 'image' );

// Remove single quotes and explode string into array.
$mime_types_array = explode( ',', str_replace( "'", '', $mime_types ) );

// Iterate over array and check if string contains input.
foreach ( $mime_types_array as $item ) {
if ( strpos( $item, $format ) !== false ) {
$mime = $item;
break;
}
}
if ( ! isset( $mime ) && empty( $mime ) ) {
$mime = 'image/webp';
}
$mime_types = str_replace( ",'" . $mime . "'", '', $mime_types );
$statuses = Imagify_DB::get_post_statuses();
$nodata_join = Imagify_DB::get_required_wp_metadata_join_clause();
$nodata_where = Imagify_DB::get_required_wp_metadata_where_clause( [
'prepared' => true,
] );
$nextgen_suffix = constant( imagify_get_optimization_process_class_name( 'wp' ) . '::' . strtoupper( $format ) . '_SUFFIX' );

$ids = $wpdb->get_col( $wpdb->prepare( // WPCS: unprepared SQL ok.
"
SELECT p.ID
FROM $wpdb->posts AS p
$nodata_join
LEFT JOIN $wpdb->postmeta AS mt1
ON ( p.ID = mt1.post_id AND mt1.meta_key = '_imagify_status' )
LEFT JOIN $wpdb->postmeta AS mt2
ON ( p.ID = mt2.post_id AND mt2.meta_key = '_imagify_data' )
WHERE
p.post_mime_type IN ( $mime_types )
AND (mt1.meta_key IS NULL OR mt1.meta_value = 'success' OR mt1.meta_value = 'already_optimized' )
AND mt2.meta_value NOT LIKE %s
AND p.post_type = 'attachment'
AND p.post_status IN ( $statuses )
$nodata_where
ORDER BY p.ID DESC
LIMIT 0, %d",
'%' . $wpdb->esc_like( $nextgen_suffix . '";a:4:{s:7:"success";b:1;' ) . '%',
imagify_get_unoptimized_attachment_limit()
) );

$wpdb->flush();
unset( $mime_types, $statuses, $nextgen_suffix, $mime );

$ids = array_filter( array_map( 'absint', $ids ) );

$data = [
'ids' => [],
'errors' => [
'no_file_path' => [],
'no_backup' => [],
],
];

if ( ! $ids ) {
return $data;
}

$metas = Imagify_DB::get_metas( [
// Get attachments filename.
'filenames' => '_wp_attached_file',
], $ids );

/**
* Fires before testing for file existence.
*
* @since 1.9
*
* @param array $ids An array of attachment IDs.
* @param array $metas An array of the data fetched from the database.
* @param string $context The context.
*/
do_action( 'imagify_bulk_generate_nextgen_before_file_existence_tests', $ids, $metas, 'wp' );

foreach ( $ids as $i => $id ) {
if ( empty( $metas['filenames'][ $id ] ) ) {
// Problem. Should not happen, thanks to the wpdb query.
$data['errors']['no_file_path'][] = $id;
continue;
}

$file_path = get_imagify_attached_file( $metas['filenames'][ $id ] );

if ( ! $file_path ) {
// Main file not found.
$data['errors']['no_file_path'][] = $id;
continue;
}

$backup_path = get_imagify_attachment_backup_path( $file_path );

if ( ! $this->filesystem->exists( $backup_path ) ) {
// No backup, no WebP.
$data['errors']['no_backup'][] = $id;
continue;
}

$data['ids'][] = $id;
} // End foreach().

return $data;
}

/**
* Get the context data.
*
Expand Down
1 change: 0 additions & 1 deletion inc/functions/attachments.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ function imagify_get_mime_types( $type = null ) {
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'avif' => 'image/avif',
];
}

Expand Down