PluginProbe ʕ •ᴥ•ʔ
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager / 2.9.3
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager v2.9.3
3.1.9 3.1.8 3.1.7 2.9.3 2.9.4 2.9.5 2.9.6 2.9.7 2.9.8 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.2 3.1.3 3.1.4 3.1.5 3.1.6 trunk 1.3.7 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.1.7 2.1.8 2.1.9 2.2 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.2.8 2.2.9 2.3 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.3.8 2.3.9 2.4 2.4.1 2.4.2 2.4.3 2.4.4 2.4.5 2.4.6 2.4.7 2.4.8 2.4.9 2.5 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 2.5.7 2.5.8 2.5.9 2.6 2.6.1 2.6.2 2.6.3 2.6.4 2.6.5 2.6.6 2.6.7 2.6.8 2.6.9 2.7 2.7.1 2.7.2 2.7.3 2.7.4 2.7.5 2.8 2.8.1 2.8.2 2.8.3 2.8.4 2.8.5 2.8.6 2.8.7 2.8.8 2.8.9 2.9 2.9.1 2.9.2
folders / includes / media.replace.php
folders / includes Last commit date
class-affiliate.php 3 years ago class-polylang.php 3 years ago class-review-box.php 3 years ago class-upgrade-box.php 3 years ago class-wpml.php 3 years ago folders.class.php 3 years ago form.class.php 3 years ago media.replace.php 2 years ago plugins.class.php 3 years ago tree.class.php 3 years ago
media.replace.php
1834 lines
1 <?php
2 /**
3 * Class Folders Replace Media
4 *
5 * @author : Premio <contact@premio.io>
6 * @license : GPL2
7 * */
8
9 if (! defined('ABSPATH')) {
10 exit;
11 }
12
13 class folders_replace_media {
14
15 /**
16 * Button Color
17 *
18 * @var string $buttonColor Replacement Button Color
19 * @since 1.0.0
20 * @access public
21 */
22 public $buttonColor;
23
24 /**
25 * Is Replacement functionality enabled or not
26 *
27 * @var string $isEnabled Replacement Functionality Status
28 * @since 1.0.0
29 * @access public
30 */
31 public $isEnabled = false;
32
33 /**
34 * Folders Upgrade Link
35 *
36 * @var string $upgradeLink Upgrade Link
37 * @since 1.0.0
38 * @access public
39 */
40 public $upgradeLink;
41
42 /**
43 * Old file path
44 *
45 * @var string $oldFilePath Old File Path
46 * @since 1.0.0
47 * @access public
48 */
49 public $oldFilePath;
50
51 /**
52 * Old file URL
53 *
54 * @var string $oldFilePath Old File URL
55 * @since 1.0.0
56 * @access public
57 */
58 public $oldFileURL;
59
60 /**
61 * New file Path
62 *
63 * @var string $newFilePath New File Path
64 * @since 1.0.0
65 * @access public
66 */
67 public $newFilePath;
68
69 /**
70 * New file URL
71 *
72 * @var string $newFilePath New File URL
73 * @since 1.0.0
74 * @access public
75 */
76 public $newFileURL;
77
78 /**
79 * Mode for file Replacement
80 *
81 * @var string $mode New File URL
82 * @since 1.0.0
83 * @access public
84 */
85 public $mode = "rename-file";
86
87 /**
88 * Old image Meta Array
89 *
90 * @var array $oldImageMeta Old image Meta Array
91 * @since 1.0.0
92 * @access public
93 */
94 public $oldImageMeta;
95
96 /**
97 * New image Meta Array
98 *
99 * @var array $newImageMeta New image Meta Array
100 * @since 1.0.0
101 * @access public
102 */
103 public $newImageMeta;
104
105 /**
106 * WordPress Upload Dir Path
107 *
108 * @var string $uploadDir WordPress Upload Dir Path
109 * @since 1.0.0
110 * @access public
111 */
112 public $uploadDir;
113
114 /**
115 * Check if old file is image
116 *
117 * @var string $isOldImage Old file status
118 * @since 1.0.0
119 * @access public
120 */
121 public $isOldImage = 0;
122
123 /**
124 * Check if uploaded file is image
125 *
126 * @var string $isNewImage New file status
127 * @since 1.0.0
128 * @access public
129 */
130 public $isNewImage = 0;
131
132 /**
133 * Attachment ID for Replacement file
134 *
135 * @var string $attachment_id Attachment ID
136 * @since 1.0.0
137 * @access public
138 */
139 public $attachment_id;
140
141 /**
142 * Collection of Replacement Items
143 *
144 * @var array $replaceItems Replacement Items
145 * @since 1.0.0
146 * @access public
147 */
148 public $replaceItems = [];
149
150 /**
151 * Old File Path
152 *
153 * @var array $old_file_path Old File Path
154 * @since 1.0.0
155 * @access public
156 */
157 public $old_file_path;
158
159 /**
160 * Old File URL
161 *
162 * @var array $old_file_url Old File URL
163 * @since 1.0.0
164 * @access public
165 */
166 public $old_file_url;
167
168 /**
169 * New file path
170 *
171 * @var array $new_file_path New file path
172 * @since 1.0.0
173 * @access public
174 */
175 public $new_file_path;
176
177 /**
178 * New file URL
179 *
180 * @var array $new_file_url New file URL
181 * @since 1.0.0
182 * @access public
183 */
184 public $new_file_url;
185
186 /**
187 * Old Image Meta
188 *
189 * @var array $old_image_meta Old Image Meta
190 * @since 1.0.0
191 * @access public
192 */
193 public $old_image_meta;
194
195 /**
196 * New Image Meta
197 *
198 * @var array $new_image_meta New Image Meta
199 * @since 1.0.0
200 * @access public
201 */
202 public $new_image_meta;
203
204 /**
205 * Upload dir path
206 *
207 * @var array $upload_dir Upload dir path
208 * @since 1.0.0
209 * @access public
210 */
211 public $upload_dir;
212
213 /**
214 * Old file image status
215 *
216 * @var array $is_old_image Old file image status
217 * @since 1.0.0
218 * @access public
219 */
220 public $is_old_image = 0;
221
222 /**
223 * New file image status
224 *
225 * @var array $is_new_image New file image status
226 * @since 1.0.0
227 * @access public
228 */
229 public $is_new_image = 0;
230
231
232 /**
233 * Define the core functionality of the replacement functionality.
234 *
235 * Set Button Color
236 * Check for Functionality is enabled or not
237 * Show Replacement form, Success message
238 *
239 * @since 1.0.0
240 */
241 function __construct() {
242
243 add_action("init", array($this,"init"));
244
245 $customize_folders = get_option('customize_folders');
246
247 $this->buttonColor = isset($customize_folders['media_replace_button'])?$customize_folders['media_replace_button']:"#FA166B";
248
249 $this->isEnabled = isset($customize_folders['folders_enable_replace_media'])?$customize_folders['folders_enable_replace_media']:"yes";
250
251 $this->replace_media_title = isset($customize_folders['replace_media_title'])?$customize_folders['replace_media_title']:"off";
252
253 $this->isEnabled = ($this->isEnabled == "yes")?true:false;
254
255 if (isset($customize_folders['show_folder_in_settings']) && $customize_folders['show_folder_in_settings'] == "yes") {
256 $this->upgradeLink = admin_url("options-general.php?page=wcp_folders_settings&setting_page=upgrade-to-pro");
257 } else {
258 $this->upgradeLink = admin_url("admin.php?page=folders-upgrade-to-pro");
259 }
260
261 if($this->isEnabled) {
262
263 add_action('admin_menu', array($this, 'admin_menu'));
264 //
265 add_filter('media_row_actions', array($this, 'add_media_action'), 10, 2);
266
267 add_action('add_meta_boxes', function () {
268 add_meta_box('folders-replace-box', esc_html__('Replace Media', 'folders'), array($this, 'replace_meta_box'), 'attachment', 'side', 'low');
269 });
270 add_filter('attachment_fields_to_edit', array($this, 'attachment_editor'), 10, 2);
271
272 add_action('admin_enqueue_scripts', array($this, 'folders_admin_css_and_js'));
273
274 add_action('admin_init', array($this, 'handle_folders_file_upload'));
275 }
276
277 /* to replace file name */
278 add_action('add_meta_boxes', function () {
279 add_meta_box('folders-replace-file-name', esc_html__('Change file name', 'folders'), array($this, 'change_file_name_box'), 'attachment', 'side', 'core');
280 });
281
282 add_action('edit_attachment', array($this, 'change_file_name_on_update' ));
283
284 add_filter('attachment_fields_to_edit', array($this, 'attachment_replace_name_with_title'), 10, 2);
285
286 add_action('admin_head', array($this, 'premio_replace_file_CSS'));
287
288 add_action('wp_enqueue_media', array($this, 'replace_media_file_script'));
289
290 add_action('wp_ajax_premio_folder_replace_name_with_title', array($this, 'replace_name_with_title'));
291
292 add_action('wp_ajax_premio_folder_update_wp_config', array($this, 'update_wp_config'));
293
294 if(isset($customize_folders['enable_media_trash']) && $customize_folders['enable_media_trash'] == "on") {
295 add_action('admin_notices', array($this, 'admin_notices'));
296
297 add_action('admin_footer', array($this, 'admin_footer'));
298 } else {
299 add_action('admin_notices', array($this, 'enable_media_notices'));
300 }
301
302 add_action('admin_notices', array($this, 'admin_premio_notices'));
303
304 add_filter('wp_get_attachment_image_src', array($this, 'update_to_new_url'), 10, 4);
305
306 add_filter('wp_prepare_attachment_for_js', array($this, 'prepare_attachment_for_js'), 10, 3);
307
308 }
309
310 /**
311 * Add admin init
312 *
313 * @since 2.6.3
314 * @access public
315 */
316 public function init() {
317 if(isset($_GET['enable_trash']) && !empty($_GET['enable_trash'])) {
318 $nonce = sanitize_text_field($_GET['enable_trash']);
319 if(wp_verify_nonce($nonce, "folders_enable_media_trash")) {
320 $customize_folders = get_option('customize_folders');
321 $customize_folders['enable_media_trash'] = "on";
322 update_option("customize_folders", $customize_folders);
323 wp_redirect(admin_url("upload.php?page=folders-media-cleaning"));
324 exit;
325 }
326 }
327 }
328
329 /**
330 * Update Cached file URL
331 *
332 * @since 2.8.4
333 * @access public
334 *
335 */
336 public function prepare_attachment_for_js($response, $attachment, $meta) {
337 if ($response === false) {
338 return $response;
339 }
340
341 $refreshToken = get_post_meta($response['id'], "folders_file_replaced", true);
342 if($refreshToken !== false && !empty($refreshToken)) {
343 $response['url'] = add_query_arg('ver', $refreshToken, $response['url']);
344 if(isset($response['sizes']['medium']['url']) && !empty($response['sizes']['medium']['url'])) {
345 $response['sizes']['medium']['url'] = add_query_arg('ver', $refreshToken, $response['sizes']['medium']['url']);
346 }
347 }
348 return $response;
349 }
350
351 /**
352 * Update Cached file URL
353 *
354 * @since 2.8.4
355 * @access public
356 *
357 */
358 public function update_to_new_url($image, $attachment_id, $size, $icon) {
359 if ($image === false)
360 return $image;
361
362 $refreshToken = get_post_meta($attachment_id, "folders_file_replaced", true);
363 if($refreshToken !== false && !empty($refreshToken)) {
364 $image[0] = add_query_arg('ver', $refreshToken, $image[0]);
365 }
366 return $image;
367 }
368
369 /**
370 * Show media details on hover
371 *
372 * @since 2.6.3
373 * @access public
374 *
375 */
376 public function admin_premio_notices() {
377 if(isset($_REQUEST['premio_message']) && $_REQUEST['premio_message'] == "success") { ?>
378 <div class="notice notice-success is-dismissible">
379 <p><b><?php esc_html_e( 'File successfully replaced', 'folders' ); ?></b></p>
380 <p><?php esc_html_e( 'The file has been successfully replaced using the file replacement feature', 'folders' ); ?></p>
381 </div>
382
383 <style>
384 .folders-undo-notification {
385 position: fixed;
386 right: -500px;
387 bottom: 25px;
388 width: 280px;
389 background: #fff;
390 padding: 15px;
391 -webkit-box-shadow: 0 3px 6px -4px rgb(0 0 0 / 12%), 0 6px 16px 0 rgb(0 0 0 / 8%), 0 9px 28px 8px rgb(0 0 0 / 5%);
392 box-shadow: 0 3px 6px -4px rgb(0 0 0 / 12%), 0 6px 16px 0 rgb(0 0 0 / 8%), 0 9px 28px 8px rgb(0 0 0 / 5%);
393 transition: all .25s linear;
394 z-index: 250010;
395 }
396 .folders-undo-body {
397 position: relative;
398 font-size: 13px;
399 padding: 0 0 5px 0;
400 }
401 .close-undo-box {
402 position: absolute;
403 right: -10px;
404 top: 0;
405 width: 16px;
406 height: 16px;
407 transition: all .25s linear;
408 }
409 .close-undo-box span {
410 display: block;
411 position: relative;
412 width: 16px;
413 height: 16px;
414 transition: all .2s linear;
415 }
416 .close-undo-box span:after, .close-undo-box span:before {
417 content: "";
418 position: absolute;
419 width: 12px;
420 height: 2px;
421 background-color: #333;
422 display: block;
423 border-radius: 2px;
424 transform: rotate(45deg);
425 top: 7px;
426 left: 2px;
427 }
428 .close-undo-box span:after {
429 transform: rotate(-45deg);
430 }
431 .folders-undo-header {
432 font-weight: 500;
433 font-size: 14px;
434 padding: 0 0 3px 0;
435 color: #014737;
436 }
437 .folders-undo-notification.success {
438 border-left: solid 3px #70C6A3;
439 }
440 html[dir="rtl"] .folders-undo-notification {
441 right: auto;
442 left: -500px
443 }
444 html[dir="rtl"] .folders-undo-notification.active {
445 left: 25px;
446 }
447 html[dir="rtl"] .folders-undo-notification.success {
448 border-left: none;
449 border-right: solid 3px #70C6A3;
450 }
451 html[dir="rtl"] .close-undo-box {
452 right: auto;
453 left: -10px;
454 }
455 </style>
456 <div class="folders-undo-notification success" id="media-success">
457 <div class="folders-undo-body">
458 <a href="javascript:;" class="close-undo-box"><span></span></a>
459 <div class="folders-undo-header"><?php esc_html_e( 'File successfully replaced', 'folders' ); ?></div>
460 <div class="folders-undo-body" style="padding:0"><?php esc_html_e( 'The file has been successfully replaced using the file replacement feature', 'folders' ); ?></div>
461 </div>
462 </div>
463 <script>
464 jQuery(document).ready(function(){
465 jQuery("#media-success").addClass("active");
466 setTimeout(function(){
467 jQuery("#media-success").removeClass("active");
468 }, 5000);
469
470 jQuery(document).on("click", ".close-undo-box", function(){
471 jQuery("#media-success").removeClass("active");
472 });
473 });
474 </script>
475 <?php }
476 }
477
478 /**
479 * Show media details on hover
480 *
481 * @since 2.6.3
482 * @access public
483 *
484 */
485 public function admin_footer() { ?>
486 <script>
487 (function($) {
488 "use strict";
489 $(document).ready(function(){
490 $("#menu-media ul").append("<li class='media-trash-menu'><a class='media-trash' href='upload.php?mode=list&attachment-filter=trash&media_folder='><?php esc_html_e("Trash","folders"); ?></a></li>");
491 <?php if(isset($_REQUEST['attachment-filter']) && $_REQUEST['attachment-filter']=="trash") { ?>
492 $("#menu-media .current").removeClass("current");
493 $("#menu-media .media-trash-menu").addClass("current");
494 $(".wp-filter .view-switch a").remove();
495 $(".wp-filter .view-switch").css("height","28px").css("margin", "0");
496 <?php } ?>
497 });
498 })(jQuery);
499 </script>
500 <?php }
501
502 /**
503 * Admin notice for to show media message
504 *
505 * @since 2.6.3
506 * @access public
507 *
508 */
509 public function enable_media_notices() {
510 $is_defined = defined( 'MEDIA_TRASH' );
511 if ( !($is_defined && MEDIA_TRASH )) {
512 if (isset($_REQUEST['page']) && $_REQUEST['page'] == "folders-media-cleaning") { ?>
513 <style>
514 .media-trash-notice{padding:0!important;margin:15px 15px 0}.media-trash-notice-message{padding:10px;line-height: 30px}.media-trash-notice a{text-decoration:none}.media-trash-notice-footer{text-align:right;padding:10px 15px;background:#f1f1f1;margin:15px 0 0 0}.spinner.trash-spinner{display:none}.spinner.trash-spinner.animate{display:inline-block;opacity:.7;visibility:visible;margin-right:0}.float-right{float:right;}
515 </style>
516 <div class="notice notice-info premio-notice media-trash-notice">
517 <div class="media-trash-notice-message">
518 Enable move files to trash feature on Folders to temporarily delete files before deleting permanently
519 <a class="button button-primary float-right" href="<?php echo admin_url("upload.php?page=folders-media-cleaning&enable_trash=".wp_create_nonce("folders_enable_media_trash")) ?>" >Enable</a>
520 </div>
521 </div>
522 <?php }
523 }
524 }
525
526 /**
527 * Admin notice for to show WP_TRASH functionality
528 *
529 * @since 2.6.3
530 * @access public
531 *
532 */
533 public function admin_notices() {
534 $is_defined = defined( 'MEDIA_TRASH' );
535 if ( !($is_defined && MEDIA_TRASH )) {
536 global $current_screen;
537 if ((isset($current_screen->base) && $current_screen->base == "upload") || (isset($_REQUEST['page']) && ($_REQUEST['page'] == "wcp_folders_settings" || $_REQUEST['page'] == "folders-media-cleaning"))) { ?>
538 <style>
539 .media-trash-notice{padding:0 !important;margin:15px 15px 0}.media-trash-notice-message{padding:15px 10px 0}.media-trash-notice a{text-decoration:none}.media-trash-notice-footer{text-align:right;padding:10px 15px;background:#f1f1f1;margin:15px 0 0 0}.spinner.trash-spinner{display:none}.spinner.trash-spinner.animate{display:inline-block;opacity:.7;visibility:visible;margin-right:0}
540 </style>
541 <div class="notice notice-info premio-notice media-trash-notice">
542 <div class="media-trash-notice-message">
543 To enable Trash functionality in Media, Add the following one line <code>define( 'MEDIA_TRASH', true );</code> in <a href="https://wordpress.org/support/article/editing-wp-config-php/" rel="noopener noreferrer" target="_blank">wp-config.php</a> file just before the line that says "That’s all, stop editing!"
544 </div>
545 <div class="media-trash-notice-footer">
546 <a class="button button-primary" href="#">Automatically write this line<span class="spinner trash-spinner"></span></a>
547 </div>
548 </div>
549
550 <style>
551 .folder-popup-form{position:fixed;width:100%;height:100%;background:rgba(0,0,0,.5);top:0;left:0;z-index:10001;display:none}.popup-form-content{background:#fff;min-height:100px;width:400px;text-align:center;margin:0 auto;position:absolute;left:0;right:0;top:50%;transform:translate(0,-50%);-webkit-transform:translate(0,-50%);-moz-transform:translate(0,-50%);-o-transform:translate(0,-50%);-ms-transform:translate(0,-50%);padding:20px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;color:#484848}.popup-form-data{position:relative}.close-popup-button{position:absolute;right:-10px;top:-10px;width:20px;height:20px}.close-popup-button a{display:block;position:relative;width:20px;height:20px;color:#333;padding:2px;box-sizing:border-box}.close-popup-button a span{display:block;position:relative;width:16px;height:16px;transition:all .2s linear}.close-popup-button a:hover span{transform:rotate(180deg)}.close-popup-button a span:after,.close-popup-button a span:before{content:"";position:absolute;width:12px;height:2px;background-color:#333;display:block;border-radius:2px;transform:rotate(45deg);top:7px;left:2px}.close-popup-button a span:after{transform:rotate(-45deg)}.add-update-folder-title{display:block;position:relative;max-width:100%;margin:0;padding:0 0 15px 0;color:#595959;text-align:center;text-transform:none;word-wrap:break-word;font-weight:700;font-size:22px;line-height:26px}.add-update-folder-title:after{content:"";position:absolute;top:100%;width:70px;height:2px;background:#3085d6;left:0;right:0;margin:0 auto}.folder-form-buttons{display:flex}.folder-form-buttons a:not(.inline-button),.folder-form-buttons button{display:inline-flex;padding:0;text-decoration:none;margin:10px 3px;border-radius:4px;border:solid 1px #1da1f4;line-height:34px;font-weight:700;font-size:14px;box-sizing:border-box;height:36px;cursor:pointer;flex:1;justify-content:center}.form-cancel-btn,a.form-cancel-btn:hover{background-color:#fff;color:#3085d6;outline:0}.form-submit-btn{background-color:#3085d6;color:#fff;outline:0}.form-submit-btn.disabled{color:#a7aaad!important;background:#f6f7f7!important;border-color:#dcdcde!important;box-shadow:none!important;text-shadow:none!important;cursor:default}.folder-note{padding:20px 0;line-height:20px}#folder-trash-message .popup-form-content{width:460px}.folder-note a{text-decoration:none;display:inline-block}
552 </style>
553 <?php if(isset($_REQUEST['mode']) && $_REQUEST['mode'] == "list" && isset($_REQUEST['attachment-filter']) && $_REQUEST['attachment-filter'] == "trash") { ?>
554
555 <div class="folder-popup-form" id="folder-trash-message" style="display: block;">
556 <div class="popup-form-content">
557 <div class="popup-form-data">
558 <div class="close-popup-button">
559 <a class="" href="javascript:;"><span></span></a>
560 </div>
561 <form action="" method="post" id="save-folder-form">
562 <div class="add-update-folder-title">Rewrite wp-config.php to enable Trash</div>
563 <div class="folder-note">
564 To enable Trash functionality in Media, Add the following one line <code>define( 'MEDIA_TRASH', true );</code> in <a href="https://wordpress.org/support/article/editing-wp-config-php/" rel="noopener noreferrer" target="_blank">wp-config.php</a> file just before the line that says "That’s all, stop editing!"
565 </div>
566 <div class="folder-form-buttons">
567 <a href="javascript:;" class="form-cancel-btn">I'll do it manually</a>
568 <button type="submit" class="form-submit-btn write-in-config-file">Automatically write this line</button>
569 </div>
570 </form>
571 </div>
572 </div>
573 </div>
574 <div class="folder-popup-form" id="wp-config-update-notice" style="display: none;">
575 <form action="" method="post" id="bulk-folder-form">
576 <div class="popup-form-content">
577 <div class="popup-form-data">
578 <div class="close-popup-button">
579 <a class="" href="javascript:;"><span></span></a>
580 </div>
581 <div class="add-update-folder-title">
582 Something went wrong
583 </div>
584 <div class="folder-form-message" style="padding: 25px 10px;">
585 We couldn’t write to the file automatically. Please add the line manually to your wp-config.php. You need to modify your wp-config.php file and just before the line that says "That’s all, stop editing!", add this line:<code>define( 'MEDIA_TRASH', true );</code>
586 </div>
587 </div>
588 </div>
589 </form>
590 </div>
591 <?php } ?>
592
593 <script>
594 (function($) {
595 "use strict";
596 $(document).ready(function(){
597 $(document).on("click", ".media-trash-notice-footer a:not(.disabled), .write-in-config-file:not(.disabled)", function(e){
598 $(this).addClass("disabled");
599 $(".trash-spinner").addClass("animate");
600 e.preventDefault();
601 $.ajax({
602 url: "<?php echo site_url("wp-admin/admin-ajax.php") ?>",
603 data: {
604 action: "premio_folder_update_wp_config",
605 nonce: "<?php echo wp_create_nonce("add_media_status_in_wp_config") ?>"
606 },
607 type: 'post',
608 dataType: "json",
609 success: function(response) {
610 if(response.status == 1) {
611 setTimeout(function(){
612 window.location.reload();
613 }, 4000);
614 $("#folder-trash-message").remove();
615 } else {
616 $(".trash-spinner").removeClass("animate");
617 $(".media-trash-notice-footer a").removeClass("disabled");
618 $("#wp-config-update-notice").show();
619 $("#folder-trash-message").remove();
620 }
621 }
622 });
623 });
624
625 $(document).on("click", "#folder-trash-message", function(){
626 $("#folder-trash-message").hide();
627 });
628
629 $(document).on("click", "#folder-trash-message .popup-form-content", function(e){
630 e.stopPropagation();
631 });
632
633 <?php if(isset($_REQUEST['mode']) && $_REQUEST['mode'] == "list" && isset($_REQUEST['attachment-filter']) && $_REQUEST['attachment-filter'] == "trash") { ?>
634 $(document).on("click", ".close-popup-button, .form-cancel-btn", function(e){
635 e.preventDefault();
636 $("#folder-trash-message").remove();
637 $(".folder-popup-form").remove();
638 });
639 <?php } ?>
640 });
641 })(jQuery);
642 </script>
643 <?php }
644 }
645
646 $isScanPage = (isset($_REQUEST['page']) && $_REQUEST['page'] == "folders-media-cleaning" && (isset($_REQUEST['scan']) && $_REQUEST['scan'] == 1))?true:false;
647 $isFilterPage = (isset($_REQUEST['attachment-filter']) && $_REQUEST['attachment-filter'] == "trash")?true:false;
648
649 if ($isScanPage || $isFilterPage) { ?>
650 <style>
651 .media-notice {
652 margin: 15px 15px 2px;
653 }
654 .media-folder-notice {
655 display: flex;
656 align-items: baseline;
657 }
658 .media-folder-notice-left {
659 flex: 0 0 35px;
660 color: #d63638;
661 }
662 .media-folder-notice-right {
663 flex: 1;
664 font-size: 14px;
665 }
666 .media-folder-notice-right p {
667 font-size: 14px;
668 }
669 .media-folder-notice span.dashicons.dashicons-info-outline {
670 padding: 4px;
671 background-color: #fff2f2;
672 border-radius: 50%;
673 }
674 .media-folder-notice b {
675 font-weight: 600;
676 }
677 </style>
678 <div class="notice notice-error media-notice">
679 <div class="media-folder-notice">
680 <div class="media-folder-notice-left">
681 <span class="dashicons dashicons-info-outline"></span>
682 </div>
683 <div class="media-folder-notice-right">
684 <p>Please <b>be very careful before deleting</b> any files. <b>Take back up</b>, and make sure you test the website <b>before permanently deleting</b>. Some actively used files can still show up as unused files when searching. You <b>are responsible</b> for any damage if you delete anything important. So, please be careful 🙏</p>
685 </div>
686 </div>
687 </div>
688 <?php }
689 }
690
691 /**
692 * Update config.php file to save WP_TRASH functionality
693 *
694 * @since 2.6.3
695 * @access public
696 *
697 */
698 public function update_wp_config() {
699 $errorCounter = 0;
700 $response = array();
701 $response['status'] = 0;
702 $response['message'] = "";
703 $response['valid'] = 0;
704 $postData = filter_input_array(INPUT_POST);
705 if (!isset($postData['nonce']) || trim($postData['nonce']) == "") {
706 $errorCounter++;
707 $response['message'] = "Invalid request";
708 } else {
709 $nonce = sanitize_title($postData['nonce']);
710 if(!wp_verify_nonce($nonce, 'add_media_status_in_wp_config')) {
711 $errorCounter++;
712 $response['message'] = "Invalid request";
713 }
714 }
715 if($errorCounter == 0) {
716 $response['status'] = 1;
717
718 $is_defined = defined( 'MEDIA_TRASH' );
719 if ( $is_defined && MEDIA_TRASH ) {
720 echo json_encode($response);
721 die;
722 }
723
724 try {
725 $conf = ABSPATH . 'wp-config.php';
726 $stream = fopen( $conf, 'r+' );
727 if ( $stream === false ) {
728 $response['status'] = -1;
729 echo json_encode($response); die;
730 }
731
732 try {
733 if ( !flock( $stream, LOCK_EX ) ) {
734 $response['status'] = -1;
735 echo json_encode($response); die;
736 }
737 $stat = fstat( $stream );
738
739 /* Find out the ideal position to write on */
740 $found = false;
741 $patterns = array (
742 array (
743 'regex' => '^\/\*\s*' . preg_quote( "That's all, stop editing!" ) . '.*?\s*\*\/',
744 'where' => 'above'
745 )
746 );
747 $current = 0;
748 while ( !feof( $stream ) ) {
749 $line = fgets( $stream ); // Read line by line
750 if ( $line === false ) break; // No more lines
751 $prev = $current; // Previous position
752 $current = ftell( $stream ); // Current position
753 foreach ( $patterns as $item ) {
754 if ( !preg_match( '/'.$item['regex'].'/', trim( $line ) ) ) {
755 continue;
756 }
757 $found = true;
758 if ( $item['where'] == 'above' ) {
759 fseek( $stream, $prev );
760 $current = $prev;
761 }
762 break 2;
763 }
764 }
765
766 /* Check if the position is found */
767 if ( !$found ) {
768 $response['status'] = -1;
769 echo json_encode($response); die;
770 }
771
772 /* Write the constant definition line */
773 $new = "define( 'MEDIA_TRASH', true );" . PHP_EOL;
774 $rest = fread( $stream, $stat['size'] - $current );
775 fseek( $stream, $current );
776 $written = fwrite( $stream, $new . $rest );
777
778 /* All done */
779 if ( $written === false ) {
780 $response['status'] = -1;
781 echo json_encode($response); die;
782 }
783 fclose( $stream );
784 }
785 catch ( Exception $e ) {
786 fclose( $stream );
787
788 $response['status'] = -1;
789 echo json_encode($response); die;
790 }
791 }
792 catch ( Exception $e ) {
793 $response['status'] = -1;
794 echo json_encode($response); die;
795 }
796
797 echo json_encode($response); die;
798 }
799 echo json_encode($response); die;
800 }
801
802 /**
803 * Replace file name with title
804 *
805 * @since 2.6.3
806 * @access public
807 *
808 */
809 public function replace_name_with_title() {
810 $errorCounter = 0;
811 $response = array();
812 $response['status'] = 0;
813 $response['message'] = "";
814 $response['valid'] = 0;
815 $postData = filter_input_array(INPUT_POST);
816 if (!isset($postData['post_id']) || trim($postData['post_id']) == "") {
817 $errorCounter++;
818 $response['message'] = "Invalid request";
819 } else if (!isset($postData['nonce']) || trim($postData['nonce']) == "") {
820 $errorCounter++;
821 $response['message'] = "Invalid request";
822 } else if (!isset($postData['post_title']) || trim($postData['post_title']) == "") {
823 $errorCounter++;
824 $response['message'] = "Invalid request";
825 } else {
826 $nonce = sanitize_title($postData['nonce']);
827 if(!wp_verify_nonce($nonce, 'change_attachment_title_'.$postData['post_id'])) {
828 $errorCounter++;
829 $response['message'] = "Invalid request";
830 }
831 }
832 if($errorCounter == 0) {
833 $response['status'] = 1;
834
835 $post_id = $postData['post_id'];
836
837 $post = get_post($post_id);
838
839 $post_slug = sanitize_file_name(sanitize_text_field($_POST['post_title']));
840
841 $attachment_url = $post->guid;
842 $url = wp_get_attachment_url($post_id);
843 if(!empty($url)) {
844 $attachment_url = $url;
845 }
846 $file_parts = pathinfo($attachment_url);
847
848 $db_file_name = $file_parts['basename'];
849 $db_file_array = explode(".", $db_file_name);
850 $db_file_name_ext = array_pop($db_file_array);
851 $db_file_name = trim($db_file_name, $db_file_name_ext);
852 $db_file_name = trim($db_file_name, ".");
853
854 if(strtolower($db_file_name) == strtolower($post_slug)) {
855 $response['valid'] = 0;
856 $response['message'] = esc_html__("The title is same as the current filename", "folders");
857 } else {
858 $response['valid'] = 1;
859 $response['message'] = esc_html__("File name has been updated", "folders");
860 $this->change_file_name_with_title($post_id);
861 }
862 }
863 echo json_encode($response);
864 exit;
865 }
866
867 /**
868 * Add Js and CSS files for replace file name with title
869 *
870 * @since 2.6.3
871 * @access public
872 *
873 */
874 public function replace_media_file_script() {
875 wp_enqueue_script('folders-media-replace-js', WCP_FOLDER_URL . 'assets/js/replace-file-name.js', array('jquery'), WCP_FOLDER_VERSION, true);
876 wp_localize_script('folders-media-replace-js', 'replace_media_options', array(
877 'ajax_url' => admin_url("admin-ajax.php"),
878 ));
879 }
880
881 public function premio_replace_file_CSS() {
882 echo '<style>
883 .compat-field-replace_file_name th.label {display: none;}
884 .compat-field-replace_file_name td.field {width: 100%; border-top: solid 1px #c0c0c0; padding:10px 0 0 0;margin: 0;float: none;}
885 .compat-field-replace_file_name td.field label {width: 100%; display: block;padding:0 0 10px 0;}
886 .compat-field-replace_file_name td.field label input[type="checkbox"] {margin: 0 4px 0 2px;}
887 .compat-field-replace_file_name td.field button.update-name-with-title {display: none;}
888 .compat-field-replace_file_name td.field button.update-name-with-title.show {display: inline-block;}
889
890 .compat-field-folders th.label {width: 100%; text-align: left; padding: 0 0 10px 0; margin: 0; border-top: solid 1px #c0c0c0;float: none;}
891 .compat-field-folders th.label .alignleft {float: none; text-align: left; font-weight: bold;}
892 .compat-field-folders th.label br {display: none;}
893 .compat-field-folders td.field {width: 100%; padding: 0; margin: 0;float: none;}
894 .folders-undo-notification{position:fixed;right:-500px;bottom:25px;width:280px;background:#fff;padding:15px;-webkit-box-shadow:0 3px 6px -4px rgb(0 0 0 / 12%),0 6px 16px 0 rgb(0 0 0 / 8%),0 9px 28px 8px rgb(0 0 0 / 5%);box-shadow:0 3px 6px -4px rgb(0 0 0 / 12%),0 6px 16px 0 rgb(0 0 0 / 8%),0 9px 28px 8px rgb(0 0 0 / 5%);transition:all .25s linear;z-index:250010}.folders-undo-notification.active{right:25px}.folders-undo-header{font-weight:500;font-size:14px;padding:0 0 3px 0}.folders-undo-body{font-size:13px;padding:0 0 5px 0}.folders-undo-footer{text-align:right;padding:5px 0 0 0}.folders-undo-footer .undo-button{background:#1da1f4;border:none;color:#fff;padding:3px 10px;font-size:12px;border-radius:2px;cursor:pointer}.folders-undo-body{position:relative}.close-undo-box{position:absolute;right:-10px;top:0;width:16px;height:16px;transition:all .25s linear}.close-undo-box:hover{transform:rotate(180deg)}.close-undo-box span{display:block;position:relative;width:16px;height:16px;transition:all .2s linear}.close-undo-box span:after,.close-undo-box span:before{content:"";position:absolute;width:12px;height:2px;background-color:#333;display:block;border-radius:2px;transform:rotate(45deg);top:7px;left:2px}.close-undo-box span:after{transform:rotate(-45deg)}
895 .folders-undo-notification.no .folders-undo-header { color: #dd0000; }
896 .folders-undo-notification.yes .folders-undo-header { color: #014737; }
897 .update-name-with-title .spinner {display: none; visibility: visible; margin-right: 0;}
898 .update-name-with-title.in-progress .spinner {display: inline-block;}
899 </style>';
900 }
901
902 public function change_file_name_with_title($post_id = 0) {
903 if(empty($post_id)) {
904 return;
905 }
906 $post = get_post($post_id);
907 if(empty($post)) {
908 return;
909 }
910 if($post->post_type != "attachment") {
911 return;
912 }
913 $this->attachment_id = $post->ID;
914
915 $attachment_id = $post->ID;
916 $attachment = get_post($attachment_id);
917 $attachment_meta = wp_get_attachment_metadata($attachment_id);
918 $this->old_image_meta = $attachment_meta;
919 $get_attached_file = get_attached_file($attachment_id);
920 $file_name = basename($get_attached_file);
921
922 $file_ext = explode(".", $file_name);
923 $file_ext = array_pop($file_ext);
924 $post_slug = sanitize_file_name(sanitize_text_field($_POST['post_title']));
925 $new_file_name = $post_slug.".".$file_ext;
926
927 $wp_upload_path = wp_get_upload_dir();
928
929 $base_path = $wp_upload_path['basedir'].DIRECTORY_SEPARATOR;
930 $baseurl = $wp_upload_path['baseurl']."/";
931
932 $post_upload = "";
933
934 $wp_attached_file = get_post_meta($attachment_id, "_wp_attached_file", true);
935 if($wp_attached_file !== false) {
936 $old_file_name = explode("/", $wp_attached_file);
937 array_pop($old_file_name);
938
939 if(count($old_file_name) > 0) {
940 $base_path .= implode(DIRECTORY_SEPARATOR, $old_file_name);
941 $baseurl .= implode("/", $old_file_name);
942
943 $post_upload = implode("/", $old_file_name);
944 }
945 }
946
947 $upload_dir = array();
948 $upload_dir['path'] = $base_path;
949 $upload_dir['old_path'] = $base_path;
950 $upload_dir['url'] = $baseurl;
951 $upload_dir['old_url'] = $baseurl;
952
953 $this->upload_dir = $upload_dir;
954
955 $attachment_url = $attachment->guid;
956 $url = wp_get_attachment_url($attachment_id);
957 if(!empty($url)) {
958 $attachment_url = $url;
959 }
960 $file_parts = pathinfo($attachment_url);
961 $this->old_file_path = $base_path . DIRECTORY_SEPARATOR . $file_parts['basename'];
962 if(isset($attachment_meta['file']) && !empty($attachment_meta['file'])) {
963 $this->old_file_url = $wp_upload_path['baseurl'] . "/" . $attachment_meta['file'];
964 } else {
965 $this->old_file_url = wp_get_attachment_url($post_id);
966 }
967
968 if($new_file_name != $file_name) {
969 global $wpdb;
970
971 $new_file_name = $this->checkForFileName($new_file_name, $upload_dir['path'].DIRECTORY_SEPARATOR);
972
973 $this->new_file_path = $upload_dir['path'].DIRECTORY_SEPARATOR.$new_file_name;
974 $this->new_file_url = $upload_dir['url']."/".$new_file_name;
975 if(file_exists($this->old_file_path)) {
976 rename($this->old_file_path, $this->new_file_path);
977
978 update_attached_file($post->ID, $this->new_file_path);
979
980 $update_array = array();
981 $update_array['ID'] = $post->ID;
982 $update_array['post_title'] = sanitize_text_field($_REQUEST['post_title']);
983 $update_array['post_name'] = sanitize_title($post_slug);
984 $update_array['guid'] = $this->new_file_path; //wp_get_attachment_url($this->post_id);
985 $update_array['post_mime_type'] = $post->post_mime_type;
986 $post_id = wp_update_post($update_array, true);
987
988 // update post doesn't update GUID on updates.
989 $this->removeThumbImages();
990
991 $metadata = wp_generate_attachment_metadata($post->ID, $this->new_file_path);
992 wp_update_attachment_metadata($post->ID, $metadata);
993
994 $this->new_image_meta = wp_get_attachment_metadata($attachment_id);
995
996 update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name , "/"));
997
998 $this->searchAndReplace();
999
1000 delete_post_meta($attachment_id, "folders_file_replaced");
1001 add_post_meta( $attachment_id, "folders_file_replaced", time(), true);
1002 }
1003 }
1004 }
1005
1006 /**
1007 * Replace file name with title
1008 *
1009 * @since 2.6.3
1010 * @access public
1011 *
1012 */
1013 public function change_file_name_on_update($post_id = 0) {
1014 global $post;
1015 if(!isset($_REQUEST['premio_change_nonce']) || !isset($_REQUEST['premio_change_file_name'])) {
1016 return;
1017 }
1018 if(!wp_verify_nonce($_REQUEST['premio_change_nonce'], 'premio_change_file_name_'.$post->ID)) {
1019 return;
1020 }
1021 if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
1022 return;
1023 }
1024 $premio_change_file_name = sanitize_text_field($_REQUEST['premio_change_file_name']);
1025
1026 if($premio_change_file_name == "yes") {
1027 if($post->post_type == "attachment") {
1028
1029 unset($_REQUEST['premio_change_nonce']);
1030 unset($_REQUEST['premio_change_file_name']);
1031
1032 $this->change_file_name_with_title($post->ID);
1033 }
1034 }
1035 }
1036
1037 /**
1038 * Add Js and CSS files for replace file screen
1039 *
1040 * @since 2.6.3
1041 * @access public
1042 *
1043 */
1044 public function folders_admin_css_and_js($page) {
1045 if($page == "media_page_folders-replace-media" || $page == "admin_page_folders-replace-media") {
1046 wp_enqueue_style('folders-replace-media', plugin_dir_url(dirname(__FILE__)) . 'assets/css/replace-media.css', array(), WCP_FOLDER_VERSION);
1047
1048 wp_enqueue_script('folders-simpledropit', plugin_dir_url(dirname(__FILE__)) . 'assets/js/simpledropit.min.js', array(), WCP_FOLDER_VERSION);
1049 wp_enqueue_script('folders-replace-media', plugin_dir_url(dirname(__FILE__)) . 'assets/js/replace-media.js', array(), WCP_FOLDER_VERSION);
1050 $maxUploadSize = ini_get("upload_max_filesize");
1051 $maxUploadSize = str_replace(["K", "M", "G", "T", "P"],[" KB", " MB", " GB", " TB", " PB"], $maxUploadSize);
1052 $maxSize = sprintf(esc_html__("Maximum file size %s", "folders"), $maxUploadSize);
1053 wp_localize_script('folders-simpledropit','replace_settings', [
1054 'max_size' => $maxSize,
1055 'file_name' => esc_html__("File name", 'folders'),
1056 'file_size' => esc_html__("Size", 'folders'),
1057 'file_type' => esc_html__("Type", 'folders'),
1058 'dimension' => esc_html__("Dimension", 'folders'),
1059 'drag_file' => esc_html__("Drag and drop files here", 'folders')
1060 ]);
1061 // wp_enqueue_script('jquery-ui-datepicker');
1062 }
1063 }
1064
1065 /**
1066 * Add file replace menu in admin
1067 *
1068 * @since 2.6.3
1069 * @access public
1070 * @return $string
1071 *
1072 */
1073 public function admin_menu() {
1074 add_submenu_page("",
1075 esc_html__("Replace media", "folders"),
1076 esc_html__("Replace media", "folders"),
1077 'upload_files',
1078 'folders-replace-media',
1079 array($this, 'folders_replace_media')
1080 );
1081 }
1082
1083 /**
1084 * Add file replacement screen
1085 *
1086 * @since 2.6.3
1087 * @access public
1088 * @return $string
1089 *
1090 */
1091 public function folders_replace_media() {
1092 global $plugin_page;
1093 $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
1094 $attachment_id = isset($_GET['attachment_id']) ? sanitize_text_field($_GET['attachment_id']) : '';
1095 $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : '';
1096 if (!wp_verify_nonce($nonce, "folders-replace-media-".$attachment_id)) {
1097 echo 'Invalid Nonce';
1098 exit;
1099 }
1100 $attachment = get_post($attachment_id);
1101 if(empty($attachment) || !isset($attachment->guid)) {
1102 echo 'Invalid URL';
1103 exit;
1104 }
1105 $guid = $attachment->guid;
1106 $guid = explode(".", $guid);
1107 if($guid == $attachment->guid) {
1108 echo 'Invalid URL';
1109 exit;
1110 }
1111 $form_action = $this->getMediaReplaceURL($attachment_id);
1112 include_once dirname(dirname(__FILE__)) . WCP_DS . "/templates" . WCP_DS . "admin" . WCP_DS . "media-replace.php";
1113 }
1114
1115 /**
1116 * Add action for file replacement
1117 *
1118 * @since 2.6.3
1119 * @access public
1120 * @return $actions
1121 *
1122 */
1123 public function add_media_action($actions, $post) {
1124 if (!$this->isEnabled) {
1125 return array_merge($actions);
1126 }
1127
1128 if(current_user_can("upload_files")) {
1129 if (wp_attachment_is('image', $post->ID)) {
1130 $link = $this->getMediaReplaceURL($post->ID);
1131 $newaction['replace_media'] = '<a style="color: ' . esc_attr($this->buttonColor) . '" href="' . esc_url($link) . '" rel="permalink">' . esc_html__("Replace media", "folders") . '</a>';
1132 return array_merge($actions, $newaction);
1133 } else {
1134
1135 $newaction['replace_media'] = '<a style="color: ' . esc_attr($this->buttonColor) . '" target="_blank" href="' . esc_url($this->upgradeLink) . '" rel="permalink">' . esc_html__("Replace Media 🔑", "folders") . '</a>';
1136 return array_merge($actions, $newaction);
1137 }
1138 }
1139
1140 return $actions;
1141 }
1142
1143 /**
1144 * Get URL for file Replacement
1145 *
1146 * @since 2.6.3
1147 * @access public
1148 * @return $url
1149 *
1150 */
1151 public function getMediaReplaceURL($attach_id) {
1152 $url = admin_url( "upload.php");
1153 $url = add_query_arg(array(
1154 'page' => 'folders-replace-media',
1155 'action' => 'folders_replace_media',
1156 'attachment_id' => $attach_id,
1157 'nonce' => wp_create_nonce("folders-replace-media-".$attach_id)
1158 ), $url);
1159
1160 return $url;
1161 }
1162
1163 /**
1164 * Update Metabox to Replace file name with title
1165 *
1166 * @since 2.6.3
1167 * @access public
1168 * @return $size
1169 *
1170 */
1171 public function replace_meta_box($post) {
1172 if(current_user_can("upload_files")) {
1173 if (wp_attachment_is('image', $post->ID)) {
1174 $link = $this->getMediaReplaceURL($post->ID); ?>
1175 <p><a style='background: <?php echo esc_attr($this->buttonColor) ?>; border-color: <?php echo esc_attr($this->buttonColor) ?>; color:#ffffff' href='<?php echo esc_url($link) ?>' class='button-secondary'><?php esc_html_e("Upload a new file", "folders") ?></a></p><p><?php esc_html_e("Click on the button to replace the file with another file", "folders") ?></p>
1176 <?php } else { ?>
1177 <p><a style='color: <?php echo esc_attr($this->buttonColor) ?>; font-weight: 500' target='_blank' href='<?php echo esc_url($this->upgradeLink) ?>' ><?php esc_html_e("Upgrade to Pro", "folders") ?></a><?php esc_html_e("to replace any kind of files while uploading including pdf/svg/docx/etc & more.", "folders") ?></p>
1178 <?php }
1179 }
1180 }
1181
1182 /**
1183 * Add Metabox to replace file name with title
1184 *
1185 * @since 2.6.3
1186 * @access public
1187 *
1188 */
1189 public function change_file_name_box($post) {
1190 if(current_user_can("upload_files")) { ?>
1191 <p class="upgrade-bottom">
1192 <label for="change_file_name"><input disabled type="checkbox" id="change_file_name" name="premio_change_file_name" value="yes"> <?php esc_html_e("Change file name according to title", "folders") ?></label>
1193 </p>
1194 <div class="upgrade-box">
1195 <a href="<?php echo esc_url($this->upgradeLink) ?>" target="_blank"><?php esc_html_e("Upgrade to Pro", "folders"); ?></a>
1196 </div>
1197 <?php
1198 }
1199 }
1200
1201 /**
1202 * Add metabox in media edit page
1203 *
1204 * @since 2.6.3
1205 * @access public
1206 * @return $size
1207 *
1208 */
1209 public function attachment_editor($form_fields, $post)
1210 {
1211 $screen = null;
1212 if (function_exists('get_current_screen'))
1213 {
1214 $screen = get_current_screen();
1215
1216 if(! is_null($screen) && $screen->id == 'attachment') // hide on edit attachment screen.
1217 return $form_fields;
1218 }
1219
1220 if(current_user_can("upload_files")) {
1221 if (wp_attachment_is('image', $post->ID)) {
1222 $link = $this->getMediaReplaceURL($post->ID);
1223 $form_fields["folders"] = [
1224 "label" => esc_html__("Replace media", "folders"),
1225 "input" => "html",
1226 "html" => "<a style='background: " . esc_attr($this->buttonColor) . "; border-color: " . esc_attr($this->buttonColor) . "; color:#ffffff' href='" . esc_url($link) . "' class='button-secondary'>" . esc_html__("Upload a new file", "folders") . "</a>",
1227 "helps" => esc_html__("Click on the button to replace the file with another file", "folders"),
1228 ];
1229 } else {
1230 $form_fields["folders"] = [
1231 "label" => esc_html__("Replace media", "folders"),
1232 "input" => "html",
1233 "html" => "<div style='border: solid 1px #c0c0c0; padding: 10px; border-radius: 2px; background: #ececec;'><a style='color: " . esc_attr($this->buttonColor) . "; font-weight: 500' target='_blank' href='" . esc_url($this->upgradeLink) . "' >" . esc_html__("Upgrade to Pro", "folders") . "</a> " . esc_html__("to replace media files other than images", "folders") . "</div>",
1234 "helps" => esc_html__("Click on the button to replace the file with another file", "folders"),
1235 ];
1236 }
1237 }
1238
1239 return $form_fields;
1240 }
1241
1242 /**
1243 * Replace filenanme with title
1244 *
1245 * @since 2.6.3
1246 * @access public
1247 * @return $size
1248 *
1249 */
1250 public function attachment_replace_name_with_title($form_fields, $post)
1251 {
1252 $screen = null;
1253 if (function_exists('get_current_screen'))
1254 {
1255 $screen = get_current_screen();
1256
1257 if(! is_null($screen) && $screen->id == 'attachment') // hide on edit attachment screen.
1258 return $form_fields;
1259 }
1260
1261 if(current_user_can("upload_files")) {
1262 $form_fields["replace_file_name"] = array(
1263 "label" => esc_html__("Replace media", "folders"),
1264 "input" => "html",
1265 "html" => "<label for='attachment_title_" . esc_attr($post->ID) . "' data-post='" . esc_attr($post->ID) . "' data-nonce='" . wp_create_nonce('change_attachment_title_' . $post->ID) . "'><input id='attachment_title_" . esc_attr($post->ID) . "' type='checkbox' class='folder-replace-checkbox' value='" . esc_attr($post->ID) . "'>" . esc_html__("Update file name with title") . "</label><a href='" . $this->upgradeLink . "' target='_blank' style='background: " . esc_attr($this->buttonColor) . "; border-color: " . esc_attr($this->buttonColor) . "; color:#ffffff' type='button' class='button update-name-with-title' >" . esc_html__("Upgrade to Pro", "folders") . "</a>",
1266 "helps" => ""
1267 );
1268 }
1269
1270 return $form_fields;
1271 }
1272
1273 /**
1274 * Get file size
1275 *
1276 * @since 2.6.3
1277 * @access public
1278 * @return $size
1279 *
1280 */
1281 public function getFileSize($attachment_id) {
1282 $size = filesize( get_attached_file( $attachment_id ));
1283 if($size > 1000000) {
1284 $size = ($size/1000000);
1285 return number_format((float)$size, 2, ".", ",")." MB";
1286 } else if($size > 1000) {
1287 $size = ($size/1000);
1288 return number_format((float)$size, 2, ".", ",")." KB";
1289 }
1290 return $size." B";
1291 }
1292
1293 /**
1294 * Check for valid date
1295 *
1296 * @since 2.6.3
1297 * @access public
1298 *
1299 */
1300
1301 function validate_date($date, $format = 'Y-m-d') {
1302 $d = DateTime::createFromFormat($format, $date);
1303 // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
1304 return $d && $d->format($format) === $date;
1305 }
1306
1307 /**
1308 * Upload file and Replace it
1309 *
1310 * @since 2.6.3
1311 * @access public
1312 *
1313 */
1314 public function handle_folders_file_upload() {
1315 global $wpdb;
1316 if(isset($_FILES['new_media_file'])) {
1317 if($_FILES['new_media_file']['error'] == 0) {
1318 $attachment_id = isset($_GET['attachment_id']) ? sanitize_text_field($_GET['attachment_id']) : '';
1319 $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : '';
1320 if (!wp_verify_nonce($nonce, "folders-replace-media-" . $attachment_id)) {
1321 return;
1322 }
1323 $attachment = get_post($attachment_id);
1324 if (empty($attachment) || !isset($attachment->guid)) {
1325 return;
1326 }
1327 $attachment_url = $attachment->guid;
1328 $url = wp_get_attachment_url($attachment_id);
1329 if(!empty($url)) {
1330 $attachment_url = $url;
1331 }
1332 $guid = explode(".", $attachment_url);
1333 $guid = array_pop($guid);
1334 if ($guid == $attachment->guid) {
1335 return;
1336 }
1337
1338 $replacement_option = isset($_REQUEST['replacement_option'])?sanitize_text_field($_REQUEST['replacement_option']):"replace_only_file";
1339
1340 $this->attachment_id = $attachment_id;
1341
1342 $file = $_FILES['new_media_file'];
1343 $file_name = $file['name'];
1344 $file_ext = explode(".", $file_name);
1345 $file_ext = array_pop($file_ext);
1346 $ext = strtolower($file_ext);
1347
1348 $wpmime = wp_get_mime_types();
1349
1350 if(!isset($wpmime[$ext]) && !in_array($file['type'], $wpmime)) {
1351 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1352 }
1353
1354 if(!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) {
1355 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1356 }
1357
1358 if (wp_attachment_is('image', $attachment_id)) {
1359 $this->is_old_image = 1;
1360 }
1361 $this->old_file_url = $attachment_url;
1362 $this->old_image_meta = wp_get_attachment_metadata($attachment_id);
1363
1364 $new_file = $file['tmp_name'];
1365
1366 $file_parts = pathinfo($attachment_url);
1367
1368 $db_file_name = $file_parts['basename'];
1369 $db_file_array = explode(".", $db_file_name);
1370 array_pop($db_file_array);
1371 $db_file_name = implode(".", $db_file_array).".";
1372 $db_file_name .= $file_ext;
1373
1374 $wp_upload_path = wp_get_upload_dir();
1375
1376 $base_path = $old_path = $wp_upload_path['basedir'].DIRECTORY_SEPARATOR;
1377 $baseurl = $old_url = $wp_upload_path['baseurl']."/";
1378
1379 $post_upload = "";
1380
1381 $wp_attached_file = get_post_meta($attachment_id, "_wp_attached_file", true);
1382 if($wp_attached_file !== false) {
1383 $old_file_name = explode("/", $wp_attached_file);
1384 array_pop($old_file_name);
1385
1386 if(count($old_file_name) > 0) {
1387 $old_path .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1388 $old_url .= implode("/", $old_file_name);
1389 }
1390
1391 if($replacement_option == "replace_file_with_name" && isset($_REQUEST['new_folder_option']) && $_REQUEST['new_folder_option'] && isset($_REQUEST['new_folder_path']) && !empty($_REQUEST['new_folder_path'])) {
1392 $baseurl .= sanitize_text_field($_REQUEST['new_folder_path']);
1393 $base_path .= str_replace("/", DIRECTORY_SEPARATOR, $_REQUEST['new_folder_path']);
1394
1395 $post_upload = sanitize_text_field($_REQUEST['new_folder_path']);
1396 } else if(count($old_file_name) > 0) {
1397 $baseurl .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1398 $base_path .= implode("/", $old_file_name);
1399
1400 $post_upload = implode("/", $old_file_name);
1401 }
1402 }
1403
1404 $upload_dir = array();
1405 $upload_dir['path'] = $base_path;
1406 $upload_dir['old_path'] = $old_path;
1407 $upload_dir['url'] = $baseurl;
1408 $upload_dir['old_url'] = $old_url;
1409
1410 $this->upload_dir = $upload_dir;
1411
1412 $this->old_file_path = $old_path . "/" . $file_parts['basename'];
1413
1414 if (!is_dir($base_path)) {
1415 mkdir($base_path, 755, true);
1416 }
1417
1418 if (is_dir($base_path)) {
1419
1420 $file_array = explode(".", $file['name']);
1421 $file_ext = array_pop($file_array);
1422 $new_file_name = sanitize_title(implode(".", $file_array)).".".$file_ext;
1423 if($replacement_option == "replace_only_file") {
1424 $new_file_name = $db_file_name;
1425 }
1426
1427 if(strtolower($new_file_name) != strtolower($file_parts['basename'])) {
1428 $new_file_name = $this->checkForFileName($new_file_name, $base_path . DIRECTORY_SEPARATOR);
1429 }
1430
1431 $this->new_file_path = $base_path . DIRECTORY_SEPARATOR . $new_file_name;
1432
1433 $status = move_uploaded_file($new_file, $this->new_file_path);
1434
1435 $this->new_file_url = trim($baseurl, "/")."/".$new_file_name;
1436
1437 if ($status) {
1438 $old_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->old_file_path);
1439 $new_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->new_file_path);
1440 if($old_file_path != $new_file_path) {
1441 if(file_exists($this->old_file_path)) {
1442 @unlink($this->old_file_path);
1443 }
1444 }
1445
1446 update_attached_file($attachment->ID, $this->new_file_url);
1447
1448 $update_array = array();
1449 $update_array['ID'] = $attachment->ID;
1450 $update_array['guid'] = $this->new_file_url; //wp_get_attachment_url($this->post_id);
1451 $update_array['post_mime_type'] = $file['type'];
1452
1453 $current_date = date("Y-m-d H:i:s");
1454 $current_date_gmt = date_i18n("Y-m-d H:i:s", strtotime($current_date));
1455 if(isset($_REQUEST['date_options']) && !empty($_REQUEST['date_options'])) {
1456 if($_REQUEST['date_options'] == "replace_date") {
1457 $update_array['post_date'] = $current_date;
1458 $update_array['post_date_gmt'] = $current_date_gmt;
1459 } else if($_REQUEST['date_options'] == "custom_date") {
1460 $custom_date = sanitize_text_field($_POST['custom_date']);
1461 $custom_date = date("Y-m-d H:i:s", strtotime($custom_date));
1462 if($custom_date !== false && $this->validate_date($custom_date, "Y-m-d H:i:s")) {
1463 $datetime = date("Y-m-d H:i:s", strtotime($custom_date));
1464 $datetime_gmt = date_i18n("Y-m-d H:i:s", strtotime($datetime));
1465 $update_array['post_date'] = $datetime;
1466 $update_array['post_date_gmt'] = $datetime_gmt;
1467 }
1468 }
1469 }
1470 $update_array['post_modified'] = $current_date;
1471 $update_array['post_modified_gmt'] = $current_date_gmt;
1472 $post_id = wp_update_post($update_array, true);
1473
1474 update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name , "/"));
1475
1476 // update post doesn't update GUID on updates.
1477 $wpdb->update($wpdb->posts, array('guid' => $this->new_file_url), array('ID' => $attachment->ID));
1478
1479 $this->removeThumbImages();
1480
1481 $metadata = wp_generate_attachment_metadata($attachment->ID, $this->new_file_path);
1482 wp_update_attachment_metadata($attachment->ID, $metadata);
1483
1484 $this->new_image_meta = wp_get_attachment_metadata($attachment_id);
1485
1486 // update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name ), "/");
1487
1488 $this->searchAndReplace();
1489
1490 delete_post_meta($attachment_id, "folders_file_replaced");
1491 add_post_meta( $attachment_id, "folders_file_replaced", time(), true);
1492
1493 wp_redirect(admin_url("post.php?post=" . $attachment_id . "&action=edit&premio_message=success&image_update=1"));
1494 exit;
1495 } else {
1496 wp_die("Error during uploading file");
1497 }
1498
1499 } else {
1500 wp_die("Permission issue, Unable to create directory");
1501 }
1502 }
1503 }
1504 }
1505
1506 /**
1507 * Check for filename
1508 *
1509 * @since 2.6.3
1510 * @access public
1511 *
1512 */
1513 public function checkForFileName($fileName, $filePath, $postFix = 0) {
1514 $new_file_name = $fileName;
1515 if(!empty($postFix)) {
1516 $file_array = explode(".", $fileName);
1517 $file_ext = array_pop($file_array);
1518 $new_file_name = implode(".", $file_array)."-".$postFix.".".$file_ext;
1519 }
1520 if(!file_exists($filePath.$new_file_name)) {
1521 return $new_file_name;
1522 }
1523 return $this->checkForFileName($fileName, $filePath, ($postFix+1));
1524 }
1525
1526 public $replace_items = array();
1527
1528 /**
1529 * Check and Remove Thumb image in wp-content
1530 *
1531 * @since 2.6.3
1532 * @access public
1533 *
1534 */
1535 public function removeThumbImages() {
1536 if(!empty($this->old_image_meta) && isset($this->old_image_meta['sizes']) && !empty($this->upload_dir) && isset($this->upload_dir['path'])) {
1537 $path = $this->upload_dir['old_path'].DIRECTORY_SEPARATOR;
1538 foreach ($this->old_image_meta['sizes'] as $image) {
1539 if(file_exists($path.$image['file']) && (!isset($image['mime-type']) || $image['mime-type'] != 'image/svg+xml')) {
1540 @unlink($path . $image['file']);
1541 }
1542 }
1543 }
1544 }
1545
1546 /**
1547 * Search and Replace files in Database
1548 *
1549 * @since 2.6.3
1550 * @access public
1551 * @return $string
1552 *
1553 */
1554 public function searchAndReplace() {
1555 if (wp_attachment_is('image', $this->attachment_id)) {
1556 $this->is_new_image = 1;
1557 }
1558 if($this->old_file_url != $this->new_file_url) {
1559 $replace = array(
1560 'search' => $this->old_file_url,
1561 'replace' => $this->new_file_url,
1562 );
1563 $this->replace_items[] = $replace;
1564 }
1565
1566 $base_url = $this->upload_dir['url'];
1567 $base_url = trim($base_url, "/")."/";
1568 $new_url = $this->new_file_url;
1569
1570 if(isset($this->old_image_meta['sizes']) && !empty($this->old_image_meta['sizes'])) {
1571 if(!isset($this->new_image_meta['sizes']) || empty($this->new_image_meta['sizes'])) {
1572 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1573 $replace = array(
1574 'search' => $base_url.$image['file'],
1575 'replace' => $new_url,
1576 );
1577 $this->replace_items[] = $replace;
1578 }
1579 } else if(isset($this->new_image_meta['sizes']) && !empty($this->new_image_meta['sizes'])) {
1580 $new_size = $this->new_image_meta['sizes'];
1581 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1582 $new_replace_url = $new_url;
1583 if(isset($new_size[$key])) {
1584 $new_replace_url = $base_url.$new_size[$key]['file'];
1585 }
1586 $replace = array(
1587 'search' => $base_url.$image['file'],
1588 'replace' => $new_replace_url,
1589 );
1590 $this->replace_items[] = $replace;
1591 }
1592 }
1593 }
1594
1595 if(!empty($this->replace_items)) {
1596 $replace_items = array();
1597 foreach($this->replace_items as $args) {
1598 if($args['search'] != $args['replace']) {
1599 $replace_items[] = $args;
1600 }
1601 }
1602 $this->replace_items = $replace_items;
1603 $this->replaceURL();
1604 }
1605 }
1606
1607 /**
1608 * Replace URL in Database tables
1609 *
1610 * @since 2.6.3
1611 * @access public
1612 * @return $string
1613 *
1614 */
1615 function replaceURL() {
1616 /* check in post content */
1617 $this->checkInPostContent();
1618
1619 /* check in options */
1620 $this->checkInOptions();
1621
1622 /* check in meta */
1623 $this->checkInMetaData();
1624
1625 if(function_exists('folders_pro_clear_all_caches')) {
1626 folders_pro_clear_all_caches();
1627 }
1628 }
1629
1630 /**
1631 * Checking image URLs in Post Content
1632 *
1633 * @since 2.6.3
1634 * @access public
1635 * @return $string
1636 *
1637 */
1638 function checkInPostContent() {
1639 global $wpdb;
1640 $post_table = $wpdb->prefix."posts";
1641 if(!empty($this->replace_items)) {
1642 $query = "SELECT ID, post_content FROM {$post_table} WHERE post_content LIKE %s";
1643 $update_query = "UPDATE {$post_table} SET post_content = %s WHERE ID = %d";
1644 foreach ($this->replace_items as $args) {
1645 if($args['search'] != $args['replace']) {
1646 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1647 $results = $wpdb->get_results($sql_query, ARRAY_A );
1648 if(!empty($results)) {
1649 foreach ($results AS $row) {
1650 $content = $this->findAndReplaceContent($row['post_content'], $args['search'], $args['replace']);
1651 $update_post_query = $wpdb->prepare($update_query, $content, $row['ID']);
1652 $result = $wpdb->query($update_post_query);
1653 }
1654 }
1655 }
1656 }
1657 }
1658 }
1659
1660 /**
1661 * Checking image URLs in MetaData
1662 *
1663 * @since 2.6.3
1664 * @access public
1665 * @return $string
1666 *
1667 */
1668 function checkInOptions() {
1669 global $wpdb;
1670 $post_table = $wpdb->prefix."options";
1671 if(!empty($this->replace_items)) {
1672 $query = "SELECT option_id, option_value FROM {$post_table} WHERE option_value LIKE %s";
1673 $update_query = "UPDATE {$post_table} SET option_value = %s WHERE option_id = %d";
1674 foreach ($this->replace_items as $args) {
1675 if($args['search'] != $args['replace']) {
1676 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1677 $results = $wpdb->get_results($sql_query, ARRAY_A );
1678 if(!empty($results)) {
1679 foreach ($results AS $row) {
1680 $content = $this->findAndReplaceContent($row['option_value'], $args['search'], $args['replace']);
1681 $update_post_query = $wpdb->prepare($update_query, $content, $row['option_id']);
1682 $result = $wpdb->query($update_post_query);
1683 }
1684 }
1685 }
1686 }
1687 }
1688 }
1689
1690 /**
1691 * Checking image URLs in MetaData
1692 *
1693 * @since 2.6.3
1694 * @access public
1695 * @return $string
1696 *
1697 */
1698 function checkInMetaData() {
1699 $tables = array(
1700 array(
1701 'table_name' => 'usermeta',
1702 'primary_key' => 'umeta_id',
1703 'search_key' => 'meta_value'
1704 ),
1705 array(
1706 'table_name' => 'termmeta',
1707 'primary_key' => 'meta_id',
1708 'search_key' => 'meta_value'
1709 ),
1710 array(
1711 'table_name' => 'postmeta',
1712 'primary_key' => 'meta_id',
1713 'search_key' => 'meta_value'
1714 ),
1715 array(
1716 'table_name' => 'commentmeta',
1717 'primary_key' => 'meta_id',
1718 'search_key' => 'meta_value'
1719 )
1720 );
1721 global $wpdb;
1722 foreach ($tables as $table) {
1723 $post_table = $wpdb->prefix . $table['table_name'];
1724 if (!empty($this->replace_items)) {
1725 $query = "SELECT {$table['primary_key']}, {$table['search_key']} FROM {$post_table} WHERE {$table['search_key']} LIKE %s";
1726 $update_query = "UPDATE {$post_table} SET {$table['search_key']} = %s WHERE {$table['primary_key']} = %d";
1727 foreach ($this->replace_items as $args) {
1728 if ($args['search'] != $args['replace']) {
1729 $sql_query = $wpdb->prepare($query, "%" . $args['search'] . "%");
1730 $results = $wpdb->get_results($sql_query, ARRAY_A);
1731 if (!empty($results)) {
1732 foreach ($results as $row) {
1733 $content = $this->findAndReplaceContent($row[$table['search_key']], $args['search'], $args['replace']);
1734 $update_post_query = $wpdb->prepare($update_query, $content, $row[$table['primary_key']]);
1735 $result = $wpdb->query($update_post_query);
1736 }
1737 }
1738 }
1739 }
1740 }
1741 }
1742 }
1743
1744 /**
1745 * Checking for Array Key
1746 *
1747 * @since 2.6.3
1748 * @access public
1749 * @return $json
1750 * Forked from Enable Media Replace
1751 *
1752 */
1753 function findAndReplaceContent($content, $search, $replace, $depth = false) {
1754 $content = maybe_unserialize($content);
1755
1756 // Checking for JSON Data
1757 $isJson = $this->isJSON($content);
1758 if ($isJson) {
1759 $content = json_decode($content);
1760 }
1761
1762 // Replace content if content is String
1763 if (is_string($content)) {
1764 $content = str_replace($search, $replace, $content);
1765 }
1766 else if(is_wp_error($content)) { // Return if error in data
1767
1768 }
1769 else if(is_array($content)) { // Replace content if content is Array
1770 foreach($content as $index => $value) {
1771 $content[$index] = $this->findAndReplaceContent($value, $search, $replace, true);
1772 if (is_string($index)) {
1773 $index_replaced = $this->findAndReplaceContent($index, $search, $replace, true);
1774 if ($index_replaced !== $index)
1775 $content = $this->changeArrayKey($content, array($index => $index_replaced));
1776 }
1777 }
1778 }
1779 else if(is_object($content)) { // Replace content if content is Object
1780 foreach($content as $key => $value) {
1781 $content->{$key} = $this->findAndReplaceContent($value, $search, $replace, true);
1782 }
1783 }
1784
1785 if ($isJson && $depth === false) {
1786 $content = json_encode($content, JSON_UNESCAPED_SLASHES);
1787 }
1788 else if($depth === false && (is_array($content) || is_object($content))) {
1789 $content = maybe_serialize($content);
1790 }
1791
1792 return $content;
1793 }
1794
1795 /**
1796 * Checking for Array Key
1797 *
1798 * @since 2.6.3
1799 * @access public
1800 * @return $json
1801 *
1802 */
1803 function changeArrayKey($array, $set) {
1804 if (is_array($array) && is_array($set)) {
1805 $newArray = array();
1806 foreach ($array as $k => $v) {
1807 $key = array_key_exists( $k, $set) ? $set[$k] : $k;
1808 $newArray[$key] = is_array($v) ? $this->changeArrayKey($v, $set) : $v;
1809 }
1810 return $newArray;
1811 }
1812 return $array;
1813 }
1814
1815 /**
1816 * Check if it is JSON or not
1817 *
1818 * @since 2.6.3
1819 * @access public
1820 * Forked from Enable Media Replace
1821 * @return $json
1822 *
1823 */
1824 function isJSON($content)
1825 {
1826 if (is_array($content) || is_object($content))
1827 return false;
1828
1829 $json = json_decode($content);
1830 return $json && $json != $content;
1831 }
1832 }
1833 $folders_replace_media = new folders_replace_media();
1834