-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathSearchReplacer.php
More file actions
299 lines (259 loc) · 9.12 KB
/
SearchReplacer.php
File metadata and controls
299 lines (259 loc) · 9.12 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
<?php
namespace WP_CLI;
use ArrayObject;
use Exception;
class SearchReplacer {
/**
* @var string
*/
private $from;
/**
* @var string
*/
private $to;
/**
* @var string
*/
private $from_json;
/**
* @var string
*/
private $to_json;
/**
* @var bool
*/
private $recurse_objects;
/**
* @var bool
*/
private $regex;
/**
* @var string
*/
private $regex_flags;
/**
* @var string
*/
private $regex_delimiter;
/**
* @var int
*/
private $regex_limit;
/**
* @var bool
*/
private $logging;
/**
* @var string[]
*/
private $log_data = [];
/**
* @var int
*/
private $max_recursion;
/**
* @var array<string, mixed>
*/
private $unserialize_options;
/**
* @param string $from String we're looking to replace.
* @param string $to What we want it to be replaced with.
* @param bool $recurse_objects Should objects be recursively replaced?
* @param bool $regex Whether `$from` is a regular expression.
* @param string $regex_flags Flags for regular expression.
* @param string $regex_delimiter Delimiter for regular expression.
* @param bool $logging Whether logging.
* @param integer $regex_limit The maximum possible replacements for each pattern in each subject string.
*/
public function __construct( $from, $to, $recurse_objects = false, $regex = false, $regex_flags = '', $regex_delimiter = '/', $logging = false, $regex_limit = -1 ) {
$this->from = $from;
$this->to = $to;
$this->recurse_objects = $recurse_objects;
$this->regex = $regex;
$this->regex_flags = $regex_flags;
$this->regex_delimiter = $regex_delimiter;
$this->regex_limit = $regex_limit;
$this->logging = $logging;
$this->clear_log_data();
// Compute JSON-encoded versions (stripping outer quotes) for handling raw JSON values in the database.
$this->from_json = \Search_Replace_Command::json_encode_strip_quotes( $from );
$this->to_json = \Search_Replace_Command::json_encode_strip_quotes( $to );
// Get the XDebug nesting level. Will be zero (no limit) if no value is set
$this->max_recursion = intval( ini_get( 'xdebug.max_nesting_level' ) );
/**
* Filter the options passed to unserialize() during search-replace.
*
* Defaults to `[ 'allowed_classes' => [ 'stdClass' ] ]` to allow the
* built-in stdClass (used extensively by WordPress, e.g. theme mods)
* while blocking arbitrary user-defined class instantiation. Use this
* hook to allow additional classes when needed.
*
* @param array<string, mixed> $options Options array for unserialize().
*/
$this->unserialize_options = \WP_CLI::do_hook( 'search_replace_unserialize_options', [ 'allowed_classes' => [ 'stdClass' ] ] );
}
/**
* Take a serialised array and unserialise it replacing elements as needed and
* unserialising any subordinate arrays and performing the replace on those too.
* Ignores any serialized objects unless $recurse_objects is set to true.
*
* @param array|string $data The data to operate on.
* @param bool $serialised Does the value of $data need to be unserialized?
*
* @return array The original array with all elements replaced as needed.
*/
public function run( $data, $serialised = false ) {
return $this->run_recursively( $data, $serialised );
}
/**
* @param int $recursion_level Current recursion depth within the original data.
* @param array $visited_data Data that has been seen in previous recursion iterations.
*/
private function run_recursively( $data, $serialised, $recursion_level = 0, $visited_data = array() ) {
// some unseriliased data cannot be re-serialised eg. SimpleXMLElements
try {
if ( $this->recurse_objects ) {
// If we've reached the maximum recursion level, short circuit
if ( 0 !== $this->max_recursion && $recursion_level >= $this->max_recursion ) {
return $data;
}
if ( is_array( $data ) || is_object( $data ) ) {
// If we've seen this exact object or array before, short circuit
if ( in_array( $data, $visited_data, true ) ) {
return $data; // Avoid infinite loops when there's a cycle
}
// Add this data to the list of
$visited_data[] = $data;
}
}
try {
// The error suppression operator is not enough in some cases, so we disable
// reporting of notices and warnings as well.
$error_reporting = error_reporting();
error_reporting( $error_reporting & ~E_NOTICE & ~E_WARNING );
$unserialized = is_string( $data ) ? @unserialize( $data, $this->unserialize_options ) : false;
error_reporting( $error_reporting );
} catch ( \TypeError $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.typeerrorFound
// This type error is thrown when trying to unserialize a string that does not fit the
// type declarations of the properties it is supposed to fill.
// This type checking was introduced with PHP 8.1.
// See https://github.com/wp-cli/search-replace-command/issues/191
\WP_CLI::warning(
sprintf(
'Skipping an inconvertible serialized object: "%s", replacements might not be complete. Reason: %s.',
$data,
$exception->getMessage()
)
);
throw new Exception( $exception->getMessage(), $exception->getCode(), $exception );
}
if ( false !== $unserialized ) {
$data = $this->run_recursively( $unserialized, true, $recursion_level + 1 );
} elseif ( is_array( $data ) ) {
$keys = array_keys( $data );
foreach ( $keys as $key ) {
$data[ $key ] = $this->run_recursively( $data[ $key ], false, $recursion_level + 1, $visited_data );
}
} elseif ( $this->recurse_objects && ( is_object( $data ) || $data instanceof \__PHP_Incomplete_Class ) ) {
if ( $data instanceof \__PHP_Incomplete_Class ) {
$array = new ArrayObject( $data );
\WP_CLI::warning(
sprintf(
'Skipping an uninitialized class "%s", replacements might not be complete.',
$array['__PHP_Incomplete_Class_Name']
)
);
} else {
try {
$is_array_access = $data instanceof \ArrayAccess;
foreach ( $data as $key => $value ) {
$value = $this->run_recursively( $value, false, $recursion_level + 1, $visited_data );
if ( $is_array_access ) {
$data[ $key ] = $value;
} else {
$data->$key = $value;
}
}
} catch ( \Error $exception ) { // phpcs:ignore PHPCompatibility.Classes.NewClasses.errorFound
// This error is thrown when the object that was unserialized cannot be iterated upon.
// The most notable reason is an empty `mysqli_result` object which is then considered to be "already closed".
// See https://github.com/wp-cli/search-replace-command/pull/192#discussion_r1412310179
\WP_CLI::warning(
sprintf(
'Skipping an inconvertible serialized object of type "%s", replacements might not be complete. Reason: %s.',
is_object( $data ) ? get_class( $data ) : gettype( $data ),
$exception->getMessage()
)
);
throw new Exception( $exception->getMessage(), $exception->getCode(), $exception );
}
}
} elseif ( is_string( $data ) ) {
if ( $this->logging ) {
$old_data = $data;
}
if ( $this->regex ) {
$search_regex = $this->regex_delimiter;
$search_regex .= $this->from;
$search_regex .= $this->regex_delimiter;
$search_regex .= $this->regex_flags;
$result = preg_replace( $search_regex, $this->to, $data, $this->regex_limit );
if ( null === $result || PREG_NO_ERROR !== preg_last_error() ) {
\WP_CLI::warning(
sprintf(
'The provided regular expression threw a PCRE error - %s',
$this->preg_error_message( $result )
)
);
}
$data = $result;
} else {
$data = str_replace( $this->from, $this->to, $data );
if ( $this->from_json !== $this->from ) {
$data = str_replace( $this->from_json, $this->to_json, $data );
}
}
if ( $this->logging && $old_data !== $data ) {
$this->log_data[] = $old_data;
}
}
if ( $serialised ) {
return serialize( $data );
}
} catch ( Exception $exception ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Intentionally empty.
}
return $data;
}
/**
* Gets existing data saved for this run when logging.
* @return string[] Array of data strings, prior to replacements.
*/
public function get_log_data() {
return $this->log_data;
}
/**
* Clears data stored for logging.
*/
public function clear_log_data() {
$this->log_data = array();
}
/**
* Get the PCRE error constant name from an error value.
*
* @param integer $error Error code.
* @return string Error constant name.
*/
private function preg_error_message( $error ) {
static $error_names = null;
if ( null === $error_names ) {
$definitions = get_defined_constants( true );
$pcre_constants = array_key_exists( 'pcre', $definitions )
? $definitions['pcre']
: array();
$error_names = array_flip( $pcre_constants );
}
return isset( $error_names[ $error ] )
? $error_names[ $error ]
: '<unknown error>';
}
}