Replacer.php
17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
<?php
namespace EnableMediaReplace\Replacer;
use EnableMediaReplace\ShortPixelLogger\ShortPixelLogger as Log;
use EnableMediaReplace\Replacer\Libraries\Unserialize\Unserialize;
/** Module: Replacer.
*
* - Able to replace across database
* - Only replace thumbnails feature dependent on media library
* - Support for page builders / strange data
*/
class Replacer
{
protected $source_url;
protected $target_url;
protected $source_metadata = array();
protected $target_metadata = array();
public function __construct()
{
//$this->source_url = $source_url;
///$this->target_url = $target_url;
$this->loadFormats();
}
// Load classes that handle alternative formats that can occur in the metadata / post data.
protected function loadFormats()
{
Modules\Elementor::getInstance();
Modules\WpBakery::getInstance();
Modules\YoastSeo::getInstance();
}
public function setSource($url)
{
$this->source_url = $url;
}
public function getSource()
{
return $this->source_url;
}
public function setTarget($url)
{
$this->target_url = $url;
}
public function getTarget()
{
return $this->target_url;
}
public function setSourceMeta($meta)
{
$this->source_metadata = $meta;
}
public function setTargetMeta($meta)
{
$this->target_metadata = $meta;
}
public function replace($args = array())
{
if (is_null($this->source_url) || is_null($this->target_url))
{
Log::addWarn('Replacer called without source or target ');
return false;
}
$defaults = array(
'thumbnails_only' => false,
);
$errors = array();
$args = wp_parse_args($args, $defaults);
// Search-and-replace filename in post database
// @todo Check this with scaled images.
$base_url = parse_url($this->source_url, PHP_URL_PATH);// emr_get_match_url( $this->source_url);
$base_url = str_replace('.' . pathinfo($base_url, PATHINFO_EXTENSION), '', $base_url);
/** Fail-safe if base_url is a whole directory, don't go search/replace */
if (is_dir($base_url))
{
Log::addError('Search Replace tried to replace to directory - ' . $base_url);
$errors[] = __('Fail Safe :: Source Location seems to be a directory.', 'enable-media-replace');
return $errors;
}
if (strlen(trim($base_url)) == 0)
{
Log::addError('Current Base URL emtpy - ' . $base_url);
$errors[] = __('Fail Safe :: Source Location returned empty string. Not replacing content','enable-media-replace');
return $errors;
}
// get relurls of both source and target.
$urls = $this->getRelativeURLS();
if ($args['thumbnails_only'])
{
foreach($urls as $side => $data)
{
if (isset($data['base']))
{
unset($urls[$side]['base']);
}
if (isset($data['file']))
{
unset($urls[$side]['file']);
}
}
}
$search_urls = $urls['source'];
$replace_urls = $urls['target'];
/* If the replacement is much larger than the source, there can be more thumbnails. This leads to disbalance in the search/replace arrays.
Remove those from the equation. If the size doesn't exist in the source, it shouldn't be in use either */
foreach($replace_urls as $size => $url)
{
if (! isset($search_urls[$size]))
{
Log::addDebug('Dropping size ' . $size . ' - not found in source urls');
unset($replace_urls[$size]);
}
}
Log::addDebug('Source', $this->source_metadata);
Log::addDebug('Target', $this->target_metadata);
/* If on the other hand, some sizes are available in source, but not in target, try to replace them with something closeby. */
foreach($search_urls as $size => $url)
{
if (! isset($replace_urls[$size]))
{
$closest = $this->findNearestSize($size);
if ($closest)
{
$sourceUrl = $search_urls[$size];
$baseurl = trailingslashit(str_replace(wp_basename($sourceUrl), '', $sourceUrl));
Log::addDebug('Nearest size of source ' . $size . ' for target is ' . $closest);
$replace_urls[$size] = $baseurl . $closest;
}
else
{
Log::addDebug('Unset size ' . $size . ' - no closest found in source');
}
}
}
/* If source and target are the same, remove them from replace. This happens when replacing a file with same name, and +/- same dimensions generated.
After previous loops, for every search there should be a replace size.
*/
foreach($search_urls as $size => $url)
{
$replace_url = isset($replace_urls[$size]) ? $replace_urls[$size] : false;
if ($url == $replace_url) // if source and target as the same, no need for replacing.
{
unset($search_urls[$size]);
unset($replace_urls[$size]);
}
}
// If the two sides are disbalanced, the str_replace part will cause everything that has an empty replace counterpart to replace it with empty. Unwanted.
if (count($search_urls) !== count($replace_urls))
{
Log::addError('Unbalanced Replace Arrays, aborting', array($search_urls, $replace_urls, count($search_urls), count($replace_urls) ));
$errors[] = __('There was an issue with updating your image URLS: Search and replace have different amount of values. Aborting updating thumbnails', 'enable-media-replace');
return $errors;
}
Log::addDebug('Doing meta search and replace -', array($search_urls, $replace_urls) );
Log::addDebug('Searching with BaseuRL ' . $base_url);
do_action('shortpixel/replacer/replace_urls', $search_urls, $replace_urls);
$updated = 0;
$updated += $this->doReplaceQuery($base_url, $search_urls, $replace_urls);
$replaceRuns = apply_filters('shortpixel/replacer/custom_replace_query', array(), $base_url, $search_urls, $replace_urls);
Log::addDebug("REPLACE RUNS", $replaceRuns);
foreach($replaceRuns as $component => $run)
{
Log::addDebug('Running additional replace for : '. $component, $run);
$updated += $this->doReplaceQuery($run['base_url'], $run['search_urls'], $run['replace_urls']);
}
Log::addDebug("Updated Records : " . $updated);
return $updated;
}
private function doReplaceQuery($base_url, $search_urls, $replace_urls)
{
global $wpdb;
/* Search and replace in WP_POSTS */
// Removed $wpdb->remove_placeholder_escape from here, not compatible with WP 4.8
$posts_sql = $wpdb->prepare(
"SELECT ID, post_content FROM $wpdb->posts WHERE post_status in ('publish', 'future', 'draft', 'pending', 'private')
AND post_content LIKE %s",
'%' . $base_url . '%');
$rs = $wpdb->get_results( $posts_sql, ARRAY_A );
$number_of_updates = 0;
if ( ! empty( $rs ) ) {
foreach ( $rs AS $rows ) {
$number_of_updates = $number_of_updates + 1;
// replace old URLs with new URLs.
$post_content = $rows["post_content"];
$post_id = $rows['ID'];
$replaced_content = $this->replaceContent($post_content, $search_urls, $replace_urls, false, true);
if ($replaced_content !== $post_content)
{
// $result = wp_update_post($post_ar);
$sql = 'UPDATE ' . $wpdb->posts . ' SET post_content = %s WHERE ID = %d';
$sql = $wpdb->prepare($sql, $replaced_content, $post_id);
$result = $wpdb->query($sql);
if ($result === false)
{
Notice::addError('Something went wrong while replacing' . $result->get_error_message() );
Log::addError('WP-Error during post update', $result);
}
}
}
}
$number_of_updates += $this->handleMetaData($base_url, $search_urls, $replace_urls);
return $number_of_updates;
}
private function handleMetaData($url, $search_urls, $replace_urls)
{
global $wpdb;
$meta_options = apply_filters('shortpixel/replacer/metadata_tables', array('post', 'comment', 'term', 'user'));
$number_of_updates = 0;
foreach($meta_options as $type)
{
switch($type)
{
case "post": // special case.
$sql = 'SELECT meta_id as id, meta_key, meta_value FROM ' . $wpdb->postmeta . '
WHERE post_id in (SELECT ID from '. $wpdb->posts . ' where post_status in ("publish", "future", "draft", "pending", "private") ) AND meta_value like %s';
$type = 'post';
$update_sql = ' UPDATE ' . $wpdb->postmeta . ' SET meta_value = %s WHERE meta_id = %d';
break;
default:
$table = $wpdb->{$type . 'meta'}; // termmeta, commentmeta etc
$meta_id = 'meta_id';
if ($type == 'user')
$meta_id = 'umeta_id';
$sql = 'SELECT ' . $meta_id . ' as id, meta_value FROM ' . $table . '
WHERE meta_value like %s';
$update_sql = " UPDATE $table set meta_value = %s WHERE $meta_id = %d ";
break;
}
$sql = $wpdb->prepare($sql, '%' . $url . '%');
// This is a desparate solution. Can't find anyway for wpdb->prepare not the add extra slashes to the query, which messes up the query.
// $postmeta_sql = str_replace('[JSON_URL]', $json_url, $postmeta_sql);
$rsmeta = $wpdb->get_results($sql, ARRAY_A);
if (! empty($rsmeta))
{
foreach ($rsmeta as $row)
{
$number_of_updates++;
$content = $row['meta_value'];
$id = $row['id'];
$content = $this->replaceContent($content, $search_urls, $replace_urls); //str_replace($search_urls, $replace_urls, $content);
$prepared_sql = $wpdb->prepare($update_sql, $content, $id);
Log::addDebug('Update Meta SQl' . $prepared_sql);
$result = $wpdb->query($prepared_sql);
}
}
} // foreach
return $number_of_updates;
} // function
/**
* Replaces Content across several levels of possible data
* @param $content String The Content to replace
* @param $search String Search string
* @param $replace String Replacement String
* @param $in_deep Boolean. This is use to prevent serialization of sublevels. Only pass back serialized from top.
* @param $strict_check Boolean . If true, remove all classes from serialization check and fail. This should be done on post_content, not on metadata.
*/
private function replaceContent($content, $search, $replace, $in_deep = false, $strict_check = false)
{
//$is_serial = false;
if ( true === is_serialized($content))
{
$serialized_content = $content; // use to return content back if incomplete classes are found, prevent destroying the original information
if (true === $strict_check)
{
$args = array('allowed_classes' => false);
}
else
{
$args = array('allowed_classes' => true);
}
$content = Unserialize::unserialize($content, $args);
// bail directly on incomplete classes. In < PHP 7.2 is_object is false on incomplete objects!
if (true === $this->checkIncomplete($content))
{
return $serialized_content;
}
}
$isJson = $this->isJSON($content);
if ($isJson)
{
$content = json_decode($content);
Log::addDebug('JSon Content', $content);
}
if (is_string($content)) // let's check the normal one first.
{
$content = apply_filters('shortpixel/replacer/content', $content, $search, $replace);
$content = str_replace($search, $replace, $content);
}
elseif (is_wp_error($content)) // seen this.
{
//return $content; // do nothing.
}
elseif (is_array($content) ) // array metadata and such.
{
foreach($content as $index => $value)
{
$content[$index] = $this->replaceContent($value, $search, $replace, true); //str_replace($value, $search, $replace);
if (is_string($index)) // If the key is the URL (sigh)
{
$index_replaced = $this->replaceContent($index, $search,$replace, true);
if ($index_replaced !== $index)
$content = $this->change_key($content, array($index => $index_replaced));
}
}
}
elseif(is_object($content)) // metadata objects, they exist.
{
// bail directly on incomplete classes.
if (true === $this->checkIncomplete($content))
{
// if it was serialized, return the original as not to corrupt data.
if (isset($serialized_content))
{
return $serialized_content;
}
else { // else just return the content.
return $content;
}
}
foreach($content as $key => $value)
{
$content->{$key} = $this->replaceContent($value, $search, $replace, true); //str_replace($value, $search, $replace);
}
}
if ($isJson && $in_deep === false) // convert back to JSON, if this was JSON. Different than serialize which does WP automatically.
{
Log::addDebug('Value was found to be JSON, encoding');
// wp-slash -> WP does stripslashes_deep which destroys JSON
$content = json_encode($content, JSON_UNESCAPED_SLASHES);
Log::addDebug('Content returning', array($content));
}
elseif($in_deep === false && (is_array($content) || is_object($content)))
$content = maybe_serialize($content);
return $content;
}
private function change_key($arr, $set) {
if (is_array($arr) && is_array($set)) {
$newArr = array();
foreach ($arr as $k => $v) {
$key = array_key_exists( $k, $set) ? $set[$k] : $k;
$newArr[$key] = is_array($v) ? $this->change_key($v, $set) : $v;
}
return $newArr;
}
return $arr;
}
private function getRelativeURLS()
{
$dataArray = array(
'source' => array('url' => $this->source_url, 'metadata' => $this->getFilesFromMetadata($this->source_metadata) ),
'target' => array('url' => $this->target_url, 'metadata' => $this->getFilesFromMetadata($this->target_metadata) ),
);
// Log::addDebug('Source Metadata', $this->source_metadata);
// Log::addDebug('Target Metadata', $this->target_metadata);
$result = array();
foreach($dataArray as $index => $item)
{
$result[$index] = array();
$metadata = $item['metadata'];
$baseurl = parse_url($item['url'], PHP_URL_PATH);
$result[$index]['base'] = $baseurl; // this is the relpath of the mainfile.
$baseurl = trailingslashit(str_replace( wp_basename($item['url']), '', $baseurl)); // get the relpath of main file.
foreach($metadata as $name => $filename)
{
$result[$index][$name] = $baseurl . wp_basename($filename); // filename can have a path like 19/08 etc.
}
}
// Log::addDebug('Relative URLS', $result);
return $result;
}
private function getFilesFromMetadata($meta)
{
$fileArray = array();
if (isset($meta['file']))
$fileArray['file'] = $meta['file'];
if (isset($meta['sizes']))
{
foreach($meta['sizes'] as $name => $data)
{
if (isset($data['file']))
{
$fileArray[$name] = $data['file'];
}
}
}
return $fileArray;
}
/** FindNearestsize
* This works on the assumption that when the exact image size name is not available, find the nearest width with the smallest possible difference to impact the site the least.
*/
private function findNearestSize($sizeName)
{
if (! isset($this->source_metadata['sizes'][$sizeName]) || ! isset($this->target_metadata['width'])) // This can happen with non-image files like PDF.
{
// Check if metadata-less item is a svg file. Just the main file to replace all thumbnails since SVG's don't need thumbnails.
if (strpos($this->target_url, '.svg') !== false)
{
$svg_file = wp_basename($this->target_url);
return $svg_file; // this is the relpath of the mainfile.
}
return false;
}
$old_width = $this->source_metadata['sizes'][$sizeName]['width']; // the width from size not in new image
$new_width = $this->target_metadata['width']; // default check - the width of the main image
$diff = abs($old_width - $new_width);
// $closest_file = str_replace($this->relPath, '', $this->newMeta['file']);
$closest_file = wp_basename($this->target_metadata['file']); // mainfile as default
foreach($this->target_metadata['sizes'] as $sizeName => $data)
{
$thisdiff = abs($old_width - $data['width']);
if ( $thisdiff < $diff )
{
$closest_file = $data['file'];
if(is_array($closest_file)) { $closest_file = $closest_file[0];} // HelpScout case 709692915
if(!empty($closest_file)) {
$diff = $thisdiff;
$found_metasize = true;
}
}
}
if(empty($closest_file)) return false;
return $closest_file;
}
/* Check if given content is JSON format. */
private function isJSON($content)
{
if (is_array($content) || is_object($content) || is_null($content))
return false; // can never be.
$json = json_decode($content);
return $json && $json != $content;
}
private function checkIncomplete($var)
{
return ($var instanceof \__PHP_Incomplete_Class);
}
} // class