PluginProbe ʕ •ᴥ•ʔ
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager / 2.9
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager v2.9
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 3 years ago plugins.class.php 3 years ago tree.class.php 3 years ago
media.replace.php
1824 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) {
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) {
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;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;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
1051 $maxUploadSize = ini_get("upload_max_filesize");
1052 $maxUploadSize = str_replace(["K", "M", "G", "T", "P"],[" KB", " MB", " GB", " TB", " PB"], $maxUploadSize);
1053 $maxSize = sprintf(esc_html__("Maximum file size %s", "folders"), $maxUploadSize);
1054 wp_localize_script('folders-simpledropit','replace_settings', [
1055 'max_size' => $maxSize,
1056 'file_name' => esc_html__("File name", 'folders'),
1057 'file_size' => esc_html__("Size", 'folders'),
1058 'file_type' => esc_html__("Type", 'folders'),
1059 'dimension' => esc_html__("Dimension", 'folders'),
1060 'drag_file' => esc_html__("Drag and drop files here", 'folders'),
1061 ]);
1062 // wp_enqueue_script('jquery-ui-datepicker');
1063 }
1064 }
1065
1066 /**
1067 * Add file replace menu in admin
1068 *
1069 * @since 2.6.3
1070 * @access public
1071 * @return $string
1072 *
1073 */
1074 public function admin_menu() {
1075 add_submenu_page("",
1076 esc_html__("Replace media", "folders"),
1077 esc_html__("Replace media", "folders"),
1078 'upload_files',
1079 'folders-replace-media',
1080 array($this, 'folders_replace_media')
1081 );
1082 }
1083
1084 /**
1085 * Add file replacement screen
1086 *
1087 * @since 2.6.3
1088 * @access public
1089 * @return $string
1090 *
1091 */
1092 public function folders_replace_media() {
1093 global $plugin_page;
1094 $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
1095 $attachment_id = isset($_GET['attachment_id']) ? sanitize_text_field($_GET['attachment_id']) : '';
1096 $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : '';
1097 if (!wp_verify_nonce($nonce, "folders-replace-media-".$attachment_id)) {
1098 echo 'Invalid Nonce';
1099 exit;
1100 }
1101 $attachment = get_post($attachment_id);
1102 if(empty($attachment) || !isset($attachment->guid)) {
1103 echo 'Invalid URL';
1104 exit;
1105 }
1106 $guid = $attachment->guid;
1107 $guid = explode(".", $guid);
1108 if($guid == $attachment->guid) {
1109 echo 'Invalid URL';
1110 exit;
1111 }
1112 $form_action = $this->getMediaReplaceURL($attachment_id);
1113 include_once dirname(dirname(__FILE__)) . WCP_DS . "/templates" . WCP_DS . "admin" . WCP_DS . "media-replace.php";
1114 }
1115
1116 /**
1117 * Add action for file replacement
1118 *
1119 * @since 2.6.3
1120 * @access public
1121 * @return $actions
1122 *
1123 */
1124 public function add_media_action($actions, $post) {
1125 if (!$this->isEnabled) {
1126 return array_merge($actions);
1127 }
1128
1129 if(current_user_can("upload_files")) {
1130 if (wp_attachment_is('image', $post->ID)) {
1131 $link = $this->getMediaReplaceURL($post->ID);
1132 $newaction['replace_media'] = '<a style="color: ' . esc_attr($this->buttonColor) . '" href="' . esc_url($link) . '" rel="permalink">' . esc_html__("Replace media", "folders") . '</a>';
1133 return array_merge($actions, $newaction);
1134 } else {
1135
1136 $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>';
1137 return array_merge($actions, $newaction);
1138 }
1139 }
1140
1141 return $actions;
1142 }
1143
1144 /**
1145 * Get URL for file Replacement
1146 *
1147 * @since 2.6.3
1148 * @access public
1149 * @return $url
1150 *
1151 */
1152 public function getMediaReplaceURL($attach_id) {
1153 $url = admin_url( "upload.php");
1154 $url = add_query_arg(array(
1155 'page' => 'folders-replace-media',
1156 'action' => 'folders_replace_media',
1157 'attachment_id' => $attach_id,
1158 'nonce' => wp_create_nonce("folders-replace-media-".$attach_id)
1159 ), $url);
1160
1161 return $url;
1162 }
1163
1164 /**
1165 * Update Metabox to Replace file name with title
1166 *
1167 * @since 2.6.3
1168 * @access public
1169 * @return $size
1170 *
1171 */
1172 public function replace_meta_box($post) {
1173 if(current_user_can("upload_files")) {
1174 if (wp_attachment_is('image', $post->ID)) {
1175 $link = $this->getMediaReplaceURL($post->ID); ?>
1176 <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>
1177 <?php } else { ?>
1178 <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>
1179 <?php }
1180 }
1181 }
1182
1183 /**
1184 * Add Metabox to replace file name with title
1185 *
1186 * @since 2.6.3
1187 * @access public
1188 *
1189 */
1190 public function change_file_name_box($post) {
1191 if(current_user_can("upload_files")) { ?>
1192 <p class="upgrade-bottom">
1193 <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>
1194 </p>
1195 <div class="upgrade-box">
1196 <a href="<?php echo esc_url($this->upgradeLink) ?>" target="_blank"><?php esc_html_e("Upgrade to Pro", "folders"); ?></a>
1197 </div>
1198 <?php
1199 }
1200 }
1201
1202 /**
1203 * Add metabox in media edit page
1204 *
1205 * @since 2.6.3
1206 * @access public
1207 * @return $size
1208 *
1209 */
1210 public function attachment_editor($form_fields, $post)
1211 {
1212 $screen = null;
1213 if (function_exists('get_current_screen'))
1214 {
1215 $screen = get_current_screen();
1216
1217 if(! is_null($screen) && $screen->id == 'attachment') // hide on edit attachment screen.
1218 return $form_fields;
1219 }
1220
1221 if(current_user_can("upload_files")) {
1222 if (wp_attachment_is('image', $post->ID)) {
1223 $link = $this->getMediaReplaceURL($post->ID);
1224 $form_fields["folders"] = [
1225 "label" => esc_html__("Replace media", "folders"),
1226 "input" => "html",
1227 "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>",
1228 "helps" => esc_html__("Click on the button to replace the file with another file", "folders"),
1229 ];
1230 } else {
1231 $form_fields["folders"] = [
1232 "label" => esc_html__("Replace media", "folders"),
1233 "input" => "html",
1234 "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>",
1235 "helps" => esc_html__("Click on the button to replace the file with another file", "folders"),
1236 ];
1237 }
1238 }
1239
1240 return $form_fields;
1241 }
1242
1243 /**
1244 * Replace filenanme with title
1245 *
1246 * @since 2.6.3
1247 * @access public
1248 * @return $size
1249 *
1250 */
1251 public function attachment_replace_name_with_title($form_fields, $post)
1252 {
1253 $screen = null;
1254 if (function_exists('get_current_screen'))
1255 {
1256 $screen = get_current_screen();
1257
1258 if(! is_null($screen) && $screen->id == 'attachment') // hide on edit attachment screen.
1259 return $form_fields;
1260 }
1261
1262 if(current_user_can("upload_files")) {
1263 $form_fields["replace_file_name"] = array(
1264 "label" => esc_html__("Replace media", "folders"),
1265 "input" => "html",
1266 "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>",
1267 "helps" => ""
1268 );
1269 }
1270
1271 return $form_fields;
1272 }
1273
1274 /**
1275 * Get file size
1276 *
1277 * @since 2.6.3
1278 * @access public
1279 * @return $size
1280 *
1281 */
1282 public function getFileSize($attachment_id) {
1283 $size = filesize( get_attached_file( $attachment_id ));
1284 if($size > 1000000) {
1285 $size = ($size/1000000);
1286 return number_format((float)$size, 2, ".", ",")." MB";
1287 } else if($size > 1000) {
1288 $size = ($size/1000);
1289 return number_format((float)$size, 2, ".", ",")." KB";
1290 }
1291 return $size." B";
1292 }
1293
1294 /**
1295 * Check for valid date
1296 *
1297 * @since 2.6.3
1298 * @access public
1299 *
1300 */
1301
1302 function validate_date($date, $format = 'Y-m-d') {
1303 $d = DateTime::createFromFormat($format, $date);
1304 // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
1305 return $d && $d->format($format) === $date;
1306 }
1307
1308 /**
1309 * Upload file and Replace it
1310 *
1311 * @since 2.6.3
1312 * @access public
1313 *
1314 */
1315 public function handle_folders_file_upload() {
1316 global $wpdb;
1317 if(isset($_FILES['new_media_file'])) {
1318 if($_FILES['new_media_file']['error'] == 0) {
1319 $attachment_id = isset($_GET['attachment_id']) ? sanitize_text_field($_GET['attachment_id']) : '';
1320 $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : '';
1321 if (!wp_verify_nonce($nonce, "folders-replace-media-" . $attachment_id)) {
1322 return;
1323 }
1324 $attachment = get_post($attachment_id);
1325 if (empty($attachment) || !isset($attachment->guid)) {
1326 return;
1327 }
1328 $attachment_url = $attachment->guid;
1329 $url = wp_get_attachment_url($attachment_id);
1330 if(!empty($url)) {
1331 $attachment_url = $url;
1332 }
1333 $guid = explode(".", $attachment_url);
1334 $guid = array_pop($guid);
1335 if ($guid == $attachment->guid) {
1336 return;
1337 }
1338
1339 $replacement_option = isset($_REQUEST['replacement_option'])?sanitize_text_field($_REQUEST['replacement_option']):"replace_only_file";
1340
1341 $this->attachment_id = $attachment_id;
1342
1343 $file = $_FILES['new_media_file'];
1344 $file_name = $file['name'];
1345 $file_ext = explode(".", $file_name);
1346 $file_ext = array_pop($file_ext);
1347
1348 if (wp_attachment_is('image', $attachment_id)) {
1349 $this->is_old_image = 1;
1350 }
1351 $this->old_file_url = $attachment_url;
1352 $this->old_image_meta = wp_get_attachment_metadata($attachment_id);
1353
1354 $new_file = $file['tmp_name'];
1355
1356 $file_parts = pathinfo($attachment_url);
1357
1358 $db_file_name = $file_parts['basename'];
1359 $db_file_array = explode(".", $db_file_name);
1360 array_pop($db_file_array);
1361 $db_file_name = implode(".", $db_file_array).".";
1362 $db_file_name .= $file_ext;
1363
1364 $wp_upload_path = wp_get_upload_dir();
1365
1366 $base_path = $old_path = $wp_upload_path['basedir'].DIRECTORY_SEPARATOR;
1367 $baseurl = $old_url = $wp_upload_path['baseurl']."/";
1368
1369 $post_upload = "";
1370
1371 $wp_attached_file = get_post_meta($attachment_id, "_wp_attached_file", true);
1372 if($wp_attached_file !== false) {
1373 $old_file_name = explode("/", $wp_attached_file);
1374 array_pop($old_file_name);
1375
1376 if(count($old_file_name) > 0) {
1377 $old_path .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1378 $old_url .= implode("/", $old_file_name);
1379 }
1380
1381 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'])) {
1382 $baseurl .= sanitize_text_field($_REQUEST['new_folder_path']);
1383 $base_path .= str_replace("/", DIRECTORY_SEPARATOR, $_REQUEST['new_folder_path']);
1384
1385 $post_upload = sanitize_text_field($_REQUEST['new_folder_path']);
1386 } else if(count($old_file_name) > 0) {
1387 $baseurl .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1388 $base_path .= implode("/", $old_file_name);
1389
1390 $post_upload = implode("/", $old_file_name);
1391 }
1392 }
1393
1394 $upload_dir = array();
1395 $upload_dir['path'] = $base_path;
1396 $upload_dir['old_path'] = $old_path;
1397 $upload_dir['url'] = $baseurl;
1398 $upload_dir['old_url'] = $old_url;
1399
1400 $this->upload_dir = $upload_dir;
1401
1402 $this->old_file_path = $old_path . "/" . $file_parts['basename'];
1403
1404 if (!is_dir($base_path)) {
1405 mkdir($base_path, 755, true);
1406 }
1407
1408 if (is_dir($base_path)) {
1409
1410 $file_array = explode(".", $file['name']);
1411 $file_ext = array_pop($file_array);
1412 $new_file_name = sanitize_title(implode(".", $file_array)).".".$file_ext;
1413 if($replacement_option == "replace_only_file") {
1414 $new_file_name = $db_file_name;
1415 }
1416
1417 if(strtolower($new_file_name) != strtolower($file_parts['basename'])) {
1418 $new_file_name = $this->checkForFileName($new_file_name, $base_path . DIRECTORY_SEPARATOR);
1419 }
1420
1421 $this->new_file_path = $base_path . DIRECTORY_SEPARATOR . $new_file_name;
1422
1423 $status = move_uploaded_file($new_file, $this->new_file_path);
1424
1425 $this->new_file_url = trim($baseurl, "/")."/".$new_file_name;
1426
1427 if ($status) {
1428 $old_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->old_file_path);
1429 $new_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->new_file_path);
1430 if($old_file_path != $new_file_path) {
1431 if(file_exists($this->old_file_path)) {
1432 @unlink($this->old_file_path);
1433 }
1434 }
1435
1436 update_attached_file($attachment->ID, $this->new_file_url);
1437
1438 $update_array = array();
1439 $update_array['ID'] = $attachment->ID;
1440 $update_array['guid'] = $this->new_file_url; //wp_get_attachment_url($this->post_id);
1441 $update_array['post_mime_type'] = $file['type'];
1442
1443 $current_date = date("Y-m-d H:i:s");
1444 $current_date_gmt = date_i18n("Y-m-d H:i:s", strtotime($current_date));
1445 if(isset($_REQUEST['date_options']) && !empty($_REQUEST['date_options'])) {
1446 if($_REQUEST['date_options'] == "replace_date") {
1447 $update_array['post_date'] = $current_date;
1448 $update_array['post_date_gmt'] = $current_date_gmt;
1449 } else if($_REQUEST['date_options'] == "custom_date") {
1450 $custom_date = sanitize_text_field($_POST['custom_date']);
1451 $custom_date = date("Y-m-d H:i:s", strtotime($custom_date));
1452 if($custom_date !== false && $this->validate_date($custom_date, "Y-m-d H:i:s")) {
1453 $datetime = date("Y-m-d H:i:s", strtotime($custom_date));
1454 $datetime_gmt = date_i18n("Y-m-d H:i:s", strtotime($datetime));
1455 $update_array['post_date'] = $datetime;
1456 $update_array['post_date_gmt'] = $datetime_gmt;
1457 }
1458 }
1459 }
1460 $update_array['post_modified'] = $current_date;
1461 $update_array['post_modified_gmt'] = $current_date_gmt;
1462 $post_id = wp_update_post($update_array, true);
1463
1464 update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name , "/"));
1465
1466 // update post doesn't update GUID on updates.
1467 $wpdb->update($wpdb->posts, array('guid' => $this->new_file_url), array('ID' => $attachment->ID));
1468
1469 $this->removeThumbImages();
1470
1471 $metadata = wp_generate_attachment_metadata($attachment->ID, $this->new_file_path);
1472 wp_update_attachment_metadata($attachment->ID, $metadata);
1473
1474 $this->new_image_meta = wp_get_attachment_metadata($attachment_id);
1475
1476 // update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name ), "/");
1477
1478 $this->searchAndReplace();
1479
1480 delete_post_meta($attachment_id, "folders_file_replaced");
1481 add_post_meta( $attachment_id, "folders_file_replaced", time(), true);
1482
1483 wp_redirect(admin_url("post.php?post=" . $attachment_id . "&action=edit&premio_message=success&image_update=1"));
1484 exit;
1485 } else {
1486 wp_die("Error during uploading file");
1487 }
1488
1489 } else {
1490 wp_die("Permission issue, Unable to create directory");
1491 }
1492 }
1493 }
1494 }
1495
1496 /**
1497 * Check for filename
1498 *
1499 * @since 2.6.3
1500 * @access public
1501 *
1502 */
1503 public function checkForFileName($fileName, $filePath, $postFix = 0) {
1504 $new_file_name = $fileName;
1505 if(!empty($postFix)) {
1506 $file_array = explode(".", $fileName);
1507 $file_ext = array_pop($file_array);
1508 $new_file_name = implode(".", $file_array)."-".$postFix.".".$file_ext;
1509 }
1510 if(!file_exists($filePath.$new_file_name)) {
1511 return $new_file_name;
1512 }
1513 return $this->checkForFileName($fileName, $filePath, ($postFix+1));
1514 }
1515
1516 public $replace_items = array();
1517
1518 /**
1519 * Check and Remove Thumb image in wp-content
1520 *
1521 * @since 2.6.3
1522 * @access public
1523 *
1524 */
1525 public function removeThumbImages() {
1526 if(!empty($this->old_image_meta) && isset($this->old_image_meta['sizes']) && !empty($this->upload_dir) && isset($this->upload_dir['path'])) {
1527 $path = $this->upload_dir['old_path'].DIRECTORY_SEPARATOR;
1528 foreach ($this->old_image_meta['sizes'] as $image) {
1529 if(file_exists($path.$image['file']) && (!isset($image['mime-type']) || $image['mime-type'] != 'image/svg+xml')) {
1530 @unlink($path . $image['file']);
1531 }
1532 }
1533 }
1534 }
1535
1536 /**
1537 * Search and Replace files in Database
1538 *
1539 * @since 2.6.3
1540 * @access public
1541 * @return $string
1542 *
1543 */
1544 public function searchAndReplace() {
1545 if (wp_attachment_is('image', $this->attachment_id)) {
1546 $this->is_new_image = 1;
1547 }
1548 if($this->old_file_url != $this->new_file_url) {
1549 $replace = array(
1550 'search' => $this->old_file_url,
1551 'replace' => $this->new_file_url,
1552 );
1553 $this->replace_items[] = $replace;
1554 }
1555
1556 $base_url = $this->upload_dir['url'];
1557 $base_url = trim($base_url, "/")."/";
1558 $new_url = $this->new_file_url;
1559
1560 if(isset($this->old_image_meta['sizes']) && !empty($this->old_image_meta['sizes'])) {
1561 if(!isset($this->new_image_meta['sizes']) || empty($this->new_image_meta['sizes'])) {
1562 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1563 $replace = array(
1564 'search' => $base_url.$image['file'],
1565 'replace' => $new_url,
1566 );
1567 $this->replace_items[] = $replace;
1568 }
1569 } else if(isset($this->new_image_meta['sizes']) && !empty($this->new_image_meta['sizes'])) {
1570 $new_size = $this->new_image_meta['sizes'];
1571 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1572 $new_replace_url = $new_url;
1573 if(isset($new_size[$key])) {
1574 $new_replace_url = $base_url.$new_size[$key]['file'];
1575 }
1576 $replace = array(
1577 'search' => $base_url.$image['file'],
1578 'replace' => $new_replace_url,
1579 );
1580 $this->replace_items[] = $replace;
1581 }
1582 }
1583 }
1584
1585 if(!empty($this->replace_items)) {
1586 $replace_items = array();
1587 foreach($this->replace_items as $args) {
1588 if($args['search'] != $args['replace']) {
1589 $replace_items[] = $args;
1590 }
1591 }
1592 $this->replace_items = $replace_items;
1593 $this->replaceURL();
1594 }
1595 }
1596
1597 /**
1598 * Replace URL in Database tables
1599 *
1600 * @since 2.6.3
1601 * @access public
1602 * @return $string
1603 *
1604 */
1605 function replaceURL() {
1606 /* check in post content */
1607 $this->checkInPostContent();
1608
1609 /* check in options */
1610 $this->checkInOptions();
1611
1612 /* check in meta */
1613 $this->checkInMetaData();
1614
1615 if(function_exists('folders_pro_clear_all_caches')) {
1616 folders_pro_clear_all_caches();
1617 }
1618 }
1619
1620 /**
1621 * Checking image URLs in Post Content
1622 *
1623 * @since 2.6.3
1624 * @access public
1625 * @return $string
1626 *
1627 */
1628 function checkInPostContent() {
1629 global $wpdb;
1630 $post_table = $wpdb->prefix."posts";
1631 if(!empty($this->replace_items)) {
1632 $query = "SELECT ID, post_content FROM {$post_table} WHERE post_content LIKE %s";
1633 $update_query = "UPDATE {$post_table} SET post_content = %s WHERE ID = %d";
1634 foreach ($this->replace_items as $args) {
1635 if($args['search'] != $args['replace']) {
1636 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1637 $results = $wpdb->get_results($sql_query, ARRAY_A );
1638 if(!empty($results)) {
1639 foreach ($results AS $row) {
1640 $content = $this->findAndReplaceContent($row['post_content'], $args['search'], $args['replace']);
1641 $update_post_query = $wpdb->prepare($update_query, $content, $row['ID']);
1642 $result = $wpdb->query($update_post_query);
1643 }
1644 }
1645 }
1646 }
1647 }
1648 }
1649
1650 /**
1651 * Checking image URLs in MetaData
1652 *
1653 * @since 2.6.3
1654 * @access public
1655 * @return $string
1656 *
1657 */
1658 function checkInOptions() {
1659 global $wpdb;
1660 $post_table = $wpdb->prefix."options";
1661 if(!empty($this->replace_items)) {
1662 $query = "SELECT option_id, option_value FROM {$post_table} WHERE option_value LIKE %s";
1663 $update_query = "UPDATE {$post_table} SET option_value = %s WHERE option_id = %d";
1664 foreach ($this->replace_items as $args) {
1665 if($args['search'] != $args['replace']) {
1666 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1667 $results = $wpdb->get_results($sql_query, ARRAY_A );
1668 if(!empty($results)) {
1669 foreach ($results AS $row) {
1670 $content = $this->findAndReplaceContent($row['option_value'], $args['search'], $args['replace']);
1671 $update_post_query = $wpdb->prepare($update_query, $content, $row['option_id']);
1672 $result = $wpdb->query($update_post_query);
1673 }
1674 }
1675 }
1676 }
1677 }
1678 }
1679
1680 /**
1681 * Checking image URLs in MetaData
1682 *
1683 * @since 2.6.3
1684 * @access public
1685 * @return $string
1686 *
1687 */
1688 function checkInMetaData() {
1689 $tables = array(
1690 array(
1691 'table_name' => 'usermeta',
1692 'primary_key' => 'umeta_id',
1693 'search_key' => 'meta_value'
1694 ),
1695 array(
1696 'table_name' => 'termmeta',
1697 'primary_key' => 'meta_id',
1698 'search_key' => 'meta_value'
1699 ),
1700 array(
1701 'table_name' => 'postmeta',
1702 'primary_key' => 'meta_id',
1703 'search_key' => 'meta_value'
1704 ),
1705 array(
1706 'table_name' => 'commentmeta',
1707 'primary_key' => 'meta_id',
1708 'search_key' => 'meta_value'
1709 )
1710 );
1711 global $wpdb;
1712 foreach ($tables as $table) {
1713 $post_table = $wpdb->prefix . $table['table_name'];
1714 if (!empty($this->replace_items)) {
1715 $query = "SELECT {$table['primary_key']}, {$table['search_key']} FROM {$post_table} WHERE {$table['search_key']} LIKE %s";
1716 $update_query = "UPDATE {$post_table} SET {$table['search_key']} = %s WHERE {$table['primary_key']} = %d";
1717 foreach ($this->replace_items as $args) {
1718 if ($args['search'] != $args['replace']) {
1719 $sql_query = $wpdb->prepare($query, "%" . $args['search'] . "%");
1720 $results = $wpdb->get_results($sql_query, ARRAY_A);
1721 if (!empty($results)) {
1722 foreach ($results as $row) {
1723 $content = $this->findAndReplaceContent($row[$table['search_key']], $args['search'], $args['replace']);
1724 $update_post_query = $wpdb->prepare($update_query, $content, $row[$table['primary_key']]);
1725 $result = $wpdb->query($update_post_query);
1726 }
1727 }
1728 }
1729 }
1730 }
1731 }
1732 }
1733
1734 /**
1735 * Checking for Array Key
1736 *
1737 * @since 2.6.3
1738 * @access public
1739 * @return $json
1740 * Forked from Enable Media Replace
1741 *
1742 */
1743 function findAndReplaceContent($content, $search, $replace, $depth = false) {
1744 $content = maybe_unserialize($content);
1745
1746 // Checking for JSON Data
1747 $isJson = $this->isJSON($content);
1748 if ($isJson) {
1749 $content = json_decode($content);
1750 }
1751
1752 // Replace content if content is String
1753 if (is_string($content)) {
1754 $content = str_replace($search, $replace, $content);
1755 }
1756 else if(is_wp_error($content)) { // Return if error in data
1757
1758 }
1759 else if(is_array($content)) { // Replace content if content is Array
1760 foreach($content as $index => $value) {
1761 $content[$index] = $this->findAndReplaceContent($value, $search, $replace, true);
1762 if (is_string($index)) {
1763 $index_replaced = $this->findAndReplaceContent($index, $search, $replace, true);
1764 if ($index_replaced !== $index)
1765 $content = $this->changeArrayKey($content, array($index => $index_replaced));
1766 }
1767 }
1768 }
1769 else if(is_object($content)) { // Replace content if content is Object
1770 foreach($content as $key => $value) {
1771 $content->{$key} = $this->findAndReplaceContent($value, $search, $replace, true);
1772 }
1773 }
1774
1775 if ($isJson && $depth === false) {
1776 $content = json_encode($content, JSON_UNESCAPED_SLASHES);
1777 }
1778 else if($depth === false && (is_array($content) || is_object($content))) {
1779 $content = maybe_serialize($content);
1780 }
1781
1782 return $content;
1783 }
1784
1785 /**
1786 * Checking for Array Key
1787 *
1788 * @since 2.6.3
1789 * @access public
1790 * @return $json
1791 *
1792 */
1793 function changeArrayKey($array, $set) {
1794 if (is_array($array) && is_array($set)) {
1795 $newArray = array();
1796 foreach ($array as $k => $v) {
1797 $key = array_key_exists( $k, $set) ? $set[$k] : $k;
1798 $newArray[$key] = is_array($v) ? $this->changeArrayKey($v, $set) : $v;
1799 }
1800 return $newArray;
1801 }
1802 return $array;
1803 }
1804
1805 /**
1806 * Check if it is JSON or not
1807 *
1808 * @since 2.6.3
1809 * @access public
1810 * Forked from Enable Media Replace
1811 * @return $json
1812 *
1813 */
1814 function isJSON($content)
1815 {
1816 if (is_array($content) || is_object($content))
1817 return false;
1818
1819 $json = json_decode($content);
1820 return $json && $json != $content;
1821 }
1822 }
1823 $folders_replace_media = new folders_replace_media();
1824