forked from flourishlib/flourish-classes
-
Notifications
You must be signed in to change notification settings - Fork 10
/
fCache.php
743 lines (668 loc) · 20 KB
/
fCache.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
<?php
/**
* A simple interface to cache data using different backends
*
* @copyright Copyright (c) 2009-2012 Will Bond
* @author Will Bond [wb] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fCache
*
*/
class fCache
{
/**
* The cache configuration, used for database, directory and file caches
*
* The array structure for database caches is:
* {{{
* array(
* 'table' => (string) {the database table to use},
* 'key_column' => (string) {the varchar column to store the key in, should be able to handle at least 250 characters},
* 'value_column' => (string) {the text/varchar column to store the value in},
* 'ttl_column' => (string) {the integer column to store the expiration time in}
* )
* }}}
*
* The array structure for directory caches:
* {{{
* array(
* 'path' => (string) {the directory path with trailing slash}
* )
* }}}
*
* The array structure for file caches:
* {{{
* array(
* 'path' => (string) {the file path},
* 'state' => (string) {clean or dirty, used to appropriately save}
* )
* }}}
*
* @var array
*/
protected $config;
/**
* The data store to use
*
* Either the:
* - array structure for file cache
* - Memcache or Memcached object for memcache
* - fDatabase object for database
* - Redis object for redis
*
* Not used for apc, directory or xcache
*
* @var mixed
*/
protected $data_store;
/**
* The type of cache
*
* The valid values are:
* - `'apc'`
* - `'database'`
* - `'directory'`
* - `'file'`
* - `'memcache'`
* - `'redis'`
* - `'xcache'`
*
* @var string
*/
protected $type;
/**
* Set the type and master key for the cache
*
* A `file` cache uses a single file to store values in an associative
* array and is probably not suitable for a large number of keys.
*
* Using an `apc` or `xcache` cache will have far better performance
* than a file or directory, however please remember that keys are shared
* server-wide.
*
* `$config` is an associative array of configuration options for the various
* backends. Some backend require additional configuration, while others
* provide provide optional settings.
*
* The following `$config` options must be set for the `database` backend:
*
* - `table`: The database table to use for caching
* - `key_column`: The column to store the cache key in - must support at least 250 character strings
* - `value_column`: The column to store the serialized value in - this should probably be a `TEXT` column to support large values, or `BLOB` if binary serialization is used
* - `value_data_type`: If a `BLOB` column is being used for the `value_column`, this should be set to 'blob', otherwise `string`
* - `ttl_column`: The column to store the expiration timestamp of the cached entry - this should be an integer
*
* The following `$config` for the following items can be set for all backends:
*
* - `serializer`: A callback to serialize data with, defaults to the PHP function `serialize()`
* - `unserializer`: A callback to unserialize data with, defaults to the PHP function `unserialize()`
*
* Common serialization callbacks include:
*
* - `json_encode`/`json_decode`
* - `igbinary_serialize`/`igbinary_unserialize`
*
* Please note that using JSON for serialization will exclude all non-public
* properties of objects from being serialized.
*
* A custom `serialize` and `unserialze` option is `string`, which will cast
* all values to a string when storing, instead of serializing them. If a
* `__toString()` method is provided for objects, it will be called.
*
* @param string $type The type of caching to use: `'apc'`, `'database'`, `'directory'`, `'file'`, `'memcache'`, `'redis'`, `'xcache'`
* @param mixed $data_store The path for a `file` or `directory` cache, an `Memcache` or `Memcached` object for a `memcache` cache, an fDatabase object for a `database` cache or a `Redis` object for a `redis` cache - not used for `apc` or `xcache`
* @param array $config Configuration options - see method description for details
* @return fCache
*/
public function __construct($type, $data_store=NULL, $config=array())
{
switch ($type) {
case 'database':
foreach (array('table', 'key_column', 'value_column', 'ttl_column') as $key) {
if (empty($config[$key])) {
throw new fProgrammerException(
'The config key %s is not set',
$key
);
}
}
$this->config = $config;
if (!isset($this->config['value_data_type'])) {
$this->config['value_data_type'] = 'string';
}
if (!$data_store instanceof fDatabase) {
throw new fProgrammerException(
'The data store provided is not a valid %s object',
'fDatabase'
);
}
$this->data_store = $data_store;
break;
case 'directory':
$exists = file_exists($data_store);
if (!$exists) {
throw new fEnvironmentException(
'The directory specified, %s, does not exist',
$data_store
);
}
if (!is_dir($data_store)) {
throw new fEnvironmentException(
'The path specified, %s, is not a directory',
$data_store
);
}
if (!is_writable($data_store)) {
throw new fEnvironmentException(
'The directory specified, %s, is not writable',
$data_store
);
}
$this->config['path'] = realpath($data_store) . DIRECTORY_SEPARATOR;
break;
case 'file':
$exists = file_exists($data_store);
if (!$exists && !is_writable(dirname($data_store))) {
throw new fEnvironmentException(
'The file specified, %s, does not exist and the directory it in inside of is not writable',
$data_store
);
}
if ($exists && !is_writable($data_store)) {
throw new fEnvironmentException(
'The file specified, %s, is not writable',
$data_store
);
}
$this->config['path'] = $data_store;
if ($exists) {
$this->data_store = unserialize(file_get_contents($data_store));
} else {
$this->data_store = array();
}
$this->config['state'] = 'clean';
break;
case 'memcache':
if (!$data_store instanceof Memcache && !$data_store instanceof Memcached) {
throw new fProgrammerException(
'The data store provided is not a valid %s or %s object',
'Memcache',
'Memcached'
);
}
$this->data_store = $data_store;
break;
case 'redis':
if (!$data_store instanceof Redis) {
throw new fProgrammerException(
'The data store provided is not a valid %s object',
'Redis'
);
}
$this->data_store = $data_store;
break;
case 'apc':
case 'xcache':
if (!extension_loaded($type)) {
throw new fEnvironmentException(
'The %s extension does not appear to be installed',
$type
);
}
break;
default:
throw new fProgrammerException(
'The type specified, %s, is not a valid cache type. Must be one of: %s.',
$type,
join(', ', array('apc', 'database', 'directory', 'file', 'memcache', 'redis', 'xcache'))
);
}
$this->config['serializer'] = isset($config['serializer']) ? $config['serializer'] : 'serialize';
$this->config['unserializer'] = isset($config['unserializer']) ? $config['unserializer'] : 'unserialize';
$this->type = $type;
}
/**
* Cleans up after the cache object
*
* @internal
*
* @return void
*/
public function __destruct()
{
// Only sometimes clean the cache of expired values
if (rand(0, 99) == 50) {
$this->clean();
}
$this->save();
}
/**
* Tries to set a value to the cache, but stops if a value already exists
*
* @param string $key The key to store as, this should not exceed 250 characters
* @param mixed $value The value to store, this will be serialized
* @param integer $ttl The number of seconds to keep the cache valid for, 0 for no limit
* @return boolean If the key/value pair were added successfully
*/
public function add($key, $value, $ttl=0)
{
$value = $this->serialize($value);
switch ($this->type) {
case 'apc':
return apc_add($key, $value, $ttl);
case 'file':
if (isset($this->data_store[$key]) && (($this->data_store[$key]['expire'] && $this->data_store[$key]['expire'] >= time()) || !$this->data_store[$key]['expire'])) {
return FALSE;
}
$this->data_store[$key] = array(
'value' => $value,
'expire' => (!$ttl) ? 0 : time() + $ttl
);
$this->config['state'] = 'dirty';
return TRUE;
case 'database':
$res = $this->data_store->query(
"SELECT %r FROM %r WHERE %r = %s",
$this->config['key_column'],
$this->config['table'],
$this->config['key_column'],
$key
);
if ($res->countReturnedRows()) {
return FALSE;
}
try {
$value_placeholder = $this->config['value_data_type'] == 'blob' ? '%l' : '%s';
$this->data_store->query(
"INSERT INTO %r (%r, %r, %r) VALUES (%s, " . $value_placeholder . ", %i)",
$this->config['table'],
$this->config['key_column'],
$this->config['value_column'],
$this->config['ttl_column'],
$key,
$value,
(!$ttl) ? 0 : time() + $ttl
);
return TRUE;
} catch (fSQLException $e) {
return FALSE;
}
case 'directory':
if (file_exists($this->config['path'] . $key)) {
return FALSE;
}
$expiration_date = (!$ttl) ? 0 : time() + $ttl;
file_put_contents(
$this->config['path'] . $key,
$expiration_date . "\n" . $value
);
return TRUE;
case 'memcache':
if ($ttl > 2592000) {
$ttl = time() + 2592000;
}
if ($this->data_store instanceof Memcache) {
return $this->data_store->add($key, $value, 0, $ttl);
}
return $this->data_store->add($key, $value, $ttl);
case 'redis':
if (!$ttl) {
return $this->data_store->setnx($key, $value);
}
if ($this->data_store->exists($key)) {
return FALSE;
}
$this->data_store->setex($key, $ttl, $value);
return TRUE;
case 'xcache':
if (xcache_isset($key)) {
return FALSE;
}
xcache_set($key, $value, $ttl);
return TRUE;
}
}
/**
* Removes all cache entries that have expired
*
* @return void
*/
public function clean()
{
switch ($this->type) {
case 'database':
$this->data_store->query(
"DELETE FROM %r WHERE %r != 0 AND %r < %i",
$this->config['table'],
$this->config['ttl_column'],
$this->config['ttl_column'],
time()
);
break;
case 'directory':
$clear_before = time();
$files = array_diff(scandir($this->config['path']), array('.', '..'));
foreach ($files as $file) {
if (!file_exists($this->config['path'] . $file)) {
continue;
}
$handle = fopen($this->config['path'] . $file, 'r');
$expiration_date = trim(fgets($handle));
fclose($handle);
if ($expiration_date && $expiration_date < $clear_before) {
unlink($this->config['path'] . $file);
}
}
break;
case 'file':
$clear_before = time();
foreach ($this->data_store as $key => $value) {
if ($value['expire'] && $value['expire'] < $clear_before) {
unset($this->data_store[$key]);
$this->config['state'] = 'dirty';
}
}
break;
}
}
/**
* Clears the WHOLE cache of every key, use with caution!
*
* xcache may require a login or password depending on your ini settings.
*
* @return boolean If the cache was successfully cleared
*/
public function clear()
{
switch ($this->type) {
case 'apc':
return apc_clear_cache('user');
case 'database':
$this->data_store->query(
"DELETE FROM %r",
$this->config['table']
);
return TRUE;
case 'directory':
$files = array_diff(scandir($this->config['path']), array('.', '..'));
$success = TRUE;
foreach ($files as $file) {
fCore::startErrorCapture();
$success = unlink($this->config['path'] . $file) && $success;
fCore::stopErrorCapture();
}
return $success;
case 'file':
$this->data_store = array();
$this->config['state'] = 'dirty';
return TRUE;
case 'memcache':
return $this->data_store->flush();
case 'redis':
return $this->data_store->flushDB();
case 'xcache':
fCore::startErrorCapture();
xcache_clear_cache(XC_TYPE_VAR, 0);
return (bool) fCore::stopErrorCapture();
}
}
/**
* Deletes a value from the cache
*
* @param string $key The key to delete
* @return boolean If the delete succeeded
*/
public function delete($key)
{
switch ($this->type) {
case 'apc':
return apc_delete($key);
case 'database':
return (bool) $this->data_store->query(
"DELETE FROM %r WHERE %r = %s",
$this->config['table'],
$this->config['key_column'],
$key
)->countAffectedRows();
case 'directory':
fCore::startErrorCapture();
$succes = unlink($this->config['path'] . $key);
fCore::stopErrorCapture();
return $success;
case 'file':
if (isset($this->data_store[$key])) {
unset($this->data_store[$key]);
$this->config['state'] = 'dirty';
}
return TRUE;
case 'memcache':
return (bool) $this->data_store->delete($key, 0);
case 'redis':
return (bool) $this->data_store->delete($key);
case 'xcache':
return xcache_unset($key);
}
}
/**
* Returns a value from the cache
*
* @param string $key The key to return the value for
* @param mixed $default The value to return if the key did not exist
* @return mixed The cached value or the default value if no cached value was found
*/
public function get($key, $default=NULL)
{
switch ($this->type) {
case 'apc':
$value = apc_fetch($key);
if ($value === FALSE) { return $default; }
break;
case 'database':
$res = $this->data_store->query(
"SELECT %r FROM %r WHERE %r = %s AND (%r = 0 OR %r >= %i)",
$this->config['value_column'],
$this->config['table'],
$this->config['key_column'],
$key,
$this->config['ttl_column'],
$this->config['ttl_column'],
time()
);
if (!$res->countReturnedRows()) { return $default; }
$value = $res->fetchScalar();
break;
case 'directory':
if (!file_exists($this->config['path'] . $key)) {
return $default;
}
$handle = fopen($this->config['path'] . $key, 'r');
$expiration_date = fgets($handle);
if ($expiration_date != 0 && $expiration_date < time()) {
return $default;
}
$value = '';
while (!feof($handle)) {
$value .= fread($handle, 524288);
}
fclose($handle);
break;
case 'file':
if (isset($this->data_store[$key])) {
$expire = $this->data_store[$key]['expire'];
if (!$expire || $expire >= time()) {
$value = $this->data_store[$key]['value'];
} elseif ($expire) {
unset($this->data_store[$key]);
$this->config['state'] = 'dirty';
}
}
if (!isset($value)) {
return $default;
}
break;
case 'memcache':
$value = $this->data_store->get($key);
if ($value === FALSE) { return $default; }
break;
case 'redis':
$value = $this->data_store->get($key);
if ($value === FALSE) { return $default; }
break;
case 'xcache':
$value = xcache_get($key);
if ($value === FALSE) { return $default; }
}
return $this->unserialize($value);
}
/**
* Only valid for `file` caches, saves the file to disk
*
* @return void
*/
public function save()
{
if ($this->type != 'file' || $this->config['state'] == 'clean') {
return;
}
file_put_contents($this->config['path'], serialize($this->data_store));
$this->config['state'] = 'clean';
}
/**
* Serializes a value before storing it in the cache
*
* @param mixed $value The value to serialize
* @return string The serialized value
*/
protected function serialize($value)
{
if ($this->config['serializer'] == 'string') {
if (is_object($value) && method_exists($value, '__toString')) {
return $value->__toString();
}
return (string) $value;
}
return call_user_func($this->config['serializer'], $value);
}
/**
* Sets a value to the cache, overriding any previous value
*
* @param string $key The key to store as, this should not exceed 250 characters
* @param mixed $value The value to store, this will be serialized
* @param integer $ttl The number of seconds to keep the cache valid for, 0 for no limit
* @return boolean If the value was successfully saved
*/
public function set($key, $value, $ttl=0)
{
$value = $this->serialize($value);
switch ($this->type) {
case 'apc':
return apc_store($key, $value, $ttl);
case 'database':
$res = $this->data_store->query(
"SELECT %r FROM %r WHERE %r = %s",
$this->config['key_column'],
$this->config['table'],
$this->config['key_column'],
$key
);
$expiration_date = (!$ttl) ? 0 : time() + $ttl;
try {
$value_placeholder = $this->config['value_data_type'] == 'blob' ? '%l' : '%s';
if (!$res->countReturnedRows()) {
$this->data_store->query(
"INSERT INTO %r (%r, %r, %r) VALUES (%s, " . $value_placeholder . ", %i)",
$this->config['table'],
$this->config['key_column'],
$this->config['value_column'],
$this->config['ttl_column'],
$key,
$value,
$expiration_date
);
} else {
$this->data_store->query(
"UPDATE %r SET %r = " . $value_placeholder . ", %r = %s WHERE %r = %s",
$this->config['table'],
$this->config['value_column'],
$value,
$this->config['ttl_column'],
$expiration_date,
$this->config['key_column'],
$key
);
}
} catch (fSQLException $e) {
return FALSE;
}
return TRUE;
case 'directory':
$expiration_date = (!$ttl) ? 0 : time() + $ttl;
return (bool) file_put_contents(
$this->config['path'] . $key,
$expiration_date . "\n" . $value
);
case 'file':
$this->data_store[$key] = array(
'value' => $value,
'expire' => (!$ttl) ? 0 : time() + $ttl
);
$this->config['state'] = 'dirty';
return TRUE;
case 'memcache':
if ($ttl > 2592000) {
$ttl = time() + 2592000;
}
if ($this->data_store instanceof Memcache) {
$result = $this->data_store->replace($key, $value, 0, $ttl);
if (!$result) {
return $this->data_store->set($key, $value, 0, $ttl);
}
return $result;
}
return $this->data_store->set($key, $value, $ttl);
case 'redis':
if ($ttl) {
return $this->data_store->setex($key, $ttl, $value);
}
return $this->data_store->set($key, $value);
case 'xcache':
return xcache_set($key, $value, $ttl);
}
}
/**
* Unserializes a value before returning it
*
* @param string $value The serialized value
* @return mixed The PHP value
*/
protected function unserialize($value)
{
if ($this->config['unserializer'] == 'string') {
return $value;
}
return call_user_func($this->config['unserializer'], $value);
}
}
/**
* Copyright (c) 2009-2012 Will Bond <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/