3 namespace Friendica\Core\Cache;
5 use Friendica\Database\Database;
6 use Friendica\Util\DateTimeFormat;
11 * @author Hypolite Petovan <hypolite@mrpetovan.com>
13 class DatabaseCache extends Cache implements ICache
20 public function __construct(string $hostname, Database $dba)
22 parent::__construct($hostname);
30 public function getAllKeys($prefix = null)
33 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
35 $where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
38 $stmt = $this->dba->select('cache', ['k'], $where);
41 while ($key = $this->dba->fetch($stmt)) {
42 array_push($keys, $key['k']);
44 $this->dba->close($stmt);
52 public function get($key)
54 $cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]);
56 if ($this->dba->isResult($cache)) {
57 $cached = $cache['v'];
58 $value = @unserialize($cached);
60 // Only return a value if the serialized value is valid.
61 // We also check if the db entry is a serialized
62 // boolean 'false' value (which we want to return).
63 if ($cached === serialize(false) || $value !== false) {
74 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
78 'v' => serialize($value),
79 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
80 'updated' => DateTimeFormat::utcNow()
84 'v' => serialize($value),
86 'updated' => DateTimeFormat::utcNow()
90 return $this->dba->update('cache', $fields, ['k' => $key], true);
96 public function delete($key)
98 return $this->dba->delete('cache', ['k' => $key]);
104 public function clear($outdated = true)
107 return $this->dba->delete('cache', ['`expires` < NOW()']);
109 return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
116 public function getName()
118 return self::TYPE_DATABASE;