PluginProbe
Import Users & Customers with Meta | WP Ultimate CSV Importer Add-on / 1.4.1
Import Users & Customers with Meta | WP Ultimate CSV Importer Add-on v1.4.1
2.0 1.7.1 1.2.9 1.3 1.4 1.4.1 1.4.2 1.4.3 1.5 1.6 1.7 trunk 1.0 1.1 1.2 1.2.1 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8
import-users / importExtensions / MediaHandling.php

MediaHandling.php in Import Users & Customers with Meta | WP Ultimate CSV Importer Add-on 1.4.1, at importExtensions/MediaHandling.php

702 lines 23.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Import Users plugin file.
4 *
5 * Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
6 */
7
8 namespace Smackcoders\SMUSERS;
9
10 if ( ! defined( 'ABSPATH' ) )
11 exit; // Exit if accessed directly
12
13 class MediaHandling{
14 private static $instance=null;
15 public $header_array;
16 public $value_array;
17
18 public function __construct(){
19
20 require_once(ABSPATH.'wp-load.php');
21 require_once(ABSPATH . 'wp-admin/includes/image.php');
22 require_once(ABSPATH . 'wp-admin/includes/file.php');
23 add_action('wp_ajax_image_options', array($this , 'imageOptions'));
24 add_action('wp_ajax_delete_image' , array($this , 'deleteImage'));
25 }
26
27 public static function imageOptions(){
28 check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
29 $media_settings['use_ExistingImage'] = sanitize_text_field($_POST['use_ExistingImage']);
30 $media_settings['overwriteImage'] = sanitize_text_field($_POST['overwriteImage']);
31 $media_settings['title'] = sanitize_text_field($_POST['title']);
32 $media_settings['caption'] = sanitize_text_field($_POST['caption']);
33 $media_settings['alttext'] = sanitize_text_field($_POST['alttext']);
34 $media_settings['description'] = sanitize_text_field($_POST['description']);
35 $media_settings['file_name'] = sanitize_text_field($_POST['file_name']);
36 $media_settings['thumbnail'] = sanitize_text_field($_POST['thumbnail']);
37 $media_settings['media_handle_option'] = sanitize_text_field($_POST['media_handle_option']);
38 $media_settings['medium'] = sanitize_text_field($_POST['medium']);
39 $media_settings['medium_large'] = sanitize_text_field($_POST['medium_large']);
40 $media_settings['large'] = sanitize_text_field($_POST['large']);
41 $media_settings['custom'] = sanitize_text_field($_POST['custom']);
42 $media_settings['custom_slug'] = sanitize_text_field($_POST['custom_slug']);
43 $media_settings['custom_slug'] = sanitize_text_field($_POST['custom_width']);
44 $media_settings['custom_height'] = sanitize_text_field($_POST['custom_height']);
45 $image_info = array(
46 'media_settings' => $media_settings
47 );
48 update_option( 'smack_image_options', $image_info );
49 $result['success'] = 'true';
50 echo wp_json_encode($result);
51 wp_die();
52 }
53 public static function getInstance() {
54 if (MediaHandling::$instance == null) {
55 MediaHandling::$instance = new MediaHandling;
56 //MediaHandling::$instance->featured_image();
57 return MediaHandling::$instance;
58 }
59 return MediaHandling::$instance;
60 }
61
62 public function deleteImage(){
63 check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
64 $image = sanitize_text_field($_POST['image']);
65 $media_dir = wp_get_upload_dir();
66 $names = glob($media_dir['path'].'/'.'*.*');
67 foreach($names as $values){
68 if (strpos($values, $image) !== false) {
69 unlink($values);
70 }
71 }
72 $result['success'] = 'true';
73 echo wp_json_encode($result);
74 wp_die();
75 }
76
77 public function media_handling($img_url , $post_id , $data_array = null ,$module = null, $image_type = null ,$hash_key = null, $header_array = null , $value_array = null){
78 $encodedurl = urlencode($img_url);
79 $img_url = urldecode($encodedurl);
80 $media_handle = get_option('smack_image_options');
81 $image_name = basename($img_url);
82 $image_title = sanitize_file_name( pathinfo( $image_name, PATHINFO_FILENAME ) );
83 global $wpdb;
84
85 if($media_handle['media_settings']['media_handle_option'] == 'true'){
86 if($media_handle['media_settings']['use_ExistingImage'] == 'true'){
87 $guid_url = $img_url;
88 $attachment_id = $wpdb->get_results("select ID from {$wpdb->prefix}posts where guid = '$guid_url'" ,ARRAY_A);
89 if(!empty($attachment_id)){
90 foreach($attachment_id as $value){
91 $attach_id = $value['ID'];
92 if(!wp_get_attachment_url($attach_id)){
93 $attach_id = $this->image_function($img_url , $post_id , $data_array, '', 'use_existing_image',$header_array , $value_array );
94 }
95 }
96 }
97 else{
98 $attach_id = $this->image_function($img_url , $post_id , $data_array , '', 'use_existing_image',$header_array , $value_array);
99 }
100 }
101 elseif($media_handle['media_settings']['overwriteImage'] == 'true'){
102 $get_id = $wpdb->get_results("SELECT ID FROM {$wpdb->prefix}posts WHERE post_title = '$image_title' AND post_type = 'attachment' limit 1");
103 if(!empty($get_id)){
104 foreach($get_id as $value){
105 $attach_id = $value->ID;
106 $this->overwrite($attach_id , $img_url);
107 if(!empty($data_array['featured_image'])) {
108 set_post_thumbnail( $post_id, $attach_id );
109 }
110 }
111 }
112 else{
113 $attach_id = $this->image_function($img_url , $post_id , $data_array,'','',$header_array , $value_array);
114 }
115 }
116 else{
117 $attach_id = $this->image_function($img_url , $post_id , $data_array,'','',$header_array , $value_array);
118 }
119 }
120 else{
121 $guid_url = $img_url;
122 $attachment_id = $wpdb->get_results("select ID from {$wpdb->prefix}posts where guid = '$guid_url'" ,ARRAY_A);
123
124 if(!empty($attachment_id)){
125
126 foreach($attachment_id as $value){
127 $attach_id = $value['ID'];
128 if($_wp_attachment_metadata = get_post_meta($attach_id, '_wp_attachment_metadata', true)){
129 // When an attachment is available on Media and not has attachment link
130 if(!is_array($_wp_attachment_metadata)){
131 $attach_id = $this->image_function($img_url , $post_id , $data_array,'','',$header_array , $value_array);
132 }
133 }
134 //set_post_thumbnail( $post_id, $attach_id );
135 }
136 }
137 }
138 return $attach_id;
139 }
140
141 public function image_function($f_img , $post_id , $data_array = null,$option_name = null, $use_existing_image = false,$header_array = null , $value_array = null){
142
143 global $wpdb;
144 $media_handle = get_option('smack_image_options');
145 $media_settings = array_combine($header_array,$value_array);
146 if(isset($media_handle['media_settings']['alttext'])) {
147 $alttext ['_wp_attachment_image_alt'] = $media_settings[$media_handle['media_settings']['alttext']];
148 }
149 if(preg_match_all('/\b(?:(?:https?|?:http?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i', $f_img , $matchedlist, PREG_PATTERN_ORDER)) {
150 $f_img = $f_img;
151 }
152 else{
153 $media_dir = wp_get_upload_dir();
154 $names = glob($media_dir['path'].'/'.'*.*');
155 foreach($names as $values){
156 if (strpos($values, $f_img) !== false) {
157 $f_img = $media_dir['url'].'/'.$f_img;
158 }
159 }
160 }
161 $image_name = pathinfo($f_img);
162 if(!empty($media_handle['media_settings']['file_name'])){
163 $file_type = wp_check_filetype( $f_img, null );
164 $ext = '.'. $file_type['ext'];
165 $fimg_name = $media_settings[$media_handle['media_settings']['file_name']].$ext;
166 }
167 else{
168 $fimg_name = $image_name['basename'];
169 }
170
171 $file_type = wp_check_filetype( $fimg_name, null );
172 if($use_existing_image){
173 if(empty($file_type['ext'])){
174 $fimg_name = @basename($f_img);
175 $fimg_name = str_replace(' ', '-', trim($fimg_name));
176 $fimg_name = preg_replace('/[^a-zA-Z0-9._\-\s]/', '', $fimg_name);
177 }
178 $attachment_id = $wpdb->get_var("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type = 'attachment' AND guid LIKE '%$fimg_name'");
179
180 if($attachment_id){
181 if(!empty($data_array['featured_image'])){
182 set_post_thumbnail( $post_id, $attachment_id );
183 return $attachment_id;
184 }else{
185 return $attachment_id;
186 }
187 }
188 }
189
190 $attachment_title = sanitize_file_name( pathinfo( $fimg_name, PATHINFO_FILENAME ) );
191 $file_type = wp_check_filetype( $fimg_name, null );
192 $dir = wp_upload_dir();
193 $dirname = date('Y') . '/' . date('m');
194 $uploaddir_paths = $dir ['basedir'] . '/' . $dirname ;
195 $uploaddir_url = $dir ['baseurl'] . '/' . $dirname;
196 $f_img = str_replace(" ","%20",$f_img);
197 if(empty($file_type['ext'])){
198 $fimg_name = @basename($f_img);
199 $fimg_name = str_replace(' ', '-', trim($fimg_name));
200 $fimg_name = preg_replace('/[^a-zA-Z0-9._\-\s]/', '', $fimg_name);
201 }
202 if ($uploaddir_paths != "" && $uploaddir_paths) {
203 $uploaddir_path = $uploaddir_paths . "/" . $fimg_name;
204 }
205 //Removed curl and added wordpress http api
206 $response = wp_remote_get($f_img, array( 'timeout' => 10));
207 $rawdata = wp_remote_retrieve_body($response);
208 $http_code = wp_remote_retrieve_response_code($response);
209 if($http_code == 404){
210 return null;
211 }
212
213 if ( $http_code != 200 && strpos( $rawdata, 'Not Found' ) != 0 ) {
214 $rawdata = null;
215 }
216 if ($rawdata == false) {
217 return null;
218 } else {
219
220 if (file_exists($uploaddir_path)) {
221 $i = 1;
222 $exist = true;
223 while($exist){
224 $fimg_name = $attachment_title . "-" . $i . "." . $file_type['ext'];
225 $uploaddir_path = $uploaddir_paths . "/" . $fimg_name;
226
227 if (file_exists($uploaddir_path)) {
228 $i = $i + 1;
229 }
230 else{
231 $exist = false;
232 }
233 }
234 }
235
236 $fp = fopen($uploaddir_path, 'x');
237 fwrite($fp, $rawdata);
238 fclose($fp);
239 }
240 if(empty($file_type['type'])){
241 $file_type['type'] = 'image/jpeg';
242 }
243 $post_info = array(
244 'guid' => $uploaddir_url . "/" . $fimg_name,
245 'post_mime_type' => $file_type['type'],
246 'post_title' => $attachment_title,
247 'post_content' => '',
248 'post_status' => 'inherit',
249 );
250 //unset( $post_info['ID'] );
251 $attach_id = wp_insert_attachment( $post_info,$uploaddir_path, $post_id );
252 $attach_data = wp_generate_attachment_metadata( $attach_id, $uploaddir_path );
253 wp_update_attachment_metadata( $attach_id, $attach_data );
254 if($media_handle['media_settings']['thumbnail'] = 'true') {
255 $thumbnail_width = get_option('thumbnail_size_w');
256 $thumbnail_height = get_option('thumbnail_size_h');
257 $metadata = wp_get_attachment_metadata($attach_id);
258 $metadata['width'] = $thumbnail_width;
259 $metadata['height'] = $thumbnail_height;
260 wp_update_attachment_metadata($attach_id,$metadata);
261 }
262 elseif($media_handle['media_settings']['medium_'] = 'true'){
263 $medium_width = get_option('medium_size_w');
264 $medium_height = get_option('medium_size_h');
265 $metadata = wp_get_attachment_metadata($attach_id);
266 $metadata['width'] = $medium_width;
267 $metadata['height'] = $medium_height;
268 wp_update_attachment_metadata($attach_id,$metadata);
269 }
270 elseif($media_handle['media_settings']['medium_large'] = 'true') {
271 $medium_large_width = get_option('medium_large_size_w');
272 $medium_large_height = get_option('medium_large_size_h');
273 //add_image_size( 'medium_large', $medium_large_width, $medium_large_height, true );
274 $metadata = wp_get_attachment_metadata($attach_id);
275 $metadata['width'] = $medium_large_width;
276 $metadata['height'] = $medium_large_height;
277 wp_update_attachment_metadata($attach_id,$metadata);
278 }
279 elseif($media_handle['media_settings']['large'] = 'true'){
280 $large_width = get_option('large_size_w');
281 $large_height = get_option('large_size_h');
282 $metadata = wp_get_attachment_metadata($attach_id);
283 $metadata['width'] = $large_width;
284 $metadata['height'] = $large_height;
285 wp_update_attachment_metadata($attach_id,$metadata);
286 }
287 if(isset($media_handle['media_settings']['description'])){
288 $media_handle['media_settings']['description'] = $media_settings[$media_handle['media_settings']['description']];
289 }
290 if(isset($media_handle['media_settings']['caption'])){
291 $media_handle['media_settings']['caption'] = $media_settings[$media_handle['media_settings']['caption']];
292 }
293 if(isset($media_handle['media_settings']['title'])){
294 $media_handle['media_settings']['title'] = $media_settings[$media_handle['media_settings']['title']];
295 }
296 if(isset($media_handle['media_settings']['caption']) || isset($media_handle['media_settings']['description'])){
297 wp_update_post(array(
298 'ID' =>$attach_id,
299 'post_content' =>$media_handle['media_settings']['description'],
300 'post_excerpt' =>$media_handle['media_settings']['caption']
301 ));
302 }
303 if(isset($media_handle['media_settings']['title'])){
304 wp_update_post(array(
305 'ID' =>$attach_id,
306 'post_title' =>$media_handle['media_settings']['title']
307 ));
308 }
309 if($attach_id != null && isset($alttext['_wp_attachment_image_alt'])){
310 update_post_meta($attach_id, '_wp_attachment_image_alt', $alttext['_wp_attachment_image_alt']);
311 }
312 if(!empty($data_array['featured_image'])) {
313 set_post_thumbnail( $post_id, $attach_id );
314 }
315 delete_option( $option_name );
316 return $attach_id;
317 }
318
319
320 public function image_import($data_array){
321 $encodedurl = urlencode($data_array['featured_image']);
322 $data_array['featured_image'] = urldecode($encodedurl);
323 if(isset($data_array['alt_text'])) {
324 $alttext ['_wp_attachment_image_alt'] = $data_array['alt_text'];
325 }
326 if(preg_match_all('/\b(?:(?:https?|http|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i', $data_array['featured_image'] , $matchedlist, PREG_PATTERN_ORDER))
327 {
328 $f_img = $data_array['featured_image'];
329 }
330 else{
331 $media_dir = wp_get_upload_dir();
332 $names = glob($media_dir['path'].'/'.'*.*');
333 $f_img = $data_array['featured_image'];
334 foreach($names as $values){
335 if (strpos($values, $f_img) !== false) {
336 $f_img = $media_dir['url'].'/'.$f_img;
337 }
338 }
339 }
340 $image_name = pathinfo($f_img);
341 $attachment_title = sanitize_file_name( pathinfo( $f_img, PATHINFO_FILENAME ) );
342 $file_type = wp_check_filetype( $f_img, null );
343 $dir = wp_upload_dir();
344 $dirname = date('Y') . '/' . date('m');
345 $uploaddir_paths = $dir ['basedir'] . '/' . $dirname ;
346 $uploaddir_url = $dir ['baseurl'] . '/' . $dirname;
347 if(empty($file_type['ext']) || empty($data_array['file_name'])){
348 $fimg_name = @basename($f_img);
349 $fimg_name = str_replace(' ', '-', trim($fimg_name));
350 $fimg_name = preg_replace('/[^a-zA-Z0-9._\-\s]/', '', $fimg_name);
351 }
352 if(!empty($data_array['file_name'])){
353 $file_type = wp_check_filetype( $f_img, null );
354 $ext = '.'. $file_type['ext'];
355 $fimg_name = $data_array['file_name'].$ext;
356 }
357 if ($uploaddir_paths != "" && $uploaddir_paths) {
358 $uploaddir_path = $uploaddir_paths . "/" . $fimg_name;
359 }
360 if (strstr($f_img, 'https://drive.google.com')){
361 $page_content = file_get_contents($f_img);
362 $dom_obj = new \DOMDocument();
363 $dom_obj->loadHTML($page_content);
364 $meta_val = null;
365 foreach($dom_obj->getElementsByTagName('meta') as $meta) {
366 if($meta->getAttribute('property')=='og:image'){
367 $meta_val = $meta->getAttribute('content');
368 }
369 }
370
371 $response = wp_remote_get($meta_val);
372 $rawdata = wp_remote_retrieve_body($response);
373 }
374 //Removed curl and added wordpress http api
375 else{
376 if($file_type['ext'] == 'jpeg'){
377 $response = wp_remote_get($f_img, array( 'timeout' => 30));
378 }else{
379 $response = wp_remote_get($f_img, array( 'timeout' => 10));
380 }
381 $rawdata = wp_remote_retrieve_body($response);
382 }
383 $http_code = wp_remote_retrieve_response_code($response);
384
385 if($http_code == 404){
386 return null;
387 }
388
389 // When
390 if ( $http_code != 200 && strpos( $rawdata, 'Not Found' ) != 0 ) {
391 return null;
392 }
393
394 if ($rawdata == false) {
395
396 return null;
397 } else {
398
399 if (file_exists($uploaddir_path)) {
400 $i = 1;
401 $exist = true;
402 while($exist){
403 $fimg_name = $attachment_title . "-" . $i . "." . $file_type['ext'];
404 $uploaddir_path = $uploaddir_paths . "/" . $fimg_name;
405
406 if (file_exists($uploaddir_path)) {
407 $i = $i + 1;
408 }
409 else{
410 $exist = false;
411 }
412 }
413 }
414 $fp = fopen($uploaddir_path, 'x');
415 fwrite($fp, $rawdata);
416 fclose($fp);
417 }
418 if(empty($file_type['type'])){
419 $file_type['type'] = 'image/jpeg';
420 }
421 //Removed curl and added wordpress http api
422 $post_info = array(
423 'guid' => $uploaddir_url . "/" . $fimg_name,
424 'post_mime_type' => $file_type['type'],
425 'post_title' => $attachment_title,
426 'post_content' => '',
427 'post_status' => 'inherit',
428 );
429 unset( $post_info['ID'] );
430 $attach_id = wp_insert_attachment( $post_info,$uploaddir_path );
431 $attach_data = wp_generate_attachment_metadata( $attach_id, $uploaddir_path );
432 wp_update_attachment_metadata( $attach_id, $attach_data );
433 wp_update_post(array(
434 'ID' => $attach_id,
435 'post_title' => $data_array['title'],
436 'post_content' => $data_array['description'],
437 'post_excerpt' => $data_array['caption']
438 ));
439 if($attach_id != null && isset($alttext['_wp_attachment_image_alt'])){
440 update_post_meta($attach_id, '_wp_attachment_image_alt', $alttext['_wp_attachment_image_alt']);
441 }
442 return $attach_id;
443 }
444
445
446 function overwrite($post_id , $img_url){
447
448 global $wpdb;
449 $sql = "SELECT post_mime_type FROM {$wpdb->prefix}posts WHERE ID = $post_id";
450 list($current_filetype) = $wpdb->get_row($sql, ARRAY_N);
451 $current_filename = wp_get_attachment_url($post_id);
452
453 $current_guid = $current_filename;
454 $current_filename = substr($current_filename, (strrpos($current_filename, "/") + 1));
455
456 $ID = $post_id;
457
458 //$current_file = get_attached_file($ID, apply_filters( 'emr_unfiltered_get_attached_file', true ));
459 $current_file = get_attached_file($ID);
460 $current_path = substr($current_file, 0, (strrpos($current_file, "/")));
461 $current_file = preg_replace("|(?<!:)/{2,}|", "/", $current_file);
462 $current_filename = basename($current_file);
463 $current_metadata = wp_get_attachment_metadata( $post_id );
464
465 // $original_file_perms = fileperms($current_file) & 0777;
466
467 $data = file_get_contents($img_url);
468
469 $new_filename = basename($img_url);
470 $file_type = wp_check_filetype( $new_filename, null );
471 $new_filetype = $file_type["type"];
472 if(empty($new_filetype['ext'])){
473 $new_filename = @basename($img_url);
474 $new_filename = str_replace(' ', '-', trim($new_filename));
475 $new_filename = preg_replace('/[^a-zA-Z0-9._\-\s]/', '', $new_filename);
476 }
477 if(empty($new_filetype)){
478 $new_filetype = 'image/jpeg';
479 }
480
481 $original_file_perms = fileperms($current_file) & 0777;
482
483 $this->emr_delete_current_files( $current_file, $post_id, $current_metadata );
484
485 $new_filename = wp_unique_filename( $current_path, $new_filename );
486 $new_file = $current_path . "/" . $new_filename;
487 file_put_contents($new_file, $data);
488
489 @chmod($current_file, $original_file_perms);
490
491 $new_filetitle = preg_replace('/\.[^.]+$/', '', basename($new_file));
492 $new_guid = str_replace($current_filename, $new_filename, $current_guid);
493
494 $post_date = gmdate( 'Y-m-d H:i:s' );
495
496 $sql = $wpdb->prepare(
497 "UPDATE {$wpdb->prefix}posts SET post_title = '$new_filetitle', post_name = '$new_filetitle', guid = '$new_guid', post_mime_type = '$new_filetype', post_date = '$post_date', post_date_gmt = '$post_date' WHERE ID = %d;",
498 $post_id
499 );
500 $wpdb->query($sql);
501
502
503 $sql = $wpdb->prepare(
504 "SELECT meta_value FROM {$wpdb->prefix}postmeta WHERE meta_key = '_wp_attached_file' AND post_id = %d;",
505 $post_id
506 );
507
508 $old_meta_name = $wpdb->get_row($sql, ARRAY_A);
509 $old_meta_name = $old_meta_name["meta_value"];
510
511 // Make new postmeta _wp_attached_file
512 $new_meta_name = str_replace($current_filename, $new_filename, $old_meta_name);
513 $sql = $wpdb->prepare(
514 "UPDATE {$wpdb->prefix}postmeta SET meta_value = '$new_meta_name' WHERE meta_key = '_wp_attached_file' AND post_id = %d;",
515 $post_id
516 );
517 $wpdb->query($sql);
518
519 $new_metadata = wp_generate_attachment_metadata( $post_id, $new_file );
520 wp_update_attachment_metadata( $post_id, $new_metadata );
521
522
523
524 $current_base_url = $this->emr_get_match_url( $current_guid ); // .wp-contet.uplodas/ dae name without ext
525
526 $sql = $wpdb->prepare(
527 "SELECT ID, post_content FROM {$wpdb->prefix}posts WHERE post_status = 'publish' AND post_content LIKE %s;",
528 '%' . $current_base_url . '%'
529 );
530
531
532 $rs = $wpdb->get_results( $sql, ARRAY_A );
533
534 $number_of_updates = 0;
535
536
537 if ( ! empty( $rs ) ) {
538 $search_urls = $this->emr_get_file_urls( $current_guid, $current_metadata );
539 $replace_urls = $this->emr_get_file_urls( $new_guid, $new_metadata );
540 $replace_urls = $this->emr_normalize_file_urls( $search_urls, $replace_urls );
541
542 foreach ( $rs AS $rows ) {
543
544 $number_of_updates = $number_of_updates + 1;
545
546 // replace old URLs with new URLs.
547 $post_content = $rows["post_content"];
548
549 $post_content = addslashes( str_replace( $search_urls, $replace_urls, $post_content ) );
550
551 $sql = $wpdb->prepare(
552 "UPDATE {$wpdb->prefix}posts SET post_content = '$post_content' WHERE ID = %d;",
553 $rows["ID"]
554 );
555
556 $wpdb->query( $sql );
557 }
558 }
559 update_attached_file( $post_id, $new_file );
560
561 }
562
563
564 function emr_delete_current_files( $current_file, $post_id , $metadta = null ) {
565 // Delete old file
566
567 // Find path of current file
568 $current_path = substr($current_file, 0, (strrpos($current_file, "/")));
569
570 // Check if old file exists first
571 if (file_exists($current_file)) {
572 // Now check for correct file permissions for old file
573 clearstatcache();
574 if (is_writable($current_file)) {
575 // Everything OK; delete the file
576 unlink($current_file);
577 }
578 else {
579 // File exists, but has wrong permissions. Let the user know.
580 printf( esc_html__('The file %1$s can not be deleted by the web server, most likely because the permissions on the file are wrong.'), $current_file);
581 exit;
582 }
583 }
584
585 // Delete old resized versions if this was an image
586 $suffix = substr($current_file, (strlen($current_file)-4));
587 $prefix = substr($current_file, 0, (strlen($current_file)-4));
588
589 if (strtolower($suffix) === ".pdf") {
590 $prefix .= "-pdf";
591 $suffix = ".jpg";
592 }
593
594 $imgAr = array(".png", ".gif", ".jpg", ".jpeg");
595 if (in_array($suffix, $imgAr)) {
596 // It's a png/gif/jpg based on file name
597 // Get thumbnail filenames from metadata
598 if ( empty( $metadata ) ) {
599 $metadata = wp_get_attachment_metadata( $post_id );
600 }
601 // var_dump($metadata);exit;
602
603 if (is_array($metadata)) { // Added fix for error messages when there is no metadata (but WHY would there not be? I don't know…)
604 foreach($metadata["sizes"] AS $thissize) {
605 // Get all filenames and do an unlink() on each one;
606 $thisfile = $thissize["file"];
607 // Create array with all old sizes for replacing in posts later
608 $oldfilesAr[] = $thisfile;
609 // Look for files and delete them
610 if (strlen($thisfile)) {
611 $thisfile = $current_path . "/" . $thissize["file"];
612 if (file_exists($thisfile)) {
613 unlink($thisfile);
614 }
615 }
616 }
617 }
618
619 }
620 }
621
622 function emr_get_match_url($url) {
623 $url = $this->emr_remove_scheme($url);
624 $url = $this->emr_maybe_remove_query_string($url);
625 $url = $this->emr_remove_size_from_filename($url, true);
626 $url = $this->emr_remove_domain_from_filename($url);
627
628 return $url;
629 }
630
631 function emr_remove_scheme( $url ) {
632 return preg_replace( '/^(?:http|https):/', '', $url );
633 }
634
635 function emr_maybe_remove_query_string( $url ) {
636 $parts = explode( '?', $url );
637
638 return reset( $parts );
639 }
640
641 function emr_remove_size_from_filename( $url, $remove_extension = false ) {
642 $url = preg_replace( '/^(\S+)-[0-9]{1,4}x[0-9]{1,4}(\.[a-zA-Z0-9\.]{2,})?/', '$1$2', $url );
643
644 if ( $remove_extension ) {
645 $ext = pathinfo( $url, PATHINFO_EXTENSION );
646 $url = str_replace( ".$ext", '', $url );
647 }
648
649 return $url;
650 }
651
652 function emr_remove_domain_from_filename($url) {
653 // Holding place for possible future function
654 $url = str_replace($this->emr_remove_scheme(get_bloginfo('url')), '', $url);
655 return $url;
656 }
657
658
659 function emr_get_file_urls( $guid, $metadata ) {
660 $urls = array();
661
662 $guid = $this->emr_remove_scheme( $guid );
663 $guid= $this->emr_remove_domain_from_filename($guid);
664
665 $urls['guid'] = $guid;
666
667 if ( empty( $metadata ) ) {
668 return $urls;
669 }
670
671 $base_url = dirname( $guid );
672
673 if ( ! empty( $metadata['file'] ) ) {
674 $urls['file'] = trailingslashit( $base_url ) . wp_basename( $metadata['file'] );
675 }
676
677 if ( ! empty( $metadata['sizes'] ) ) {
678 foreach ( $metadata['sizes'] as $key => $value ) {
679 $urls[ $key ] = trailingslashit( $base_url ) . wp_basename( $value['file'] );
680 }
681 }
682
683 return $urls;
684 }
685
686 function emr_normalize_file_urls( $old, $new ) {
687 $result = array();
688
689 if ( empty( $new['guid'] ) ) {
690 return $result;
691 }
692
693 $guid = $new['guid'];
694
695 foreach ( $old as $key => $value ) {
696 $result[ $key ] = empty( $new[ $key ] ) ? $guid : $new[ $key ];
697 }
698
699 return $result;
700 }
701 }
702