PluginProbe ʕ •ᴥ•ʔ
Robin Image Optimizer – Unlimited Image Optimization, WebP & AVIF / trunk
Robin Image Optimizer – Unlimited Image Optimization, WebP & AVIF vtrunk
2.0.5 trunk 1.3.7 1.4.0 1.4.1 1.4.2 1.4.6 1.5.0 1.5.3 1.5.6 1.5.8 1.6.5 1.6.6 1.6.9 1.7.0 1.7.4 1.8.1 1.8.2 1.9.0 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4
robin-image-optimizer / libs / addons / admin / ajax / folders.php
robin-image-optimizer / libs / addons / admin / ajax Last commit date
folders.php 6 months ago optimization.php 6 months ago
folders.php
505 lines
1 <?php
2
3 /**
4 * AJAX обработчик выбора папки
5 */
6 add_action(
7 'wp_ajax_wriop_browse_dir',
8 function () {
9 if ( ! check_ajax_referer( 'bulk_optimization', false, false ) || ! current_user_can( 'manage_options' ) ) {
10 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
11 }
12
13 if ( is_main_site() ) {
14 $base = get_home_path();
15 $root = wp_normalize_path( $base );
16 } else {
17 $up = wp_upload_dir();
18 $root = wp_normalize_path( $up['basedir'] );
19 }
20
21 $dir = trim( WRIO_Plugin::app()->request->post( 'dir', null, 'rawurldecode' ) );
22
23 $multiselect = WRIO_Plugin::app()->request->post( 'multiSelect' );
24 $multiselect = $multiselect == 'true' ? true : false;
25
26 $only_folders = WRIO_Plugin::app()->request->post( 'onlyFolders' );
27 $only_folders = $only_folders == 'true' ? true : false;
28 $only_folders = $dir == '/' || $only_folders;
29
30 $only_files = WRIO_Plugin::app()->request->post( 'onlyFiles' );
31 $only_files = $only_files == 'true' ? true : false;
32
33 $selected_dir = trailingslashit( $root ) . ( $dir == '/' ? '' : $dir );
34
35 // set checkbox if multiSelect set to true
36 $checkbox = $multiselect ? "<input type='checkbox' />" : null;
37
38 $upload_dir = wp_upload_dir();
39 $upload_dir_path = trailingslashit( str_replace( ABSPATH, '', $upload_dir['basedir'] ) );
40 $wp_content_dir = trailingslashit( str_replace( ABSPATH, '', WP_CONTENT_DIR ) );
41
42 $ngg_path = str_replace( wp_normalize_path( ABSPATH ), '', wrio_get_ngg_galleries_path() );
43 $shortpixel_path = str_replace( wp_normalize_path( ABSPATH ), '', wrio_get_shortpixel_path() );
44 $ewww_path = str_replace( wp_normalize_path( ABSPATH ), '', wrio_get_ewww_tools_path() );
45 $wc_path = str_replace( wp_normalize_path( ABSPATH ), '', wrio_get_wc_logs_path() );
46
47 $exclude_dirs = [
48 $ngg_path,
49 $shortpixel_path,
50 $ewww_path,
51 $wc_path,
52 $wp_content_dir . 'backup',
53 $wp_content_dir . 'backups',
54 $wp_content_dir . 'cache',
55 $wp_content_dir . 'lang',
56 $wp_content_dir . 'langs',
57 $wp_content_dir . 'languages',
58 $upload_dir_path . 'wio_backup',
59 $upload_dir_path . 'wrio',
60 $upload_dir_path . 'wrio-webp-uploads',
61 // 'wp-admin',
62 // 'wp-includes'
63 ];
64 // исключаем все директории /wp-content/uploads/2019 - они уже оптимизируются в медиабиблиотеке.
65 // с основания WP в 2003 году до текущего года + 1 на всякий случай.
66 $year = date( 'Y' ) + 1;
67 for ( $i = 2003; $i <= $year; $i++ ) {
68 $exclude_dirs[] = $upload_dir_path . $i;
69 }
70
71 if ( file_exists( $selected_dir ) && is_dir( $selected_dir ) ) {
72
73 $files = scandir( $selected_dir );
74 $return_dir = substr( $selected_dir, strlen( $root ) );
75
76 natcasesort( $files );
77
78 if ( count( $files ) > 2 ) { // The 2 accounts for . and ..
79 echo "<ul class='jqueryFileTree'>";
80 $counter = 0;
81 foreach ( $files as $file ) {
82 // если в папке очень много файлов, то показываем не все.
83 if ( $counter++ > 200 ) {
84 break;
85 }
86 // если это папка бекап или другое исключение - пропускаем
87 if ( in_array( $return_dir . $file, $exclude_dirs ) ) {
88 continue;
89 }
90
91 $htmlRel = str_replace( "'", '&apos;', $return_dir . $file );
92 $htmlName = htmlentities( $file );
93 $ext = preg_replace( '/^.*\./', '', $file );
94
95 if ( file_exists( $selected_dir . $file ) && $file != '.' && $file != '..' ) {
96 // KEEP the spaces in front of the rel values - it's a trick to make WP Hide not replace the wp-content path
97 if ( is_dir( $selected_dir . $file ) && ( ! $only_files || $only_folders ) ) {
98 echo "<li class='directory collapsed'>{$checkbox}<a rel=' " . $htmlRel . "/'>" . $htmlName . '</a></li>';
99 } elseif ( ! $only_folders || $only_files ) {
100 echo "<li class='file ext_{$ext}'>{$checkbox}<a rel=' " . $htmlRel . "'>" . $htmlName . '</a></li>';
101 }
102 }
103 }
104
105 echo '</ul>';
106 }
107 }
108 die();
109 }
110 );
111
112 /**
113 * AJAX обработчик добавления папки
114 */
115 add_action(
116 'wp_ajax_wrio-add-custom-folder',
117 function () {
118 if ( ! check_ajax_referer( 'bulk_optimization', false, false ) || ! current_user_can( 'manage_options' ) ) {
119 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
120 }
121
122 $path = WRIO_Plugin::app()->request->request( 'path', null, true );
123
124 if ( empty( $path ) ) {
125 wp_die( - 1 );
126 }
127
128 $cf = WRIO_Custom_Folders::get_instance();
129 $folder = $cf->addFolder( $path );
130
131 if ( is_wp_error( $folder ) ) {
132 wp_send_json_error(
133 [
134 'error_message' => $folder->get_error_message(),
135 'error_code' => $folder->get_error_code(),
136 ]
137 );
138 }
139
140 wp_send_json_success( $folder->toArray() );
141 }
142 );
143
144 /**
145 * AJAX индексация папки
146 */
147 add_action(
148 'wp_ajax_wrio-scan-folder',
149 function () {
150 if ( ! check_ajax_referer( 'bulk_optimization', false, false ) || ! current_user_can( 'manage_options' ) ) {
151 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
152 }
153
154 $uid = WRIO_Plugin::app()->request->request( 'uid', null, true );
155 $offset = WRIO_Plugin::app()->request->request( 'offset', 0, true );
156 $total = WRIO_Plugin::app()->request->request( 'total', 0, true );
157
158 if ( empty( $uid ) ) {
159 wp_die( - 1 );
160 }
161
162 $max_process_elements = 100; // сколько элементов за итерацию индексирования
163
164 $cf = WRIO_Custom_Folders::get_instance();
165 $folder = $cf->getFolder( $uid );
166
167 if ( ! $total ) {
168 $total = $folder->reCountFiles();
169 $cf->saveFolders();
170 }
171
172 $processed_count = $folder->indexing( $offset, $max_process_elements );
173 $offset = $offset + $processed_count;
174
175 $results = [
176 'offset' => $offset,
177 'total' => $total,
178 'complete' => false,
179 'percent' => 0,
180 ];
181
182 if ( $total ) {
183 $results['percent'] = 100 - ( ( $total - $offset ) * 100 / $total );
184 /**
185 * Операция индексирования состоит из дву�
186 этапов. Проверка существующи�
187 файлов и поиск новы�
188 файлов.
189 * Поэтому процент делим на 2 и добавляем 50% т.к. это вторая часть.
190 */
191 $results['percent'] = $results['percent'] / 2 + 50;
192 }
193
194 if ( $offset >= $total ) {
195 $results['percent'] = 100;
196 $results['complete'] = true;
197 }
198
199 wp_send_json_success( $results );
200 }
201 );
202
203 /**
204 * AJAX обработчик удаления папки
205 */
206 add_action(
207 'wp_ajax_wriop_remove_folder',
208 function () {
209 if ( ! check_ajax_referer( 'bulk_optimization', false, false ) || ! current_user_can( 'manage_options' ) ) {
210 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
211 }
212
213 $uid = isset( $_POST['uid'] ) ? $_POST['uid'] : false;
214 if ( ! $uid ) {
215 die();
216 }
217 $cf = WRIO_Custom_Folders::get_instance();
218 $cf->removeFolder( $uid );
219 $cf->saveFolders();
220
221 die();
222 }
223 );
224
225 /**
226 * AJAX проверка проиндексированны�
227 файлов
228 */
229 add_action(
230 'wp_ajax_wriop_folder_sync_index',
231 function () {
232 if ( ! check_ajax_referer( 'bulk_optimization', false, false ) || ! current_user_can( 'manage_options' ) ) {
233 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
234 }
235
236 $uid = isset( $_POST['uid'] ) ? $_POST['uid'] : false;
237 $offset = isset( $_POST['offset'] ) ? intval( $_POST['offset'] ) : 0;
238 $total = isset( $_POST['total'] ) ? intval( $_POST['total'] ) : 0;
239 $max_process_elements = 20; // сколько элементов за итерацию индексирования
240
241 $cf = WRIO_Custom_Folders::get_instance();
242 $folder = $cf->getFolder( $uid );
243 $total = $folder->countIndexedFiles();
244 $processed_count = $folder->syncIndex( $offset, $max_process_elements );
245 $offset = $offset + $processed_count;
246 $results = [
247 'offset' => $offset,
248 'total' => $total,
249 'complete' => false,
250 'percent' => 0,
251 ];
252 if ( $total ) {
253 $results['percent'] = 100 - ( ( $total - $offset ) * 100 / $total );
254 /**
255 * Операция индексирования состоит из дву�
256 этапов. Проверка существующи�
257 файлов и поиск новы�
258 файлов.
259 * Поэтому процент делим на 2. Это первая часть.
260 */
261 $results['percent'] = $results['percent'] / 2;
262 }
263
264 if ( $offset >= $total ) {
265 $results['percent'] = 100;
266 $results['complete'] = true;
267 }
268
269 wp_send_json( $results );
270 }
271 );
272
273 /**
274 * AJAX массовая оптимизация
275 */
276 /*
277 add_action( 'wp_ajax_wriop_process_cf_images', function () {
278 check_admin_referer( 'wio-iph' );
279 $reset_current_error = (bool) WRIO_Plugin::app()->request->request( 'reset_current_errors' );
280
281 // в ajax запросе мы не знаем, получен ли он из мультиадминки или из обычной. Поэтому проверяем параметр, полученный из frontend
282 if ( isset( $_POST['multisite'] ) and $_POST['multisite'] ) {
283 $multisite = new WIO_Multisite;
284 $multisite->initHooks();
285 }
286
287 $cf = WRIO_Custom_Folders::get_instance();
288
289 /*$folders = $cf->getFolders();
290
291 if ( ! empty( $folders ) ) {
292 foreach ( (array) $folders as $folder ) {
293 $folder = $cf->getFolder( $folder->get( 'uid' ) );
294 $count_files = $folder->countFiles();
295 $count_indexed_files = $folder->countIndexedFiles();
296 $test = 'fsdf';
297 }
298 }*/
299
300 /*
301 if ( $reset_current_error ) {
302 // сбрасываем текущие ошибки оптимизации
303 $cf->resetCurrentErrors();
304 }
305
306 $max_process_per_request = 1;
307 $optimized_data = $cf->processUnoptimizedImages( $max_process_per_request );
308
309 // если изображения закончились - посылаем команду завершения
310 if ( $optimized_data['remain'] <= 0 ) {
311 $optimized_data['end'] = true;
312 }
313 wp_send_json( $optimized_data );
314 } );*/
315
316 /**
317 * AJAX массовая оптимизация выбранной папки
318 */
319 /*
320 add_action( 'wp_ajax_wriop_process_cf_folder_images', function () {
321 check_admin_referer( 'wio-iph' );
322
323 // в ajax запросе мы не знаем, получен ли он из мультиадминки или из обычной. Поэтому проверяем параметр, полученный из frontend
324 if ( isset( $_POST['multisite'] ) and $_POST['multisite'] ) {
325 $multisite = new WIO_Multisite;
326 $multisite->initHooks();
327 }
328
329 $cf = WRIO_Custom_Folders::get_instance();
330 $max_process_per_request = 1;
331
332 add_filter( 'wriop_cf_current_folder', function ( $folder_uid ) {
333 $folder_uid = isset( $_POST['uid'] ) ? $_POST['uid'] : false;
334
335 return $folder_uid;
336 } );
337
338 $optimized_data = $cf->processUnoptimizedImages( $max_process_per_request );
339
340 // если изображения закончились - посылаем команду завершения
341 if ( $optimized_data['remain'] <= 0 ) {
342 $optimized_data['end'] = true;
343 }
344 wp_send_json( $optimized_data );
345 } );*/
346
347 /**
348 * Переоптимизация cf_image. AJAX
349 */
350 add_action(
351 'wp_ajax_wio_cf_reoptimize_image',
352 function () {
353 if ( ! check_ajax_referer( 'reoptimize', false, false ) || ! current_user_can( 'manage_options' ) ) {
354 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
355 }
356
357 $image_id = (int) $_POST['id'];
358 $backup = WRIOP_Backup::get_instance();
359 $backup_origin_images = WRIO_Plugin::app()->getPopulateOption( 'backup_origin_images', false );
360 $cf = WRIO_Custom_Folders::get_instance();
361
362 if ( $backup_origin_images and ! $backup->isBackupWritable() ) {
363 echo $cf->getMediaColumnContent( $image_id );
364 die();
365 }
366
367 wp_suspend_cache_addition( true );
368
369 $default_level = WRIO_Plugin::app()->getPopulateOption( 'image_optimization_level', 'normal' );
370 $level = isset( $_POST['level'] ) ? sanitize_text_field( $_POST['level'] ) : $default_level;
371
372 $optimized_data = $cf->optimizeImage( $image_id, $level );
373
374 if ( $optimized_data && isset( $optimized_data['processing'] ) ) {
375 echo 'processing'; // эту строку не локализировать!
376 die();
377 }
378
379 echo $cf->getMediaColumnContent( $image_id );
380 die();
381 }
382 );
383
384 /**
385 * Восстановление
386 */
387 add_action(
388 'wp_ajax_wio_cf_restore_image',
389 function () {
390 if ( ! check_ajax_referer( 'restore', false, false ) || ! current_user_can( 'manage_options' ) ) {
391 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
392 }
393
394 wp_suspend_cache_addition( true );
395 $image_id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
396
397 $cf = WRIO_Custom_Folders::get_instance();
398 $cf_image = $cf->getImage( $image_id );
399 $image_statistics = WRIO_Image_Statistic_Folders::get_instance();
400 if ( $cf_image->isOptimized() ) {
401 $restored = $cf_image->restore();
402 if ( ! is_wp_error( $restored ) ) {
403 $optimization_data = $cf_image->getOptimizationData();
404 $optimized_size = $optimization_data->get_final_size();
405 $original_size = $optimization_data->get_original_size();
406 $webp_optimized_size = $optimization_data->get_extra_data()->get_webp_main_size();
407 $image_statistics->deductFromField( 'webp_optimized_size', $webp_optimized_size );
408 $image_statistics->deductFromField( 'optimized_size', $optimized_size );
409 $image_statistics->deductFromField( 'original_size', $original_size );
410 $image_statistics->save();
411
412 $folder = $cf->getFolder( $cf_image->get( 'folder_uid' ) );
413 $folder->reCountOptimizedFiles();
414 $cf->saveFolders();
415 }
416 }
417
418 echo $cf->getMediaColumnContent( $image_id );
419 die();
420 }
421 );
422
423 /**
424 * AJAX обработчик восстановления из резервной копии
425 */
426 /*
427 add_action( 'wp_ajax_wio_cf_restore_backup', function () {
428 check_admin_referer( 'wio-iph' );
429 $max_process_per_request = 10; // сколько картинок восстанавливаем за 1 запрос
430 $total = sanitize_text_field( $_POST['total'] );
431 if ( isset( $_POST['blog_id'] ) && $_POST['blog_id'] ) {
432 switch_to_blog( intval( $_POST['blog_id'] ) );
433 }
434 $folder_uid = isset( $_POST['uid'] ) ? sanitize_text_field( $_POST['uid'] ) : false;
435 $cf = WRIO_Custom_Folders::get_instance();
436 if ( $total == '?' ) {
437 $total = RIO_Process_Queue::count_by_type_status( 'cf_image', 'success' );
438 }
439 $restored_data = $cf->restoreFolderFromBackup( $folder_uid, $max_process_per_request );
440 if ( isset( $_POST['blog_id'] ) && $_POST['blog_id'] ) {
441 restore_current_blog();
442 }
443 $restored_data['total'] = $total;
444 if ( $total ) {
445 $restored_data['percent'] = 100 - ( $restored_data['remain'] * 100 / $total );
446 } else {
447 $restored_data['percent'] = 0;
448 }
449 // если изображения закончились - посылаем команду завершения
450 if ( $restored_data['remain'] <= 0 ) {
451 $restored_data['end'] = true;
452 }
453 wp_send_json( $restored_data );
454 } );*/
455
456 /**
457 * Загружает шаблон для всплывающий окон
458 */
459 /*
460 add_action( 'wp_ajax_wio_cf_get_template_part', function () {
461 $template = sanitize_text_field( $_POST['template'] );
462 $templates = [
463 'select_folder' => 'select-folder.php',
464 'restore_folder' => 'restore-folder.php',
465 'sync_folder' => 'sync-folder.php',
466 'optimize_folder' => 'optimize-folder.php',
467 'sync_all_folders' => 'sync-all-folders.php',
468 'folders_table_body' => 'folders-table-body.php',
469 ];
470 if ( isset( $templates[ $template ] ) ) {
471 $template_file = WRIOP_PLUGIN_DIR . '/admin/pages/parts/' . $templates[ $template ];
472 if ( file_exists( $template_file ) ) {
473 include( $template_file );
474 }
475 }
476 die();
477 } );*/
478
479 /**
480 * Загружает шаблон для всплывающий окон
481 */
482 add_action(
483 'wp_ajax_wio_cf_reload_ui',
484 function () {
485 if ( ! check_ajax_referer( 'bulk_optimization', false, false ) || ! current_user_can( 'manage_options' ) ) {
486 wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
487 }
488
489 $template_file = WRIOP_PLUGIN_DIR . '/admin/pages/parts/folders-table-body.php';
490 $folders_table = '';
491 if ( is_file( $template_file ) ) {
492 ob_start();
493 include $template_file;
494 $folders_table = ob_get_contents();
495 ob_end_clean();
496 }
497 $image_statistics = WRIO_Image_Statistic_Folders::get_instance();
498 $responce = [
499 'folders_table' => $folders_table,
500 'statistic' => $image_statistics->load(),
501 ];
502 wp_send_json( $responce );
503 }
504 );
505