2018-03-24 14:39:13 -04:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Friendica\Core\Cache;
|
|
|
|
|
|
|
|
use Friendica\Core\Cache;
|
2018-07-19 22:15:21 -04:00
|
|
|
use Friendica\Database\dba;
|
2018-03-24 14:39:13 -04:00
|
|
|
use Friendica\Database\DBM;
|
|
|
|
use Friendica\Util\DateTimeFormat;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Database Cache Driver
|
|
|
|
*
|
|
|
|
* @author Hypolite Petovan <mrpetovan@gmail.com>
|
|
|
|
*/
|
2018-07-05 15:54:20 -04:00
|
|
|
class DatabaseCacheDriver extends AbstractCacheDriver implements ICacheDriver
|
2018-03-24 14:39:13 -04:00
|
|
|
{
|
|
|
|
public function get($key)
|
|
|
|
{
|
|
|
|
$cache = dba::selectFirst('cache', ['v'], ['`k` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
|
|
|
|
|
|
|
|
if (DBM::is_result($cache)) {
|
|
|
|
$cached = $cache['v'];
|
|
|
|
$value = @unserialize($cached);
|
|
|
|
|
|
|
|
// Only return a value if the serialized value is valid.
|
|
|
|
// We also check if the db entry is a serialized
|
|
|
|
// boolean 'false' value (which we want to return).
|
|
|
|
if ($cached === serialize(false) || $value !== false) {
|
|
|
|
return $value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2018-07-04 17:37:22 -04:00
|
|
|
public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
|
2018-03-24 14:39:13 -04:00
|
|
|
{
|
|
|
|
$fields = [
|
|
|
|
'v' => serialize($value),
|
2018-07-07 13:46:16 -04:00
|
|
|
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
|
2018-03-24 14:39:13 -04:00
|
|
|
'updated' => DateTimeFormat::utcNow()
|
|
|
|
];
|
|
|
|
|
|
|
|
return dba::update('cache', $fields, ['k' => $key], true);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function delete($key)
|
|
|
|
{
|
|
|
|
return dba::delete('cache', ['k' => $key]);
|
|
|
|
}
|
|
|
|
|
2018-07-07 13:46:16 -04:00
|
|
|
public function clear($outdated = true)
|
2018-03-24 14:39:13 -04:00
|
|
|
{
|
2018-07-07 13:46:16 -04:00
|
|
|
if ($outdated) {
|
|
|
|
return dba::delete('cache', ['`expires` < NOW()']);
|
|
|
|
} else {
|
|
|
|
return dba::delete('cache', ['`k` IS NOT NULL ']);
|
|
|
|
}
|
2018-03-24 14:39:13 -04:00
|
|
|
}
|
|
|
|
}
|