This repository has been archived by the owner on Jul 3, 2022. It is now read-only.
forked from szepeviktor/w3-total-cache-fixed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbCache.php
657 lines (565 loc) · 18.6 KB
/
DbCache.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<?php
// To support legacy updates with old add-ins
if (class_exists('W3_DbCache'))
return;
w3_require_once(W3TC_LIB_W3_DIR . '/Db.php');
/**
* Class W3_DbCache
*/
class W3_DbCache extends W3_DbProcessor {
/**
* Array of queries
*
* @var array
*/
var $query_stats = array();
/**
* Queries total
*
* @var integer
*/
var $query_total = 0;
/**
* Query cache hits
*
* @var integer
*/
var $query_hits = 0;
/**
* Query cache misses
*
* @var integer
*/
var $query_misses = 0;
/**
* Time total
*
* @var integer
*/
var $time_total = 0;
/**
* Config
*
* @var W3_Config
*/
var $_config = null;
/**
* Lifetime
*
* @var integer
*/
var $_lifetime = null;
/**
* Request-global cache reject reason
* null until filled
*
* @var string
*/
private $cache_reject_reason = null;
/**
* Request-global check reject scope
* false until set
* @var bool
*/
private $cache_reject_request_wide = false;
/**
* Result of check if caching is possible at the level of current http request
* null until filled
*
* @var boolean
*/
var $_can_cache_once_per_request_result = null;
/*
* @param string $dbuser
* @param string $dbpassword
* @param string $dbname
* @param string $dbhost
*/
function __construct() {
$this->_config = w3_instance('W3_Config');
$this->_lifetime = $this->_config->get_integer('dbcache.lifetime');
}
/**
* Executes query
*
* @param string $query
* @return integer
*/
function query($query) {
if (!$this->manager->ready) {
return $this->underlying_manager->query($query);
}
$reason = '';
$cached = false;
$data = false;
$time_total = 0;
$this->query_total++;
$caching = $this->_can_cache($query, $reason);
if (preg_match('~^\s*insert\b|^\s*delete\b|^\s*update\b|^\s*replace\b~is', $query)) {
$group = $this->_get_group($query);
$this->_flush_cache_group($group);
}
if ($caching) {
$this->manager->timer_start();
//$cache_key = $this->_get_cache_key($query);
$cache = $this->_get_cache();
$group = $this->_get_group($query);
$data = $cache->get(md5($query), $group);
$time_total = $this->manager->timer_stop();
}
if (is_array($data)) {
$cached = true;
$this->query_hits++;
$this->manager->last_error = $data['last_error'];
$this->manager->last_query = $data['last_query'];
$this->manager->last_result = $data['last_result'];
$this->manager->col_info = $data['col_info'];
$this->manager->num_rows = $data['num_rows'];
$return_val = $data['return_val'];
} else {
$this->query_misses++;
$this->manager->timer_start();
$return_val = $this->underlying_manager->query($query);
$time_total = $this->manager->timer_stop();
if ($caching) {
$data = array(
'last_error' => $this->manager->last_error,
'last_query' => $this->manager->last_query,
'last_result' => $this->manager->last_result,
'col_info' => $this->manager->col_info,
'num_rows' => $this->manager->num_rows,
'return_val' => $return_val
);
$cache = $this->_get_cache();
$group = $this->_get_group($query);
$cache->set(md5($query), $data, $this->_lifetime, $group);
}
}
if ($this->_config->get_boolean('dbcache.debug')) {
$this->query_stats[] = array(
'query' => $query,
'caching' => $caching,
'reason' => $reason,
'cached' => $cached,
'data_size' => ($data ? strlen(serialize($data)) : 0),
'time_total' => $time_total
);
}
$this->time_total += $time_total;
return $return_val;
}
/**
* Initializes object, calls underlying processor
*/
function initialize() {
return $this->underlying_manager->initialize();
}
/**
* Insert a row into a table.
*
* @param string $table
* @param array $data
* @param array|string $format
* @return int|false
*/
function insert($table, $data, $format = null) {
return $this->underlying_manager->insert($table, $data, $format);
}
/**
* Replace a row into a table.
*
* @param string $table
* @param array $data
* @param array|string $format
* @return int|false
*/
function replace($table, $data, $format = null) {
return $this->underlying_manager->replace($table, $data, $format);
}
/**
* Update a row in the table
*
* @param string $table
* @param array $data
* @param array $where
* @param array|string $format
* @param array|string $format_where
* @return int|false
*/
function update($table, $data, $where, $format = null, $where_format = null) {
$group = $this->_get_group($table);
$this->_flush_cache_group($group);
return $this->underlying_manager->update($table, $data, $where, $format, $where_format);
}
/**
* Flushes cache
*
* @return boolean
*/
function flush_cache() {
$this->_flush_cache_group('all');
return true;
}
private function _flush_cache_group($group) {
$cache = $this->_get_cache();
$flush_groups = $this->_get_flush_groups($group);
foreach($flush_groups as $f_group) {
$cache->flush($f_group);
}
}
/**
* Returns cache object
*
* @return W3_Cache_Base
*/
function _get_cache() {
static $cache = array();
if (!isset($cache[0])) {
$engine = $this->_config->get_string('dbcache.engine');
switch ($engine) {
case 'memcached':
$engineConfig = array(
'servers' => $this->_config->get_array('dbcache.memcached.servers'),
'persistant' => $this->_config->get_boolean('dbcache.memcached.persistant')
);
break;
case 'redis':
$engineConfig = array(
'server' => $this->_config->get_string('dbcache.redis.server'),
'db' => $this->_config->get_integer('dbcache.redis.db'),
'persistant' => $this->_config->get_boolean('dbcache.redis.persistant')
);
break;
case 'file':
$engineConfig = array(
'use_wp_hash', true,
'section' => 'db',
'locking' => $this->_config->get_boolean('dbcache.file.locking'),
'flush_timelimit' => $this->_config->get_integer('timelimit.cache_flush')
);
break;
default:
$engineConfig = array();
}
$engineConfig['module'] = 'dbcache';
$engineConfig['host'] = w3_get_host();
$engineConfig['instance_id'] = w3_get_instance_id();
w3_require_once(W3TC_LIB_W3_DIR . '/Cache.php');
$cache[0] = W3_Cache::instance($engine, $engineConfig);
}
return $cache[0];
}
/**
* Check if can cache sql
*
* @param string $sql
* @param string $cache_reject_reason
* @return boolean
*/
function _can_cache($sql, &$cache_reject_reason) {
/**
* Skip if request-wide reject reason specified.
* Note - as a result requedt-wide checks are done only once per request
*/
if (!is_null($this->cache_reject_reason)) {
$this->cache_reject_request_wide = true;
return false;
}
/**
* Do once-per-request check if needed
*/
if (is_null($this->_can_cache_once_per_request_result)) {
$this->_can_cache_once_per_request_result = $this->_can_cache_once_per_request();
if (!$this->_can_cache_once_per_request_result) {
$this->cache_reject_request_wide = true;
return false;
}
}
/**
* Check for DONOTCACHEDB constant
*/
if (defined('DONOTCACHEDB') && DONOTCACHEDB) {
$this->cache_reject_reason = 'DONOTCACHEDB';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
/**
* Skip if doint AJAX
*/
if (defined('DOING_AJAX')) {
$this->cache_reject_reason = 'DOING_AJAX';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
/**
* Skip if doing cron
*/
if (defined('DOING_CRON')) {
$this->cache_reject_reason = 'DOING_CRON';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
/**
* Skip if APP request
*/
if (defined('APP_REQUEST')) {
$this->cache_reject_reason = 'APP_REQUEST';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
/**
* Skip if XMLRPC request
*/
if (defined('XMLRPC_REQUEST')) {
$this->cache_reject_reason = 'XMLRPC_REQUEST';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
/**
* Skip if admin
*/
if (defined('WP_ADMIN')) {
$this->cache_reject_reason = 'WP_ADMIN';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
/**
* Check for WPMU's and WP's 3.0 short init
*/
if (defined('SHORTINIT') && SHORTINIT) {
$cache_reject_reason = 'SHORTINIT';
return false;
}
/**
* Skip if SQL is rejected
*/
if (!$this->_check_sql($sql)) {
$cache_reject_reason = 'query';
return false;
}
/**
* Skip if user is logged in
*/
if ($this->_config->get_boolean('dbcache.reject.logged') && !$this->_check_logged_in()) {
$this->cache_reject_reason = 'user.logged_in';
$cache_reject_reason = $this->cache_reject_reason;
return false;
}
return true;
}
/**
* Check if can cache sql, checks which have constant results during whole request
*
* @return boolean
*/
function _can_cache_once_per_request() {
/**
* Skip if disabled
*/
if (!$this->_config->get_boolean('dbcache.enabled')) {
$this->cache_reject_reason = 'dbcache.disabled';
return false;
}
/**
* Skip if request URI is rejected
*/
if (!$this->_check_request_uri()) {
$this->cache_reject_reason = 'request';
return false;
}
/**
* Skip if cookie is rejected
*/
if (!$this->_check_cookies()) {
$this->cache_reject_reason = 'cookie';
return false;
}
return true;
}
/**
* Check SQL
*
* @param string $sql
* @return boolean
*/
function _check_sql($sql) {
$auto_reject_strings = $this->_config->get_array('dbcache.reject.words');
if (preg_match('~' . implode('|', $auto_reject_strings) . '~is', $sql)) {
return false;
}
$reject_sql = $this->_config->get_array('dbcache.reject.sql');
foreach ($reject_sql as $expr) {
$expr = trim($expr);
$expr = str_replace('{prefix}', $this->manager->prefix, $expr);
if ($expr != '' && preg_match('~' . $expr . '~i', $sql)) {
return false;
}
}
return true;
}
/**
* Check request URI
*
* @return boolean
*/
function _check_request_uri() {
$auto_reject_uri = array(
'wp-login',
'wp-register'
);
foreach ($auto_reject_uri as $uri) {
if (strstr($_SERVER['REQUEST_URI'], $uri) !== false) {
return false;
}
}
$reject_uri = $this->_config->get_array('dbcache.reject.uri');
$reject_uri = array_map('w3_parse_path', $reject_uri);
foreach ($reject_uri as $expr) {
$expr = trim($expr);
if ($expr != '' && preg_match('~' . $expr . '~i', $_SERVER['REQUEST_URI'])) {
return false;
}
}
return true;
}
/**
* Checks for WordPress cookies
*
* @return boolean
*/
function _check_cookies() {
foreach (array_keys($_COOKIE) as $cookie_name) {
if ($cookie_name == 'wordpress_test_cookie') {
continue;
}
if (preg_match('/^wp-postpass|^comment_author/', $cookie_name)) {
return false;
}
}
foreach ($this->_config->get_array('dbcache.reject.cookie') as $reject_cookie) {
foreach (array_keys($_COOKIE) as $cookie_name) {
if (strstr($cookie_name, $reject_cookie) !== false) {
return false;
}
}
}
return true;
}
/**
* Check if user is logged in
*
* @return boolean
*/
function _check_logged_in() {
foreach (array_keys($_COOKIE) as $cookie_name) {
if (strpos($cookie_name, 'wordpress_logged_in') === 0)
return false;
}
return true;
}
/**
* Returns debug info
*
* @return string
*/
function _get_debug_info() {
$debug_info = "<!-- W3 Total Cache: Db cache debug info:\r\n";
$debug_info .= sprintf("%s%s\r\n", str_pad('Engine: ', 20), w3_get_engine_name($this->_config->get_string('dbcache.engine')));
$debug_info .= sprintf("%s%d\r\n", str_pad('Total queries: ', 20), $this->query_total);
$debug_info .= sprintf("%s%d\r\n", str_pad('Cached queries: ', 20), $this->query_hits);
$debug_info .= sprintf("%s%.4f\r\n", str_pad('Total query time: ', 20), $this->time_total);
if (count($this->query_stats)) {
$debug_info .= "SQL info:\r\n";
$debug_info .= sprintf("%s | %s | %s | % s | %s | %s\r\n",
str_pad('#', 5, ' ', STR_PAD_LEFT), str_pad('Time (s)', 8, ' ', STR_PAD_LEFT),
str_pad('Caching (Reject reason)', 30, ' ', STR_PAD_BOTH),
str_pad('Status', 10, ' ', STR_PAD_BOTH),
str_pad('Data size (b)', 13, ' ', STR_PAD_LEFT),
'Query');
foreach ($this->query_stats as $index => $query) {
$debug_info .= sprintf("%s | %s | %s | %s | %s | %s\r\n",
str_pad($index + 1, 5, ' ', STR_PAD_LEFT),
str_pad(round($query['time_total'], 4), 8, ' ', STR_PAD_LEFT),
str_pad(($query['caching'] ? 'enabled'
: sprintf('disabled (%s)', $query['reason'])), 30, ' ', STR_PAD_BOTH),
str_pad(($query['cached'] ? 'cached' : 'not cached'), 10, ' ', STR_PAD_BOTH),
str_pad($query['data_size'], 13, ' ', STR_PAD_LEFT),
w3_escape_comment(trim($query['query'])));
}
}
$debug_info .= '-->';
return $debug_info;
}
private function _get_group($sql) {
$sql = strtolower($sql);
$matched = array();
$options = false. $comments = false;
$prefix = $this->manager->prefix;
$options = preg_match('~' . $prefix . 'options~i', $sql);
$comments = preg_match('~' . $prefix . '(comments|commentsmeta)~i', $sql);
if ($options && $comments)
return 'options_comments';
if ($options)
return 'options';
if ($comments)
return 'comments';
return 'all';
}
private function _get_flush_groups($group) {
switch($group) {
case 'all':
return array('all', 'options_comments', 'options', 'comments');
case 'options_comments':
return array('options_comments', 'options', 'comments');
case 'options':
case 'comments':
return array('options_comments', $group);
break;
default:
return array($group);
}
}
public function get_reject_reason() {
if (is_null($this->cache_reject_reason))
return '';
$request_wide_string = $this->cache_reject_request_wide ?
(function_exists('__') ? __('Request-wide', 'w3-total-cache').' ' : 'Request ') : '';
return $request_wide_string . $this->_get_reject_reason_message($this->cache_reject_reason);
}
/**
* @param $key
* @return string|void
*/
private function _get_reject_reason_message($key) {
if (!function_exists('__'))
return $key;
switch ($key) {
case 'dbcache.disabled':
return __('Database caching is disabled', 'w3-total-cache');
case 'DONOTCACHEDB':
return __('DONOTCACHEDB constant is defined', 'w3-total-cache');
case 'DOING_AJAX':
return __('Doing AJAX', 'w3-total-cache');
case 'request':
return __('Request URI is rejected', 'w3-total-cache');
case 'cookie':
return __('Cookie is rejected', 'w3-total-cache');
case 'DOING_CRONG':
return __('Doing cron', 'w3-total-cache');
case 'APP_REQUEST':
return __('Application request', 'w3-total-cache');
case 'XMLRPC_REQUEST':
return __('XMLRPC request', 'w3-total-cache');
case 'WP_ADMIN':
return __('wp-admin', 'w3-total-cache');
case 'SHORTINIT':
return __('Short init', 'w3-total-cache');
case 'query':
return __('Query is rejected', 'w3-total-cache');
case 'user.logged_in':
return __('User is logged in', 'w3-total-cache');
default:
return $key;
}
}
}