-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathConfigDbStorage.php
559 lines (500 loc) · 14.7 KB
/
ConfigDbStorage.php
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<?php
/**
* File: ConfigCompiler.php
*
* @package W3TC
*/
namespace W3TC;
/**
* Class ConfigDbStorage
*
* Provides configuration data using cache
*
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
* phpcs:disable WordPress.DB.DirectDatabaseQuery
* phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
* phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log
*/
class ConfigDbStorage {
/**
* Retrieves an array configuration from storage.
*
* @param int $blog_id Blog ID to retrieve the configuration for.
* @param bool $preview Whether to load the preview configuration.
*
* @return array|null Array of configuration settings or null if none exist.
*/
public static function util_array_from_storage( $blog_id, $preview ) {
$content = self::load_content( $blog_id, $preview );
$config = @json_decode( $content, true );
if ( is_array( $config ) ) {
return $config;
}
return null;
}
/**
* Checks if a configuration item exists in storage.
*
* @param int $blog_id Blog ID to check.
* @param bool $preview Whether to check the preview configuration.
*
* @return bool True if the item exists, false otherwise.
*/
public static function is_item_exists( $blog_id, $preview ) {
$content = self::load_content( $blog_id, $preview );
return is_null( $content );
}
/**
* Removes a configuration item from storage.
*
* @param int $blog_id Blog ID of the item to remove.
* @param bool $preview Whether to remove the preview configuration.
*
* @return void
*/
public static function remove_item( $blog_id, $preview ) {
$table = self::get_table( $blog_id );
$option_name = self::get_option_name( $blog_id, $preview );
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"DELETE FROM $table WHERE option_name = %s",
$option_name
)
);
}
/**
* Copies the configuration between production and preview environments.
*
* @param int $blog_id Blog ID to copy the configuration for.
* @param int $direction Copy direction: >0 for preview to production, <=0 for production to preview.
*
* @return void
*/
public static function preview_production_copy( $blog_id, $direction ) {
if ( $direction > 0 ) {
$content = self::load_content( $blog_id, true );
self::save_item( $blog_id, false, $content );
} else {
$content = self::load_content( $blog_id, false );
self::save_item( $blog_id, true, $content );
}
}
/**
* Saves a configuration item to storage.
*
* @param int $blog_id Blog ID to save the configuration for.
* @param bool $preview Whether to save as a preview configuration.
* @param string|array $data Configuration data to save, either as a string or an array.
*
* @return void
*/
public static function save_item( $blog_id, $preview, $data ) {
if ( is_string( $data ) ) {
$config = $data;
} else {
$config = wp_json_encode( $data );
}
$table = self::get_table( $blog_id );
$option_name = self::get_option_name( $blog_id, $preview );
global $wpdb;
$is_exists = ! is_null( self::load_content( $blog_id, $preview ) );
if ( $is_exists ) {
$wpdb->query(
$wpdb->prepare(
"UPDATE $table SET option_value = %s WHERE option_name = %s",
$config,
$option_name
)
);
} else {
$wpdb->query(
$wpdb->prepare(
"INSERT INTO $table (option_name, option_value) VALUES (%s, %s)",
$option_name,
$config
)
);
}
}
/**
* Retrieves the database table name for storing configuration.
*
* @param int $blog_id Blog ID to retrieve the table for.
*
* @return string Database table name.
*/
private static function get_table( $blog_id ) {
if ( defined( 'W3TC_CONFIG_DATABASE_TABLE' ) ) {
$template = W3TC_CONFIG_DATABASE_TABLE;
} else {
if ( is_multisite() ) {
error_log( 'Please use W3TC_CONFIG_DATABASE_TABLE constant, funcationality without it is not stable in multisite mode' );
}
global $table_prefix;
$template = $table_prefix . 'options';
}
if ( $blog_id <= 0 ) {
$blog_id_prefix = '';
} else {
$blog_id_prefix = $blog_id . '_';
}
return str_replace( '{blog_id_prefix}', $blog_id_prefix, $template );
}
/**
* Constructs the option name for a configuration item.
*
* @param int $blog_id Blog ID for the configuration.
* @param bool $preview Whether to generate the name for a preview configuration.
*
* @return string Option name for the configuration.
*/
private static function get_option_name( $blog_id, $preview ) {
return 'w3tc_config_' . $blog_id . ( $preview ? '_preview' : '' );
}
/**
* Loads the configuration content from storage.
*
* @param int $blog_id Blog ID to load the configuration for.
* @param bool $preview Whether to load the preview configuration.
*
* @return string|null Configuration content as a JSON-encoded string, or null if none exists.
*/
private static function load_content( $blog_id, $preview ) {
$table = self::get_table( $blog_id );
$option_name = self::get_option_name( $blog_id, $preview );
if ( isset( $GLOBALS['wpdb'] ) ) {
global $wpdb;
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT option_value FROM $table WHERE option_name = %s LIMIT 1",
$option_name
)
);
} else {
$db = new _WpdbEssentials( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
if ( $db->ready ) {
$row = $db->get_row(
$db->prepare(
"SELECT option_value FROM $table WHERE option_name = %s LIMIT 1",
$option_name
)
);
} else {
error_log( 'Failed to load w3tc config' );
$row = null;
}
// close connection immediately so that real pooled connection may be reused by later inialized wpdb object.
$db->close();
}
if ( is_object( $row ) ) {
return $row->option_value;
}
return null;
}
}
/**
* Class _WpdbEssentials
*
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
* phpcs:disable PEAR.NamingConventions.ValidClassName.StartWithCapital
* phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
* phpcs:disable WordPress.DB.RestrictedFunctions
* phpcs:disable WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
*/
class _WpdbEssentials {
/**
* Last error
*
* @var string
*/
public $last_error = '';
/**
* Number of rows
*
* @var integer
*/
public $num_rows = 0;
/**
* Number of rows affected
*
* @var integer
*/
public $rows_affected = 0;
/**
* Last query
*
* @var string
*/
public $last_query;
/**
* Last result
*
* @var array
*/
public $last_result;
/**
* Initializes the database connection.
*
* @param string $dbuser The database username.
* @param string $dbpassword The database password.
* @param string $dbname The name of the database.
* @param string $dbhost The hostname of the database.
*
* @return void
*/
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
if ( function_exists( 'mysqli_connect' ) ) {
if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
$this->use_mysqli = ! WP_USE_EXT_MYSQL;
} elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
$this->use_mysqli = true;
} elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
$this->use_mysqli = true;
}
}
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
$this->db_connect();
}
/**
* Establishes a connection to the database.
*
* @param bool $allow_bail Whether to allow bail on connection failure.
*
* @return void
*/
public function db_connect( $allow_bail = true ) {
$this->is_mysql = true;
/*
* Deprecated in 3.9+ when using MySQLi. No equivalent
* $new_link parameter exists for mysqli_* functions.
*/
$new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
$client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
if ( $this->use_mysqli ) {
$this->dbh = mysqli_init();
// mysqli_real_connect doesn't support the host param including a port or socket
// like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
$port = null;
$socket = null;
$host = $this->dbhost;
$port_or_socket = strstr( $host, ':' );
if ( ! empty( $port_or_socket ) ) {
$host = substr( $host, 0, strpos( $host, ':' ) );
$port_or_socket = substr( $port_or_socket, 1 );
if ( 0 !== strpos( $port_or_socket, '/' ) ) {
$port = intval( $port_or_socket );
$maybe_socket = strstr( $port_or_socket, ':' );
if ( ! empty( $maybe_socket ) ) {
$socket = substr( $maybe_socket, 1 );
}
} else {
$socket = $port_or_socket;
}
}
if ( WP_DEBUG ) {
mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
} else {
@mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
}
if ( $this->dbh->connect_errno ) {
$this->dbh = null;
$this->last_error = 'Connection failed with ' . $this->dbh->connect_errno . ' error code';
if ( WP_DEBUG ) {
echo esc_html( $this->last_error );
}
}
} else {
if ( WP_DEBUG ) {
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}
}
if ( $this->dbh ) {
$this->has_connected = true;
$this->ready = true;
$this->select( $this->dbname, $this->dbh );
} else {
if ( WP_DEBUG ) {
esc_html_e( 'Failed to connect to mysql server', 'w3-total-cache' );
}
}
}
/**
* Selects a database to use for the connection.
*
* @param string $db The name of the database to select.
* @param resource $dbh Optional. The database connection resource. Defaults to the current connection.
*
* @return void
*/
public function select( $db, $dbh = null ) {
if ( $this->use_mysqli ) {
$success = mysqli_select_db( $dbh, $db );
} else {
$success = mysql_select_db( $db, $dbh );
}
if ( ! $success ) {
$this->ready = false;
if ( WP_DEBUG ) {
esc_html_e( 'Failed to select database', 'w3-total-cache' );
}
}
}
/**
* Prepares a database query string with safe and escaped placeholders.
*
* @param string $query The SQL query with placeholders.
* @param mixed $args Arguments to substitute into the query.
*
* @return string The prepared SQL query.
*/
public function prepare( $query, $args ) {
$args = func_get_args();
array_shift( $args );
// If args were passed as an array (as in vsprintf), move them up.
if ( isset( $args[0] ) && is_array( $args[0] ) ) {
$args = $args[0];
}
$query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it.
$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting.
$query = preg_replace( '|(?<!%)%f|', '%F', $query ); // Force floats to be locale unaware.
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s.
array_walk( $args, array( $this, 'escape_by_ref' ) );
return @vsprintf( $query, $args );
}
/**
* Escapes a string by reference for safe usage in queries.
*
* @param string $string The string to be escaped.
*
* @return void
*/
public function escape_by_ref( &$string ) {
if ( ! is_float( $string ) ) {
$string = $this->_real_escape( $string );
}
}
/**
* Escapes a string using the active database connection.
*
* @param string $string The string to be escaped.
*
* @return string The escaped string.
*/
private function _real_escape( $string ) {
if ( $this->use_mysqli ) {
return mysqli_real_escape_string( $this->dbh, $string );
} else {
return mysql_real_escape_string( $string, $this->dbh );
}
}
/**
* Retrieves a single row from the query result set.
*
* @param string|null $query Optional. SQL query to execute. If null, retrieves from the last query result.
*
* @return object|null The first row from the result set or null if no rows exist.
*/
public function get_row( $query = null ) {
$y = 0;
if ( $query ) {
$this->query( $query );
} else {
return null;
}
if ( ! isset( $this->last_result[ $y ] ) ) {
return null;
}
return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
}
/**
* Executes a database query.
*
* @param string $query The SQL query to execute.
*
* @return int|false The number of rows affected or retrieved by the query, or false on error.
*/
public function query( $query ) {
if ( ! $this->ready ) {
return false;
}
$this->_do_query( $query );
// If there is an error then take note of it.
if ( $this->use_mysqli ) {
if ( $this->dbh instanceof \mysqli ) {
$this->last_error = mysqli_error( $this->dbh );
} else {
$this->last_error = 'query: Unable to retrieve the error message from MySQL';
}
} else {
if ( is_resource( $this->dbh ) ) {
$this->last_error = mysql_error( $this->dbh );
} else {
$this->last_error = 'query: Unable to retrieve the error message from MySQL';
}
}
if ( $this->last_error ) {
if ( WP_DEBUG ) {
echo esc_html( $this->last_error );
}
return false;
}
$num_rows = 0;
$this->last_result = array();
if ( $this->use_mysqli && $this->result instanceof \mysqli_result ) {
while ( $row = mysqli_fetch_object( $this->result ) ) {
$this->last_result[ $num_rows ] = $row;
$num_rows++;
}
} elseif ( is_resource( $this->result ) ) {
while ( $row = mysql_fetch_object( $this->result ) ) {
$this->last_result[ $num_rows ] = $row;
$num_rows++;
}
}
// Log number of rows the query returned and return number of rows selected.
$this->num_rows = $num_rows;
$return_val = $num_rows;
return $return_val;
}
/**
* Executes the database query internally.
*
* @param string $query The SQL query to execute.
*
* @return void
*/
private function _do_query( $query ) {
if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
$this->result = mysqli_query( $this->dbh, $query );
} elseif ( ! empty( $this->dbh ) ) {
$this->result = mysql_query( $query, $this->dbh );
}
}
/**
* Closes the current database connection.
*
* @return bool True if the connection was successfully closed, false otherwise.
*/
public function close() {
if ( ! $this->dbh ) {
return false;
}
if ( $this->use_mysqli ) {
$closed = mysqli_close( $this->dbh );
} else {
$closed = mysql_close( $this->dbh );
}
if ( $closed ) {
$this->dbh = null;
$this->ready = false;
$this->has_connected = false;
}
return $closed;
}
}