3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Type;
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Cache\ICache;
26 use Friendica\Core\Cache\Enum\Type;
27 use Friendica\Database\Database;
28 use Friendica\Util\DateTimeFormat;
33 class DatabaseCache extends BaseCache implements ICache
40 public function __construct(string $hostname, Database $dba)
42 parent::__construct($hostname);
50 public function getAllKeys($prefix = null)
53 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
55 $where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
58 $stmt = $this->dba->select('cache', ['k'], $where);
61 while ($key = $this->dba->fetch($stmt)) {
62 array_push($keys, $key['k']);
64 $this->dba->close($stmt);
72 public function get($key)
74 $cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]);
76 if ($this->dba->isResult($cache)) {
77 $cached = $cache['v'];
78 $value = @unserialize($cached);
80 // Only return a value if the serialized value is valid.
81 // We also check if the db entry is a serialized
82 // boolean 'false' value (which we want to return).
83 if ($cached === serialize(false) || $value !== false) {
94 public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
98 'v' => serialize($value),
99 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
100 'updated' => DateTimeFormat::utcNow()
104 'v' => serialize($value),
106 'updated' => DateTimeFormat::utcNow()
110 return $this->dba->update('cache', $fields, ['k' => $key], true);
116 public function delete($key)
118 return $this->dba->delete('cache', ['k' => $key]);
124 public function clear($outdated = true)
127 return $this->dba->delete('cache', ['`expires` < NOW()']);
129 return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
136 public function getName()
138 return Type::DATABASE;