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