PluginProbe
Import Users & Customers with Meta | WP Ultimate CSV Importer Add-on / 1.2.6
Import Users & Customers with Meta | WP Ultimate CSV Importer Add-on v1.2.6
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.2.6, at importExtensions/MediaHandling.php

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