| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) die('Access denied.'); |
| 4 |
|
| 5 |
if (!class_exists('WP_Optimize_Dashboard_Images')) : |
| 6 |
|
| 7 |
/** |
| 8 |
* Collects all data needed to render the Media / Images dashboard card. |
| 9 |
*/ |
| 10 |
class WP_Optimize_Dashboard_Images implements WP_Optimize_Dashboard_Interface { |
| 11 |
|
| 12 |
/** |
| 13 |
* @return WpoDashboardImagesData |
| 14 |
*/ |
| 15 |
public function collect(): array { |
| 16 |
global $wpdb; |
| 17 |
|
| 18 |
$smush_options = Updraft_Smush_Manager()->get_smush_options(); |
| 19 |
$auto_smush = !empty($smush_options['autosmush']); |
| 20 |
$webp_conversion = !empty($smush_options['webp_conversion']); |
| 21 |
|
| 22 |
$optimised_count = (int) $wpdb->get_var( |
| 23 |
$wpdb->prepare( |
| 24 |
"SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", |
| 25 |
'_wpo-smush-complete', |
| 26 |
'1' |
| 27 |
) |
| 28 |
); |
| 29 |
|
| 30 |
$saved_bytes = (int) WP_Optimize()->get_options()->get_option('total_bytes_saved', 0); |
| 31 |
|
| 32 |
return array( |
| 33 |
'active' => $auto_smush, |
| 34 |
'label' => __('Images', 'wp-optimize'), |
| 35 |
'optimised_count' => $optimised_count, |
| 36 |
'unused_count' => $this->get_unused_images_count(), |
| 37 |
'saved_bytes' => $saved_bytes, |
| 38 |
'saved_human' => size_format($saved_bytes, 1) ?: '0 B', |
| 39 |
'auto_optimize' => $auto_smush, |
| 40 |
'webp_conversion' => $webp_conversion, |
| 41 |
'is_premium' => WP_Optimize::is_premium(), |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Returns the total count of images flagged as unused by the WPO media scan. |
| 47 |
* |
| 48 |
* The premium WP_Optimization_images::get_unused_images_count() only counts |
| 49 |
* `unused_images_files` (orphaned filesystem files) and misses `unused_posts_images` |
| 50 |
* (media-library attachments not used in any post content), which is what the |
| 51 |
* Unused Images tab actually scans and displays. We read both transient caches |
| 52 |
* directly and sum them. |
| 53 |
* |
| 54 |
* @return int |
| 55 |
*/ |
| 56 |
private function get_unused_images_count(): int { |
| 57 |
if (!WP_Optimize::is_premium()) return 0; |
| 58 |
|
| 59 |
$blog_id = get_current_blog_id(); |
| 60 |
$prefix = 'wpo_images_cache_' . $blog_id . '_'; |
| 61 |
$cache = WP_Optimize_Transients_Cache::get_instance(); |
| 62 |
|
| 63 |
$posts = $cache->get($prefix . 'unused_posts_images'); |
| 64 |
$files = $cache->get($prefix . 'unused_images_files'); |
| 65 |
|
| 66 |
$count = 0; |
| 67 |
if (is_array($posts)) $count += count($posts); |
| 68 |
if (is_array($files)) $count += count($files); |
| 69 |
|
| 70 |
return $count; |
| 71 |
} |
| 72 |
} |
| 73 |
endif; |
| 74 |
|