PluginProbe ʕ •ᴥ•ʔ
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager / 3.0.4
Folders – Unlimited Folders to Organize Media Library Folder, Pages, Posts, File Manager v3.0.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 2 years ago class-polylang.php 2 years ago class-review-box.php 2 years ago class-upgrade-box.php 2 years ago class-wpml.php 2 years ago folders.class.php 1 year ago form.class.php 2 years ago media.replace.php 1 year ago plugins.class.php 2 years ago svg.class.php 1 year ago tree.class.php 2 years ago
media.replace.php
1690 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="javascript:;" 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="javascript:;"><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="javascript:;" 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="javascript:;"><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 if($page == "media_page_folders-replace-media" || $page == "admin_page_folders-replace-media") {
909 wp_enqueue_style('folders-replace-media', plugin_dir_url(dirname(__FILE__)) . 'assets/css/replace-media.css', [], WCP_FOLDER_VERSION);
910
911 wp_enqueue_script('folders-simpledropit', plugin_dir_url(dirname(__FILE__)) . 'assets/js/simpledropit.min.js', [], WCP_FOLDER_VERSION, true);
912 wp_enqueue_script('folders-replace-media', plugin_dir_url(dirname(__FILE__)) . 'assets/js/replace-media.js', [], WCP_FOLDER_VERSION, true);
913 $maxUploadSize = ini_get("upload_max_filesize");
914 $maxUploadSize = str_replace(["K", "M", "G", "T", "P"],[" KB", " MB", " GB", " TB", " PB"], $maxUploadSize);
915 $maxSize = sprintf(esc_html__("Maximum file size %1\$s", "folders"), $maxUploadSize);
916 wp_localize_script('folders-simpledropit','replace_settings', [
917 'max_size' => $maxSize,
918 'file_name' => esc_html__("File name", 'folders'),
919 'file_size' => esc_html__("Size", 'folders'),
920 'file_type' => esc_html__("Type", 'folders'),
921 'dimension' => esc_html__("Dimension", 'folders'),
922 'drag_file' => esc_html__("Drag and drop files here", 'folders')
923 ]);
924 // wp_enqueue_script('jquery-ui-datepicker');
925 }
926 }
927
928 /**
929 * Add file replace menu in admin
930 *
931 * @since 2.6.3
932 * @access public
933 * @return $string
934 *
935 */
936 public function admin_menu() {
937 add_submenu_page("",
938 esc_html__("Replace media", "folders"),
939 esc_html__("Replace media", "folders"),
940 'upload_files',
941 'folders-replace-media',
942 array($this, 'folders_replace_media')
943 );
944 }
945
946 /**
947 * Add file replacement screen
948 *
949 * @since 2.6.3
950 * @access public
951 * @return $string
952 *
953 */
954 public function folders_replace_media() {
955 global $plugin_page;
956 $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
957 $attachment_id = isset($_GET['attachment_id']) ? sanitize_text_field($_GET['attachment_id']) : '';
958 $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : '';
959 if (!wp_verify_nonce($nonce, "folders-replace-media-".$attachment_id)) {
960 echo 'Invalid Nonce';
961 exit;
962 }
963 $attachment = get_post($attachment_id);
964 if(empty($attachment) || !isset($attachment->guid)) {
965 echo 'Invalid URL';
966 exit;
967 }
968 $guid = $attachment->guid;
969 $guid = explode(".", $guid);
970 if($guid == $attachment->guid) {
971 echo 'Invalid URL';
972 exit;
973 }
974 $form_action = $this->getMediaReplaceURL($attachment_id);
975 include_once dirname(dirname(__FILE__)) . WCP_DS . "/templates" . WCP_DS . "admin" . WCP_DS . "media-replace.php";
976 }
977
978 /**
979 * Add action for file replacement
980 *
981 * @since 2.6.3
982 * @access public
983 * @return $actions
984 *
985 */
986 public function add_media_action($actions, $post) {
987 if (!$this->isEnabled) {
988 return array_merge($actions);
989 }
990
991 if(current_user_can("upload_files")) {
992 if (wp_attachment_is('image', $post->ID)) {
993 $link = $this->getMediaReplaceURL($post->ID);
994 $newaction['replace_media'] = '<a style="color: ' . esc_attr($this->buttonColor) . '" href="' . esc_url($link) . '" rel="permalink">' . esc_html__("Replace media", "folders") . '</a>';
995 return array_merge($actions, $newaction);
996 } else {
997
998 $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>';
999 return array_merge($actions, $newaction);
1000 }
1001 }
1002
1003 return $actions;
1004 }
1005
1006 /**
1007 * Get URL for file Replacement
1008 *
1009 * @since 2.6.3
1010 * @access public
1011 * @return $url
1012 *
1013 */
1014 public function getMediaReplaceURL($attach_id) {
1015 $url = admin_url( "upload.php");
1016 $url = add_query_arg(array(
1017 'page' => 'folders-replace-media',
1018 'action' => 'folders_replace_media',
1019 'attachment_id' => $attach_id,
1020 'nonce' => wp_create_nonce("folders-replace-media-".$attach_id)
1021 ), $url);
1022
1023 return $url;
1024 }
1025
1026 /**
1027 * Update Metabox to Replace file name with title
1028 *
1029 * @since 2.6.3
1030 * @access public
1031 * @return $size
1032 *
1033 */
1034 public function replace_meta_box($post) {
1035 if(current_user_can("upload_files")) {
1036 if (wp_attachment_is('image', $post->ID)) {
1037 $link = $this->getMediaReplaceURL($post->ID); ?>
1038 <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>
1039 <?php } else { ?>
1040 <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>
1041 <?php }
1042 }
1043 }
1044
1045 /**
1046 * Add Metabox to replace file name with title
1047 *
1048 * @since 2.6.3
1049 * @access public
1050 *
1051 */
1052 public function change_file_name_box($post) {
1053 if(current_user_can("upload_files")) { ?>
1054 <p class="upgrade-bottom">
1055 <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>
1056 </p>
1057 <div class="upgrade-box">
1058 <a href="<?php echo esc_url($this->upgradeLink) ?>" target="_blank"><?php esc_html_e("Upgrade to Pro", "folders"); ?></a>
1059 </div>
1060 <?php
1061 }
1062 }
1063
1064 /**
1065 * Add metabox in media edit page
1066 *
1067 * @since 2.6.3
1068 * @access public
1069 * @return $size
1070 *
1071 */
1072 public function attachment_editor($form_fields, $post)
1073 {
1074 $screen = null;
1075 if (function_exists('get_current_screen'))
1076 {
1077 $screen = get_current_screen();
1078
1079 if(! is_null($screen) && $screen->id == 'attachment') // hide on edit attachment screen.
1080 return $form_fields;
1081 }
1082
1083 if(current_user_can("upload_files")) {
1084 if (wp_attachment_is('image', $post->ID)) {
1085 $link = $this->getMediaReplaceURL($post->ID);
1086 $form_fields["folders"] = [
1087 "label" => esc_html__("Replace media", "folders"),
1088 "input" => "html",
1089 "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>",
1090 "helps" => esc_html__("Click on the button to replace the file with another file", "folders"),
1091 ];
1092 } else {
1093 $form_fields["folders"] = [
1094 "label" => esc_html__("Replace media", "folders"),
1095 "input" => "html",
1096 "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>",
1097 "helps" => esc_html__("Click on the button to replace the file with another file", "folders"),
1098 ];
1099 }
1100 }
1101
1102 return $form_fields;
1103 }
1104
1105 /**
1106 * Replace filenanme with title
1107 *
1108 * @since 2.6.3
1109 * @access public
1110 * @return $size
1111 *
1112 */
1113 public function attachment_replace_name_with_title($form_fields, $post)
1114 {
1115 $screen = null;
1116 if (function_exists('get_current_screen'))
1117 {
1118 $screen = get_current_screen();
1119
1120 if(! is_null($screen) && $screen->id == 'attachment') // hide on edit attachment screen.
1121 return $form_fields;
1122 }
1123
1124 if(current_user_can("upload_files")) {
1125 $form_fields["replace_file_name"] = array(
1126 "label" => esc_html__("Replace media", "folders"),
1127 "input" => "html",
1128 "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>",
1129 "helps" => ""
1130 );
1131 }
1132
1133 return $form_fields;
1134 }
1135
1136 /**
1137 * Get file size
1138 *
1139 * @since 2.6.3
1140 * @access public
1141 * @return $size
1142 *
1143 */
1144 public function getFileSize($attachment_id) {
1145 $size = filesize( get_attached_file( $attachment_id ));
1146 if($size > 1000000) {
1147 $size = ($size/1000000);
1148 return number_format((float)$size, 2, ".", ",")." MB";
1149 } else if($size > 1000) {
1150 $size = ($size/1000);
1151 return number_format((float)$size, 2, ".", ",")." KB";
1152 }
1153 return $size." B";
1154 }
1155
1156 /**
1157 * Check for valid date
1158 *
1159 * @since 2.6.3
1160 * @access public
1161 *
1162 */
1163
1164 function validate_date($date, $format = 'Y-m-d') {
1165 $d = DateTime::createFromFormat($format, $date);
1166 // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
1167 return $d && $d->format($format) === $date;
1168 }
1169
1170 /**
1171 * Upload file and Replace it
1172 *
1173 * @since 2.6.3
1174 * @access public
1175 *
1176 */
1177 public function handle_folders_file_upload() {
1178 global $wpdb;
1179 if(isset($_FILES['new_media_file'])) {
1180 if($_FILES['new_media_file']['error'] == 0) {
1181 $attachment_id = isset($_GET['attachment_id']) ? sanitize_text_field($_GET['attachment_id']) : '';
1182 $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : '';
1183 if (!wp_verify_nonce($nonce, "folders-replace-media-" . $attachment_id)) {
1184 return;
1185 }
1186 $attachment = get_post($attachment_id);
1187 if (empty($attachment) || !isset($attachment->guid)) {
1188 return;
1189 }
1190 $attachment_url = $attachment->guid;
1191 $url = wp_get_attachment_url($attachment_id);
1192 if(!empty($url)) {
1193 $attachment_url = $url;
1194 }
1195 $guid = explode(".", $attachment_url);
1196 $guid = array_pop($guid);
1197 if ($guid == $attachment->guid) {
1198 return;
1199 }
1200
1201 $replacement_option = "replace_only_file";
1202
1203 $this->attachment_id = $attachment_id;
1204
1205 $file = $_FILES['new_media_file'];
1206 $file_name = $file['name'];
1207 $file_ext = explode(".", $file_name);
1208 $file_ext = array_pop($file_ext);
1209 $ext = strtolower($file_ext);
1210
1211 $wpmime = get_allowed_mime_types();
1212
1213 if(!isset($wpmime[$ext]) && !in_array($file['type'], $wpmime)) {
1214 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1215 }
1216
1217 if(!in_array($ext, ['jpg', 'png', 'jpeg', 'gif', 'svg'])) {
1218 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1219 }
1220
1221 if(!in_array($file['type'], ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'])) {
1222 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1223 }
1224
1225 if($file_ext == "svg" || $file['type'] == 'image/svg+xml') {
1226 $status = sanitizeSvgFileContent($file['tmp_name']);
1227 if(!$status) {
1228 wp_die(esc_html__("Sorry, this file type is not permitted for security reasons", "folders"));
1229 }
1230 }
1231
1232 if (wp_attachment_is('image', $attachment_id)) {
1233 $this->is_old_image = 1;
1234 }
1235
1236 $this->old_file_url = $attachment_url;
1237 $this->old_image_meta = wp_get_attachment_metadata($attachment_id);
1238
1239 $new_file = $file['tmp_name'];
1240
1241 $file_parts = pathinfo($attachment_url);
1242
1243 $db_file_name = $file_parts['basename'];
1244 $db_file_array = explode(".", $db_file_name);
1245 array_pop($db_file_array);
1246 $db_file_name = implode(".", $db_file_array).".";
1247 $db_file_name .= $file_ext;
1248
1249 $wp_upload_path = wp_get_upload_dir();
1250
1251 $base_path = $old_path = $wp_upload_path['basedir'].DIRECTORY_SEPARATOR;
1252 $baseurl = $old_url = $wp_upload_path['baseurl']."/";
1253
1254 $post_upload = "";
1255
1256 $wp_attached_file = get_post_meta($attachment_id, "_wp_attached_file", true);
1257 if($wp_attached_file !== false) {
1258 $old_file_name = explode("/", $wp_attached_file);
1259 array_pop($old_file_name);
1260
1261 if(count($old_file_name) > 0) {
1262 $old_path .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1263 $old_url .= implode("/", $old_file_name);
1264 }
1265
1266 if(count($old_file_name) > 0) {
1267 $baseurl .= implode(DIRECTORY_SEPARATOR, $old_file_name);
1268 $base_path .= implode("/", $old_file_name);
1269 $post_upload = implode("/", $old_file_name);
1270 }
1271 }
1272
1273 $upload_dir = [];
1274 $upload_dir['path'] = $base_path;
1275 $upload_dir['old_path'] = $old_path;
1276 $upload_dir['url'] = $baseurl;
1277 $upload_dir['old_url'] = $old_url;
1278
1279 $this->upload_dir = $upload_dir;
1280
1281 $this->old_file_path = $old_path . "/" . $file_parts['basename'];
1282
1283 if (!is_dir($base_path)) {
1284 mkdir($base_path, 755, true);
1285 }
1286
1287 if (is_dir($base_path)) {
1288
1289 $file_array = explode(".", $file['name']);
1290 $file_ext = array_pop($file_array);
1291 $new_file_name = sanitize_title(implode(".", $file_array)).".".$file_ext;
1292
1293 if($replacement_option == "replace_only_file") {
1294 $new_file_name = $db_file_name;
1295 }
1296
1297 if(strtolower($new_file_name) != strtolower($file_parts['basename'])) {
1298 $new_file_name = $this->checkForFileName($new_file_name, $base_path . DIRECTORY_SEPARATOR);
1299 }
1300
1301 $this->new_file_path = $base_path . DIRECTORY_SEPARATOR . $new_file_name;
1302
1303 $status = move_uploaded_file($new_file, $this->new_file_path);
1304
1305 $this->new_file_url = trim($baseurl, "/")."/".$new_file_name;
1306
1307 if ($status) {
1308 $old_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->old_file_path);
1309 $new_file_path = str_replace(array("/",DIRECTORY_SEPARATOR), array("", ""), $this->new_file_path);
1310 if($old_file_path != $new_file_path) {
1311 if(file_exists($this->old_file_path)) {
1312 @wp_delete_file($this->old_file_path);
1313 }
1314 }
1315
1316 update_attached_file($attachment->ID, $this->new_file_url);
1317
1318 $update_array = [];
1319 $update_array['ID'] = $attachment->ID;
1320 $update_array['guid'] = $this->new_file_url; //wp_get_attachment_url($this->post_id);
1321 $update_array['post_mime_type'] = $file['type'];
1322
1323 $current_date = date("Y-m-d H:i:s");
1324 $current_date_gmt = date_i18n("Y-m-d H:i:s", strtotime($current_date));
1325
1326 $update_array['post_modified'] = $current_date;
1327 $update_array['post_modified_gmt'] = $current_date_gmt;
1328 $post_id = wp_update_post($update_array, true);
1329
1330 update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name , "/"));
1331
1332 // update post doesn't update GUID on updates.
1333 $wpdb->update($wpdb->posts, array('guid' => $this->new_file_url), array('ID' => $attachment->ID));
1334
1335 $this->removeThumbImages();
1336
1337 $metadata = wp_generate_attachment_metadata($attachment->ID, $this->new_file_path);
1338 wp_update_attachment_metadata($attachment->ID, $metadata);
1339
1340 $this->new_image_meta = wp_get_attachment_metadata($attachment_id);
1341
1342 // update_post_meta( $attachment_id, '_wp_attached_file', trim(trim($post_upload, "/")."/".$new_file_name ), "/");
1343
1344 $this->searchAndReplace();
1345
1346 delete_post_meta($attachment_id, "folders_file_replaced");
1347 add_post_meta( $attachment_id, "folders_file_replaced", time(), true);
1348
1349 wp_redirect(admin_url("post.php?post=" . $attachment_id . "&action=edit&premio_message=success&image_update=1"));
1350 exit;
1351 } else {
1352 wp_die("Error during uploading file");
1353 }
1354
1355 } else {
1356 wp_die("Permission issue, Unable to create directory");
1357 }
1358 }
1359 }
1360 }
1361
1362 /**
1363 * Check for filename
1364 *
1365 * @since 2.6.3
1366 * @access public
1367 *
1368 */
1369 public function checkForFileName($fileName, $filePath, $postFix = 0) {
1370 $new_file_name = $fileName;
1371 if(!empty($postFix)) {
1372 $file_array = explode(".", $fileName);
1373 $file_ext = array_pop($file_array);
1374 $new_file_name = implode(".", $file_array)."-".$postFix.".".$file_ext;
1375 }
1376 if(!file_exists($filePath.$new_file_name)) {
1377 return $new_file_name;
1378 }
1379 return $this->checkForFileName($fileName, $filePath, ($postFix+1));
1380 }
1381
1382 public $replace_items = [];
1383
1384 /**
1385 * Check and Remove Thumb image in wp-content
1386 *
1387 * @since 2.6.3
1388 * @access public
1389 *
1390 */
1391 public function removeThumbImages() {
1392 if(!empty($this->old_image_meta) && isset($this->old_image_meta['sizes']) && !empty($this->upload_dir) && isset($this->upload_dir['path'])) {
1393 $path = $this->upload_dir['old_path'].DIRECTORY_SEPARATOR;
1394 foreach ($this->old_image_meta['sizes'] as $image) {
1395 if(file_exists($path.$image['file']) && (!isset($image['mime-type']) || $image['mime-type'] != 'image/svg+xml')) {
1396 @wp_delete_file($path . $image['file']);
1397 }
1398 }
1399 }
1400 }
1401
1402 /**
1403 * Search and Replace files in Database
1404 *
1405 * @since 2.6.3
1406 * @access public
1407 * @return $string
1408 *
1409 */
1410 public function searchAndReplace() {
1411 if (wp_attachment_is('image', $this->attachment_id)) {
1412 $this->is_new_image = 1;
1413 }
1414 if($this->old_file_url != $this->new_file_url) {
1415 $replace = array(
1416 'search' => $this->old_file_url,
1417 'replace' => $this->new_file_url,
1418 );
1419 $this->replace_items[] = $replace;
1420 }
1421
1422 $base_url = $this->upload_dir['url'];
1423 $base_url = trim($base_url, "/")."/";
1424 $new_url = $this->new_file_url;
1425
1426 if(isset($this->old_image_meta['sizes']) && !empty($this->old_image_meta['sizes'])) {
1427 if(!isset($this->new_image_meta['sizes']) || empty($this->new_image_meta['sizes'])) {
1428 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1429 $replace = array(
1430 'search' => $base_url.$image['file'],
1431 'replace' => $new_url,
1432 );
1433 $this->replace_items[] = $replace;
1434 }
1435 } else if(isset($this->new_image_meta['sizes']) && !empty($this->new_image_meta['sizes'])) {
1436 $new_size = $this->new_image_meta['sizes'];
1437 foreach ($this->old_image_meta['sizes'] as $key=>$image) {
1438 $new_replace_url = $new_url;
1439 if(isset($new_size[$key])) {
1440 $new_replace_url = $base_url.$new_size[$key]['file'];
1441 }
1442 $replace = array(
1443 'search' => $base_url.$image['file'],
1444 'replace' => $new_replace_url,
1445 );
1446 $this->replace_items[] = $replace;
1447 }
1448 }
1449 }
1450
1451 if(!empty($this->replace_items)) {
1452 $replace_items = [];
1453 foreach($this->replace_items as $args) {
1454 if($args['search'] != $args['replace']) {
1455 $replace_items[] = $args;
1456 }
1457 }
1458 $this->replace_items = $replace_items;
1459 $this->replaceURL();
1460 }
1461 }
1462
1463 /**
1464 * Replace URL in Database tables
1465 *
1466 * @since 2.6.3
1467 * @access public
1468 * @return $string
1469 *
1470 */
1471 function replaceURL() {
1472 /* check in post content */
1473 $this->checkInPostContent();
1474
1475 /* check in options */
1476 $this->checkInOptions();
1477
1478 /* check in meta */
1479 $this->checkInMetaData();
1480
1481 if(function_exists('folders_pro_clear_all_caches')) {
1482 folders_pro_clear_all_caches();
1483 }
1484 }
1485
1486 /**
1487 * Checking image URLs in Post Content
1488 *
1489 * @since 2.6.3
1490 * @access public
1491 * @return $string
1492 *
1493 */
1494 function checkInPostContent() {
1495 global $wpdb;
1496 $post_table = $wpdb->prefix."posts";
1497 if(!empty($this->replace_items)) {
1498 $query = "SELECT ID, post_content FROM {$post_table} WHERE post_content LIKE %s";
1499 $update_query = "UPDATE {$post_table} SET post_content = %s WHERE ID = %d";
1500 foreach ($this->replace_items as $args) {
1501 if($args['search'] != $args['replace']) {
1502 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1503 $results = $wpdb->get_results($sql_query, ARRAY_A );
1504 if(!empty($results)) {
1505 foreach ($results AS $row) {
1506 $content = $this->findAndReplaceContent($row['post_content'], $args['search'], $args['replace']);
1507 $update_post_query = $wpdb->prepare($update_query, $content, $row['ID']);
1508 $result = $wpdb->query($update_post_query);
1509 }
1510 }
1511 }
1512 }
1513 }
1514 }
1515
1516 /**
1517 * Checking image URLs in MetaData
1518 *
1519 * @since 2.6.3
1520 * @access public
1521 * @return $string
1522 *
1523 */
1524 function checkInOptions() {
1525 global $wpdb;
1526 $post_table = $wpdb->prefix."options";
1527 if(!empty($this->replace_items)) {
1528 $query = "SELECT option_id, option_value FROM {$post_table} WHERE option_value LIKE %s";
1529 $update_query = "UPDATE {$post_table} SET option_value = %s WHERE option_id = %d";
1530 foreach ($this->replace_items as $args) {
1531 if($args['search'] != $args['replace']) {
1532 $sql_query = $wpdb->prepare($query, "%".$args['search']."%");
1533 $results = $wpdb->get_results($sql_query, ARRAY_A );
1534 if(!empty($results)) {
1535 foreach ($results AS $row) {
1536 $content = $this->findAndReplaceContent($row['option_value'], $args['search'], $args['replace']);
1537 $update_post_query = $wpdb->prepare($update_query, $content, $row['option_id']);
1538 $result = $wpdb->query($update_post_query);
1539 }
1540 }
1541 }
1542 }
1543 }
1544 }
1545
1546 /**
1547 * Checking image URLs in MetaData
1548 *
1549 * @since 2.6.3
1550 * @access public
1551 * @return $string
1552 *
1553 */
1554 function checkInMetaData() {
1555 $tables = array(
1556 array(
1557 'table_name' => 'usermeta',
1558 'primary_key' => 'umeta_id',
1559 'search_key' => 'meta_value'
1560 ),
1561 array(
1562 'table_name' => 'termmeta',
1563 'primary_key' => 'meta_id',
1564 'search_key' => 'meta_value'
1565 ),
1566 array(
1567 'table_name' => 'postmeta',
1568 'primary_key' => 'meta_id',
1569 'search_key' => 'meta_value'
1570 ),
1571 array(
1572 'table_name' => 'commentmeta',
1573 'primary_key' => 'meta_id',
1574 'search_key' => 'meta_value'
1575 )
1576 );
1577 global $wpdb;
1578 foreach ($tables as $table) {
1579 $post_table = $wpdb->prefix . $table['table_name'];
1580 if (!empty($this->replace_items)) {
1581 $query = "SELECT {$table['primary_key']}, {$table['search_key']} FROM {$post_table} WHERE {$table['search_key']} LIKE %s";
1582 $update_query = "UPDATE {$post_table} SET {$table['search_key']} = %s WHERE {$table['primary_key']} = %d";
1583 foreach ($this->replace_items as $args) {
1584 if ($args['search'] != $args['replace']) {
1585 $sql_query = $wpdb->prepare($query, "%" . $args['search'] . "%");
1586 $results = $wpdb->get_results($sql_query, ARRAY_A);
1587 if (!empty($results)) {
1588 foreach ($results as $row) {
1589 $content = $this->findAndReplaceContent($row[$table['search_key']], $args['search'], $args['replace']);
1590 $update_post_query = $wpdb->prepare($update_query, $content, $row[$table['primary_key']]);
1591 $result = $wpdb->query($update_post_query);
1592 }
1593 }
1594 }
1595 }
1596 }
1597 }
1598 }
1599
1600 /**
1601 * Checking for Array Key
1602 *
1603 * @since 2.6.3
1604 * @access public
1605 * @return $json
1606 * Forked from Enable Media Replace
1607 *
1608 */
1609 function findAndReplaceContent($content, $search, $replace, $depth = false) {
1610 $content = maybe_unserialize($content);
1611
1612 // Checking for JSON Data
1613 $isJson = $this->isJSON($content);
1614 if ($isJson) {
1615 $content = json_decode($content);
1616 }
1617
1618 // Replace content if content is String
1619 if (is_string($content)) {
1620 $content = str_replace($search, $replace, $content);
1621 }
1622 else if(is_wp_error($content)) { // Return if error in data
1623
1624 }
1625 else if(is_array($content)) { // Replace content if content is Array
1626 foreach($content as $index => $value) {
1627 $content[$index] = $this->findAndReplaceContent($value, $search, $replace, true);
1628 if (is_string($index)) {
1629 $index_replaced = $this->findAndReplaceContent($index, $search, $replace, true);
1630 if ($index_replaced !== $index)
1631 $content = $this->changeArrayKey($content, array($index => $index_replaced));
1632 }
1633 }
1634 }
1635 else if(is_object($content)) { // Replace content if content is Object
1636 foreach($content as $key => $value) {
1637 $content->{$key} = $this->findAndReplaceContent($value, $search, $replace, true);
1638 }
1639 }
1640
1641 if ($isJson && $depth === false) {
1642 $content = wp_json_encode($content, JSON_UNESCAPED_SLASHES);
1643 }
1644 else if($depth === false && (is_array($content) || is_object($content))) {
1645 $content = maybe_serialize($content);
1646 }
1647
1648 return $content;
1649 }
1650
1651 /**
1652 * Checking for Array Key
1653 *
1654 * @since 2.6.3
1655 * @access public
1656 * @return $json
1657 *
1658 */
1659 function changeArrayKey($array, $set) {
1660 if (is_array($array) && is_array($set)) {
1661 $newArray = [];
1662 foreach ($array as $k => $v) {
1663 $key = array_key_exists( $k, $set) ? $set[$k] : $k;
1664 $newArray[$key] = is_array($v) ? $this->changeArrayKey($v, $set) : $v;
1665 }
1666 return $newArray;
1667 }
1668 return $array;
1669 }
1670
1671 /**
1672 * Check if it is JSON or not
1673 *
1674 * @since 2.6.3
1675 * @access public
1676 * Forked from Enable Media Replace
1677 * @return $json
1678 *
1679 */
1680 function isJSON($content)
1681 {
1682 if (is_array($content) || is_object($content))
1683 return false;
1684
1685 $json = json_decode($content);
1686 return $json && $json != $content;
1687 }
1688 }
1689 $folders_replace_media = new folders_replace_media();
1690