3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core\Cache;
24 use Friendica\Database\Database;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Core\BaseCache;
31 class DatabaseCache extends BaseCache implements ICache
38 public function __construct(string $hostname, Database $dba)
40 parent::__construct($hostname);
48 public function getAllKeys($prefix = null)
51 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
53 $where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
56 $stmt = $this->dba->select('cache', ['k'], $where);
59 while ($key = $this->dba->fetch($stmt)) {
60 array_push($keys, $key['k']);
62 $this->dba->close($stmt);
70 public function get($key)
72 $cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]);
74 if ($this->dba->isResult($cache)) {
75 $cached = $cache['v'];
76 $value = @unserialize($cached);
78 // Only return a value if the serialized value is valid.
79 // We also check if the db entry is a serialized
80 // boolean 'false' value (which we want to return).
81 if ($cached === serialize(false) || $value !== false) {
92 public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
96 'v' => serialize($value),
97 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
98 'updated' => DateTimeFormat::utcNow()
102 'v' => serialize($value),
104 'updated' => DateTimeFormat::utcNow()
108 return $this->dba->update('cache', $fields, ['k' => $key], true);
114 public function delete($key)
116 return $this->dba->delete('cache', ['k' => $key]);
122 public function clear($outdated = true)
125 return $this->dba->delete('cache', ['`expires` < NOW()']);
127 return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
134 public function getName()
136 return Type::DATABASE;