PluginProbe ʕ •ᴥ•ʔ
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager / 2.9.4
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager v2.9.4
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 3 years ago tree.class.php 2 years ago
media.replace.php
1765 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 = wp_get_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 $ext = strtolower($file_ext);
1278
1279 $wpmime = wp_get_mime_types();
1280
1281 if(!isset($wpmime[$ext]) && !in_array($file['type'], $wpmime)) {
1282 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1283 }
1284
1285 if(!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) {
1286 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1287 }
1288
1289 if (wp_attachment_is('image', $attachment_id)) {
1290 $this->is_old_image = 1;
1291 }
1292 $this->old_file_url = $attachment_url;
1293 $this->old_image_meta = wp_get_attachment_metadata($attachment_id);
1294
1295 $new_file = $file['tmp_name'];
1296
1297 $file_parts = pathinfo($attachment_url);
1298
1299 $db_file_name = $file_parts['basename'];
1300 $db_file_array = explode(".", $db_file_name);
1301 array_pop($db_file_array);
1302 $db_file_name = implode(".", $db_file_array).".";
1303 $db_file_name .= $file_ext;
1304
1305 $wp_upload_path = wp_get_upload_dir();
1306
1307 $base_path = $old_path = $wp_upload_path['basedir'].DIRECTORY_SEPARATOR;
1308 $baseurl = $old_url = $wp_upload_path['baseurl']."/";
1309
1310 $post_upload = "";
1311
1312 $wp_attached_file = get_post_meta($attachment_id, "_wp_attached_file", true);
1313 if($wp_attached_file !== false) {
1314 $old_file_name = explode("/", $wp_attached_file);
1315 array_pop($old_file_name);
1316
1317 if(count($old_file_name) > 0) {
1318 $old_path .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1319 $old_url .= implode("/", $old_file_name);
1320 }
1321
1322 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'])) {
1323 $baseurl .= sanitize_text_field($_REQUEST['new_folder_path']);
1324 $base_path .= str_replace("/", DIRECTORY_SEPARATOR, $_REQUEST['new_folder_path']);
1325
1326 $post_upload = sanitize_text_field($_REQUEST['new_folder_path']);
1327 } else if(count($old_file_name) > 0) {
1328 $baseurl .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1329 $base_path .= implode("/", $old_file_name);
1330
1331 $post_upload = implode("/", $old_file_name);
1332 }
1333 }
1334
1335 $upload_dir = array();
1336 $upload_dir['path'] = $base_path;
1337 $upload_dir['old_path'] = $old_path;
1338 $upload_dir['url'] = $baseurl;
1339 $upload_dir['old_url'] = $old_url;
1340
1341 $this->upload_dir = $upload_dir;
1342
1343 $this->old_file_path = $old_path . "/" . $file_parts['basename'];
1344
1345 if (!is_dir($base_path)) {
1346 mkdir($base_path, 755, true);
1347 }
1348
1349 if (is_dir($base_path)) {
1350
1351 $file_array = explode(".", $file['name']);
1352 $file_ext = array_pop($file_array);
1353 $new_file_name = sanitize_title(implode(".", $file_array)).".".$file_ext;
1354 if($replacement_option == "replace_only_file") {
1355 $new_file_name = $db_file_name;
1356 }
1357
1358 if(strtolower($new_file_name) != strtolower($file_parts['basename'])) {
1359 $new_file_name = $this->checkForFileName($new_file_name, $base_path . DIRECTORY_SEPARATOR);
1360 }
1361
1362 $this->new_file_path = $base_path . DIRECTORY_SEPARATOR . $new_file_name;
1363
1364 $status = move_uploaded_file($new_file, $this->new_file_path);
1365
1366 $this->new_file_url = trim($baseurl, "/")."/".$new_file_name;
1367
1368 if ($status) {
1369 $old_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->old_file_path);
1370 $new_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->new_file_path);
1371 if($old_file_path != $new_file_path) {
1372 if(file_exists($this->old_file_path)) {
1373 @unlink($this->old_file_path);
1374 }
1375 }
1376
1377 update_attached_file($attachment->ID, $this->new_file_url);
1378
1379 $update_array = array();
1380 $update_array['ID'] = $attachment->ID;
1381 $update_array['guid'] = $this->new_file_url; //wp_get_attachment_url($this->post_id);
1382 $update_array['post_mime_type'] = $file['type'];
1383
1384 $current_date = date("Y-m-d H:i:s");
1385 $current_date_gmt = date_i18n("Y-m-d H:i:s", strtotime($current_date));
1386 if(isset($_REQUEST['date_options']) && !empty($_REQUEST['date_options'])) {
1387 if($_REQUEST['date_options'] == "replace_date") {
1388 $update_array['post_date'] = $current_date;
1389 $update_array['post_date_gmt'] = $current_date_gmt;
1390 } else if($_REQUEST['date_options'] == "custom_date") {
1391 $custom_date = sanitize_text_field($_POST['custom_date']);
1392 $custom_date = date("Y-m-d H:i:s", strtotime($custom_date));
1393 if($custom_date !== false && $this->validate_date($custom_date, "Y-m-d H:i:s")) {
1394 $datetime = date("Y-m-d H:i:s", strtotime($custom_date));
1395 $datetime_gmt = date_i18n("Y-m-d H:i:s", strtotime($datetime));
1396 $update_array['post_date'] = $datetime;
1397 $update_array['post_date_gmt'] = $datetime_gmt;
1398 }
1399 }
1400 }
1401 $update_array['post_modified'] = $current_date;
1402 $update_array['post_modified_gmt'] = $current_date_gmt;
1403 $post_id = wp_update_post($update_array, true);
1404
1405 update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name , "/"));
1406
1407 // update post doesn't update GUID on updates.
1408 $wpdb->update($wpdb->posts, array('guid' => $this->new_file_url), array('ID' => $attachment->ID));
1409
1410 $this->removeThumbImages();
1411
1412 $metadata = wp_generate_attachment_metadata($attachment->ID, $this->new_file_path);
1413 wp_update_attachment_metadata($attachment->ID, $metadata);
1414
1415 $this->new_image_meta = wp_get_attachment_metadata($attachment_id);
1416
1417 // update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name ), "/");
1418
1419 $this->searchAndReplace();
1420
1421 delete_post_meta($attachment_id, "folders_file_replaced");
1422 add_post_meta( $attachment_id, "folders_file_replaced", time(), true);
1423
1424 wp_redirect(admin_url("post.php?post=" . $attachment_id . "&action=edit&premio_message=success&image_update=1"));
1425 exit;
1426 } else {
1427 wp_die("Error during uploading file");
1428 }
1429
1430 } else {
1431 wp_die("Permission issue, Unable to create directory");
1432 }
1433 }
1434 }
1435 }
1436
1437 /**
1438 * Check for filename
1439 *
1440 * @since 2.6.3
1441 * @access public
1442 *
1443 */
1444 public function checkForFileName($fileName, $filePath, $postFix = 0) {
1445 $new_file_name = $fileName;
1446 if(!empty($postFix)) {
1447 $file_array = explode(".", $fileName);
1448 $file_ext = array_pop($file_array);
1449 $new_file_name = implode(".", $file_array)."-".$postFix.".".$file_ext;
1450 }
1451 if(!file_exists($filePath.$new_file_name)) {
1452 return $new_file_name;
1453 }
1454 return $this->checkForFileName($fileName, $filePath, ($postFix+1));
1455 }
1456
1457 public $replace_items = array();
1458
1459 /**
1460 * Check and Remove Thumb image in wp-content
1461 *
1462 * @since 2.6.3
1463 * @access public
1464 *
1465 */
1466 public function removeThumbImages() {
1467 if(!empty($this->old_image_meta) && isset($this->old_image_meta['sizes']) && !empty($this->upload_dir) && isset($this->upload_dir['path'])) {
1468 $path = $this->upload_dir['old_path'].DIRECTORY_SEPARATOR;
1469 foreach ($this->old_image_meta['sizes'] as $image) {
1470 if(file_exists($path.$image['file']) && (!isset($image['mime-type']) || $image['mime-type'] != 'image/svg+xml')) {
1471 @unlink($path . $image['file']);
1472 }
1473 }
1474 }
1475 }
1476
1477 /**
1478 * Search and Replace files in Database
1479 *
1480 * @since 2.6.3
1481 * @access public
1482 * @return $string
1483 *
1484 */
1485 public function searchAndReplace() {
1486 if (wp_attachment_is('image', $this->attachment_id)) {
1487 $this->is_new_image = 1;
1488 }
1489 if($this->old_file_url != $this->new_file_url) {
1490 $replace = array(
1491 'search' => $this->old_file_url,
1492 'replace' => $this->new_file_url,
1493 );
1494 $this->replace_items[] = $replace;
1495 }
1496
1497 $base_url = $this->upload_dir['url'];
1498 $base_url = trim($base_url, "/")."/";
1499 $new_url = $this->new_file_url;
1500
1501 if(isset($this->old_image_meta['sizes']) && !empty($this->old_image_meta['sizes'])) {
1502 if(!isset($this->new_image_meta['sizes']) || empty($this->new_image_meta['sizes'])) {
1503 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1504 $replace = array(
1505 'search' => $base_url.$image['file'],
1506 'replace' => $new_url,
1507 );
1508 $this->replace_items[] = $replace;
1509 }
1510 } else if(isset($this->new_image_meta['sizes']) && !empty($this->new_image_meta['sizes'])) {
1511 $new_size = $this->new_image_meta['sizes'];
1512 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1513 $new_replace_url = $new_url;
1514 if(isset($new_size[$key])) {
1515 $new_replace_url = $base_url.$new_size[$key]['file'];
1516 }
1517 $replace = array(
1518 'search' => $base_url.$image['file'],
1519 'replace' => $new_replace_url,
1520 );
1521 $this->replace_items[] = $replace;
1522 }
1523 }
1524 }
1525
1526 if(!empty($this->replace_items)) {
1527 $replace_items = array();
1528 foreach($this->replace_items as $args) {
1529 if($args['search'] != $args['replace']) {
1530 $replace_items[] = $args;
1531 }
1532 }
1533 $this->replace_items = $replace_items;
1534 $this->replaceURL();
1535 }
1536 }
1537
1538 /**
1539 * Replace URL in Database tables
1540 *
1541 * @since 2.6.3
1542 * @access public
1543 * @return $string
1544 *
1545 */
1546 function replaceURL() {
1547 /* check in post content */
1548 $this->checkInPostContent();
1549
1550 /* check in options */
1551 $this->checkInOptions();
1552
1553 /* check in meta */
1554 $this->checkInMetaData();
1555
1556 if(function_exists('folders_pro_clear_all_caches')) {
1557 folders_pro_clear_all_caches();
1558 }
1559 }
1560
1561 /**
1562 * Checking image URLs in Post Content
1563 *
1564 * @since 2.6.3
1565 * @access public
1566 * @return $string
1567 *
1568 */
1569 function checkInPostContent() {
1570 global $wpdb;
1571 $post_table = $wpdb->prefix."posts";
1572 if(!empty($this->replace_items)) {
1573 $query = "SELECT ID, post_content FROM {$post_table} WHERE post_content LIKE %s";
1574 $update_query = "UPDATE {$post_table} SET post_content = %s WHERE ID = %d";
1575 foreach ($this->replace_items as $args) {
1576 if($args['search'] != $args['replace']) {
1577 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1578 $results = $wpdb->get_results($sql_query, ARRAY_A );
1579 if(!empty($results)) {
1580 foreach ($results AS $row) {
1581 $content = $this->findAndReplaceContent($row['post_content'], $args['search'], $args['replace']);
1582 $update_post_query = $wpdb->prepare($update_query, $content, $row['ID']);
1583 $result = $wpdb->query($update_post_query);
1584 }
1585 }
1586 }
1587 }
1588 }
1589 }
1590
1591 /**
1592 * Checking image URLs in MetaData
1593 *
1594 * @since 2.6.3
1595 * @access public
1596 * @return $string
1597 *
1598 */
1599 function checkInOptions() {
1600 global $wpdb;
1601 $post_table = $wpdb->prefix."options";
1602 if(!empty($this->replace_items)) {
1603 $query = "SELECT option_id, option_value FROM {$post_table} WHERE option_value LIKE %s";
1604 $update_query = "UPDATE {$post_table} SET option_value = %s WHERE option_id = %d";
1605 foreach ($this->replace_items as $args) {
1606 if($args['search'] != $args['replace']) {
1607 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1608 $results = $wpdb->get_results($sql_query, ARRAY_A );
1609 if(!empty($results)) {
1610 foreach ($results AS $row) {
1611 $content = $this->findAndReplaceContent($row['option_value'], $args['search'], $args['replace']);
1612 $update_post_query = $wpdb->prepare($update_query, $content, $row['option_id']);
1613 $result = $wpdb->query($update_post_query);
1614 }
1615 }
1616 }
1617 }
1618 }
1619 }
1620
1621 /**
1622 * Checking image URLs in MetaData
1623 *
1624 * @since 2.6.3
1625 * @access public
1626 * @return $string
1627 *
1628 */
1629 function checkInMetaData() {
1630 $tables = array(
1631 array(
1632 'table_name' => 'usermeta',
1633 'primary_key' => 'umeta_id',
1634 'search_key' => 'meta_value'
1635 ),
1636 array(
1637 'table_name' => 'termmeta',
1638 'primary_key' => 'meta_id',
1639 'search_key' => 'meta_value'
1640 ),
1641 array(
1642 'table_name' => 'postmeta',
1643 'primary_key' => 'meta_id',
1644 'search_key' => 'meta_value'
1645 ),
1646 array(
1647 'table_name' => 'commentmeta',
1648 'primary_key' => 'meta_id',
1649 'search_key' => 'meta_value'
1650 )
1651 );
1652 global $wpdb;
1653 foreach ($tables as $table) {
1654 $post_table = $wpdb->prefix . $table['table_name'];
1655 if (!empty($this->replace_items)) {
1656 $query = "SELECT {$table['primary_key']}, {$table['search_key']} FROM {$post_table} WHERE {$table['search_key']} LIKE %s";
1657 $update_query = "UPDATE {$post_table} SET {$table['search_key']} = %s WHERE {$table['primary_key']} = %d";
1658 foreach ($this->replace_items as $args) {
1659 if ($args['search'] != $args['replace']) {
1660 $sql_query = $wpdb->prepare($query, "%" . $args['search'] . "%");
1661 $results = $wpdb->get_results($sql_query, ARRAY_A);
1662 if (!empty($results)) {
1663 foreach ($results as $row) {
1664 $content = $this->findAndReplaceContent($row[$table['search_key']], $args['search'], $args['replace']);
1665 $update_post_query = $wpdb->prepare($update_query, $content, $row[$table['primary_key']]);
1666 $result = $wpdb->query($update_post_query);
1667 }
1668 }
1669 }
1670 }
1671 }
1672 }
1673 }
1674
1675 /**
1676 * Checking for Array Key
1677 *
1678 * @since 2.6.3
1679 * @access public
1680 * @return $json
1681 * Forked from Enable Media Replace
1682 *
1683 */
1684 function findAndReplaceContent($content, $search, $replace, $depth = false) {
1685 $content = maybe_unserialize($content);
1686
1687 // Checking for JSON Data
1688 $isJson = $this->isJSON($content);
1689 if ($isJson) {
1690 $content = json_decode($content);
1691 }
1692
1693 // Replace content if content is String
1694 if (is_string($content)) {
1695 $content = str_replace($search, $replace, $content);
1696 }
1697 else if(is_wp_error($content)) { // Return if error in data
1698
1699 }
1700 else if(is_array($content)) { // Replace content if content is Array
1701 foreach($content as $index => $value) {
1702 $content[$index] = $this->findAndReplaceContent($value, $search, $replace, true);
1703 if (is_string($index)) {
1704 $index_replaced = $this->findAndReplaceContent($index, $search, $replace, true);
1705 if ($index_replaced !== $index)
1706 $content = $this->changeArrayKey($content, array($index => $index_replaced));
1707 }
1708 }
1709 }
1710 else if(is_object($content)) { // Replace content if content is Object
1711 foreach($content as $key => $value) {
1712 $content->{$key} = $this->findAndReplaceContent($value, $search, $replace, true);
1713 }
1714 }
1715
1716 if ($isJson && $depth === false) {
1717 $content = json_encode($content, JSON_UNESCAPED_SLASHES);
1718 }
1719 else if($depth === false && (is_array($content) || is_object($content))) {
1720 $content = maybe_serialize($content);
1721 }
1722
1723 return $content;
1724 }
1725
1726 /**
1727 * Checking for Array Key
1728 *
1729 * @since 2.6.3
1730 * @access public
1731 * @return $json
1732 *
1733 */
1734 function changeArrayKey($array, $set) {
1735 if (is_array($array) && is_array($set)) {
1736 $newArray = array();
1737 foreach ($array as $k => $v) {
1738 $key = array_key_exists( $k, $set) ? $set[$k] : $k;
1739 $newArray[$key] = is_array($v) ? $this->changeArrayKey($v, $set) : $v;
1740 }
1741 return $newArray;
1742 }
1743 return $array;
1744 }
1745
1746 /**
1747 * Check if it is JSON or not
1748 *
1749 * @since 2.6.3
1750 * @access public
1751 * Forked from Enable Media Replace
1752 * @return $json
1753 *
1754 */
1755 function isJSON($content)
1756 {
1757 if (is_array($content) || is_object($content))
1758 return false;
1759
1760 $json = json_decode($content);
1761 return $json && $json != $content;
1762 }
1763 }
1764 $folders_replace_media = new folders_replace_media();
1765