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