PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 1.9.3
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v1.9.3
4.1.16 4.1.15 4.1.14 4.1.13 4.1.12 4.1.11 4.1.10 4.0.30 4.0.29 4.0.28 4.0.27 4.0.26 4.0.24 4.0.25 4.0.23 4.0.22 4.0.21 4.0.19 4.0.18 4.0.17 4.0.16 1.9.3 1.9.4 1.9.5 1.9.6 All 170 releases
searchpro / inc / class-berqimages.php

class-berqimages.php in BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript 1.9.3, at inc/class-berqimages.php

372 lines 14.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH'))
3 exit;
4
5 if (class_exists('berqWP')) {
6 class berqImages extends berqWP
7 {
8 function __construct()
9 {
10
11 // add_action('add_attachment', [$this, 'generate_webp_images']);
12 // add_filter('wp_calculate_image_srcset', [$this, 'replace_srcset_with_webp'], 999, 5);
13
14 }
15
16 function replace_srcset_with_webp($sources, $size_array, $image_src, $image_meta, $attachment_id)
17 {
18 if (isset($_GET['creating_cache'])) {
19 foreach ($sources as &$source) {
20
21 if (
22 (stripos($source['url'], '.jpg') !== false ||
23 stripos($source['url'], '.jpeg') !== false ||
24 stripos($source['url'], '.png') !== false) && strpos($source['url'], get_site_url()) !== false
25 ) {
26 $webp_url = str_replace(array('.jpg', '.jpeg', '.png'), '.webp', $source['url']);
27 $file_path = str_replace(get_site_url(), ABSPATH, $webp_url);
28
29 if (!file_exists($file_path) && isset($_GET['creating_cache'])) {
30 $this->generate_webp_images($attachment_id);
31 }
32
33 if (file_exists($file_path) && filesize($file_path) > 0) {
34 $source['url'] = $webp_url;
35 }
36 }
37 }
38 }
39 return $sources;
40 }
41
42 function delete_generated_webp_images($attachment_id)
43 {
44 $file = get_attached_file($attachment_id);
45 $file_info = pathinfo($file);
46
47 // Check if the uploaded image is in a supported format
48 $supported_formats = array('jpg', 'jpeg', 'png');
49 if (in_array(strtolower($file_info['extension']), $supported_formats)) {
50 // Get the available image sizes defined in WordPress settings
51 $image_sizes = get_intermediate_image_sizes();
52
53 // Generate webP version of the image for each size
54 foreach ($image_sizes as $size_name) {
55 if ($size = wp_get_attachment_image_src($attachment_id, $size_name)) {
56 $webp_file = $file_info['dirname'] . '/' . $file_info['filename'] . '-' . $size[1] . 'x' . $size[2] . '.webp';
57 // var_dump($webp_file);
58
59 if (file_exists($webp_file)) {
60 wp_delete_file($webp_file);
61 }
62 }
63 }
64
65 // Generate webP version for the original size
66 $webp_file_original = $file_info['dirname'] . '/' . $file_info['filename'] . '.webp';
67
68 if (file_exists($webp_file_original)) {
69 wp_delete_file($webp_file_original);
70 }
71 }
72
73 }
74
75 function send_image_to_api($image_url, $quality, $maxwidth)
76 {
77 // Define the API endpoint
78 $api_url = 'https://berqwp.com/wp-json/berqwp-api/webp';
79
80 // Use the following format for file uploads with wp_remote_post
81 $body = array(
82 'image' => $image_url,
83 'quality' => $quality,
84 'maxwidth' => $maxwidth
85 );
86
87 // You don't need to manually set the Content-Type header to 'multipart/form-data';
88 // wp_remote_post() will handle it for you when it detects you're sending files.
89
90 // Send the request
91 $response = wp_remote_post(
92 $api_url,
93 array(
94 'body' => $body,
95 'timeout' => 45 // You can adjust the timeout as needed
96 )
97 );
98
99 // Check for errors
100 if (is_wp_error($response)) {
101 $error_message = $response->get_error_message();
102 return "Something went wrong: $error_message";
103 } else {
104 return wp_remote_retrieve_body($response);
105 }
106 }
107
108 function handle_not_webp($image_url, $quality, $max_width, $webp_path)
109 {
110
111 if (!function_exists('download_url')) {
112 require_once(ABSPATH . 'wp-admin/includes/file.php');
113 }
114
115 if (is_array($image_url)) {
116 $image_url = $image_url[0];
117 }
118
119 $resp = $this->send_image_to_api($image_url, $quality, $max_width);
120
121 $json = json_decode($resp, true);
122
123 if (empty($json['success']) || $json['success'] !== true) {
124 return false;
125 }
126
127 // Use the WordPress function to download the file
128 $temp_file = download_url($json['webp_url']);
129
130 // Check for errors
131 if (is_wp_error($temp_file)) {
132 return false;
133 }
134
135 // Copy the temp file to the specified path
136 $result = copy($temp_file, $webp_path);
137
138 // Clean up the temporary file
139 unlink($temp_file);
140 }
141
142 function is_webp_supported()
143 {
144 if (function_exists('imagewebp') && function_exists('imagecreatetruecolor')) {
145 $test_image = imagecreatetruecolor(1, 1); // Create a 1x1 blank image
146
147 if ($test_image === false) {
148 return false;
149 }
150
151 ob_start();
152 $webp_support = imagewebp($test_image, null, 100);
153 ob_end_clean();
154 imagedestroy($test_image);
155
156 return $webp_support;
157 }
158 return false;
159 }
160
161
162 function generate_webp_images($attachment_id)
163 {
164 $file = get_attached_file($attachment_id);
165 $file_info = pathinfo($file);
166
167 // Check if the uploaded image is in a supported format
168 $supported_formats = array('jpg', 'jpeg', 'png');
169 if (in_array(strtolower($file_info['extension']), $supported_formats)) {
170 // Get the available image sizes defined in WordPress settings
171 $image_sizes = get_intermediate_image_sizes();
172
173 // Set the quality of the image (optional)
174 $quality = (int) get_option('berqwp_webp_quality');
175 $max_width = (int) get_option('berqwp_webp_max_width');
176
177 // Generate webP version of the image for each size
178 foreach ($image_sizes as $size_name) {
179 if ($size = wp_get_attachment_image_src($attachment_id, $size_name)) {
180 $image_url = wp_get_attachment_image_src($attachment_id, $size_name);
181 $webp_file = $file_info['dirname'] . '/' . $file_info['filename'] . '-' . $size[1] . 'x' . $size[2] . '.webp';
182
183 if (!file_exists($webp_file)) {
184
185 // if webp generation is not supported
186 if (!$this->is_webp_supported()) {
187 $this->handle_not_webp($image_url, $quality, $max_width, $webp_file);
188 continue;
189 }
190
191 // Load the original image
192 $image = null;
193 $extension = strtolower($file_info['extension']);
194 if ($extension === 'jpg' || $extension === 'jpeg') {
195 $image = imagecreatefromjpeg($file);
196 } elseif ($extension === 'png') {
197 $image = imagecreatefrompng($file);
198
199 // // Preserve transparency for WebP conversion
200 // imagesavealpha($image, true);
201 // $transparentColor = imagecolorallocatealpha($image, 0, 0, 0, 127);
202 // imagefill($image, 0, 0, $transparentColor);
203
204
205 // Check if the PNG image has an alpha channel (transparency)
206 // $has_alpha = imagecolortransparent($image);
207 // if ($has_alpha || imagecolorstotal($image) > 256) {
208 // // Preserve transparency for WebP conversion
209 // imagepalettetotruecolor($image);
210 // imagesavealpha($image, true);
211 // $transparentColor = imagecolorallocatealpha($image, 0, 0, 0, 127);
212 // imagefill($image, 0, 0, $transparentColor);
213 // }
214 }
215
216 if ($image) {
217 // Resize the image to the defined size
218 $resized_image = imagescale($image, $size[1], $size[2]);
219
220 if (!$resized_image) {
221 continue;
222 }
223
224 // Check if the width exceeds the maximum width
225 if ($size[1] > $max_width) {
226 $resized_image = imagescale($resized_image, $max_width);
227 }
228
229 // Save the resized image as WebP
230 imagewebp($resized_image, $webp_file, $quality);
231
232 // Free up memory
233 imagedestroy($image);
234 imagedestroy($resized_image);
235 }
236 }
237 }
238 }
239
240 // Generate webP version for the original size
241 $webp_file_original = $file_info['dirname'] . '/' . $file_info['filename'] . '.webp';
242 $image_url = wp_get_attachment_url($attachment_id);
243
244 if (!file_exists($webp_file_original)) {
245
246 // if webp generation is not supported
247 if (!$this->is_webp_supported()) {
248 $this->handle_not_webp($image_url, $quality, $max_width, $webp_file_original);
249 return;
250 }
251
252 // Load the original image
253 $image_original = null;
254 $extension_original = strtolower($file_info['extension']);
255 if ($extension_original === 'jpg' || $extension_original === 'jpeg') {
256 $image_original = imagecreatefromjpeg($file);
257 } elseif ($extension_original === 'png') {
258 $image_original = imagecreatefrompng($file);
259
260 // Ensure the image is true color, not palette-based
261 imagepalettetotruecolor($image_original);
262 }
263
264 if ($image_original) {
265 // Check if the width exceeds the maximum width
266 $image_width = imagesx($image_original); // get image width
267 if ($image_width > $max_width) {
268 $image_original = imagescale($image_original, $max_width);
269 }
270
271 // Save the original image as WebP
272 imagewebp($image_original, $webp_file_original, $quality);
273
274 // Free up memory
275 imagedestroy($image_original);
276 }
277 }
278 }
279 }
280
281 function delete_webp_images($attachment_id)
282 {
283 $file = get_attached_file($attachment_id);
284 $file_info = pathinfo($file);
285
286 // Check if the uploaded image is in a supported format
287 $supported_formats = array('jpg', 'jpeg', 'png');
288 if (in_array(strtolower($file_info['extension']), $supported_formats)) {
289 // Get the available image sizes defined in WordPress settings
290 $image_sizes = get_intermediate_image_sizes();
291
292 // Set the quality of the image (optional)
293 $quality = (int) get_option('berqwp_webp_quality');
294 $max_width = (int) get_option('berqwp_webp_max_width');
295
296 // Generate webP version of the image for each size
297 foreach ($image_sizes as $size_name) {
298 if ($size = wp_get_attachment_image_src($attachment_id, $size_name)) {
299 $webp_file = $file_info['dirname'] . '/' . $file_info['filename'] . '-' . $size[1] . 'x' . $size[2] . '.webp';
300 // var_dump($webp_file);
301
302 if (file_exists($webp_file)) {
303 unlink($webp_file);
304 }
305 }
306 }
307
308 // Generate webP version for the original size
309 $webp_file_original = $file_info['dirname'] . '/' . $file_info['filename'] . '.webp';
310 // var_dump($webp_file_original);
311
312 if (file_exists($webp_file_original)) {
313 unlink($webp_file_original);
314 }
315 }
316 }
317
318
319
320
321 function remove_webp_image($attachment_id)
322 {
323 $file = get_attached_file($attachment_id);
324 $file_info = pathinfo($file);
325
326 // Check if the uploaded image is in a supported format
327 $supported_formats = array('jpg', 'jpeg', 'png');
328 if (isset($file_info['extension']) && in_array(strtolower($file_info['extension']), $supported_formats)) {
329 // Remove the corresponding WebP image if it exists
330 $webp_file = $file_info['dirname'] . '/' . $file_info['filename'] . '.webp';
331 if (file_exists($webp_file)) {
332 unlink($webp_file);
333 }
334 }
335 }
336
337 // Generate webP images for existing images in the media library
338 function generate_webp_images_for_existing()
339 {
340 $args = array(
341 'post_type' => 'attachment',
342 'post_mime_type' => 'image',
343 'post_status' => 'inherit',
344 'posts_per_page' => -1,
345 );
346
347 $attachments = get_posts($args);
348
349 foreach ($attachments as $attachment) {
350 $this->generate_webp_images($attachment->ID);
351 }
352 }
353
354 function delete_webp_images_for_existing()
355 {
356 $args = array(
357 'post_type' => 'attachment',
358 'post_mime_type' => 'image',
359 'post_status' => 'inherit',
360 'posts_per_page' => -1,
361 );
362
363 $attachments = get_posts($args);
364
365 foreach ($attachments as $attachment) {
366 $this->remove_webp_image($attachment->ID);
367 }
368 }
369 }
370
371 $berqImages = new berqImages();
372 }