| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib; |
| 39 | |
| 40 | use Result; |
| 41 | |
| 42 | /** |
| 43 | * キャッシュ |
| 44 | */ |
| 45 | class Cache { |
| 46 | private string $dataDir; |
| 47 | protected int $dataDuration = 1800; // 30分 |
| 48 | |
| 49 | /** |
| 50 | * @param string $dataDir キャッシュの種類(data/cache/の下のディレクトリ名) |
| 51 | * @param string|null $baseDir 保存先(既定はdata/cache/、テスト用) |
| 52 | */ |
| 53 | public function __construct(string $dataDir, ?string $baseDir = null) { |
| 54 | // 「../」でdata/cacheの外に出ない様に |
| 55 | if (!$this->isSafeName($dataDir)) throw new \InvalidArgumentException("不正なキャッシュディレクトリ名: {$dataDir}"); |
| 56 | $this->dataDir = rtrim($baseDir ?? ROOT.'/data/cache', '/').'/'.$dataDir.'/'; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * キャッシュの作成 |
| 61 | * |
| 62 | * @param string $type キャッシュ類(例:login、domainlist等) |
| 63 | * @param array $data 保存するデータ |
| 64 | * @return Result |
| 65 | */ |
| 66 | public function set(string $type, array $data): Result { |
| 67 | if (!$this->isSafeName($type)) return Result::Error('エラー:不正なキャッシュ名。'); |
| 68 | // 以前はdata/cache/が無いと作成に失敗した(再帰的ではなかった) |
| 69 | if (!is_dir($this->dataDir) && !@mkdir($this->dataDir, 0755, true) && !is_dir($this->dataDir)) |
| 70 | return Result::Error('エラー:キャッシュディレクトリの作成に失敗。'); |
| 71 | |
| 72 | $data['lifespan'] = time(); |
| 73 | $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); |
| 74 | if ($json === false) return Result::Error('エラー:キャッシュデータのエンコードに失敗。'); |
| 75 | if (file_put_contents("{$this->dataDir}{$type}.json", $json, LOCK_EX) === false) return Result::Error('エラー:キャッシュデータの保存に失敗。'); |
| 76 | |
| 77 | return Result::Success(); |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * キャッシュから受け取り |
| 82 | * |
| 83 | * @param string $type キャッシュ類(例:login、domainlist等) |
| 84 | * @return array |
| 85 | */ |
| 86 | public function get(string $type): array { |
| 87 | if (!$this->isSafeName($type)) return []; |
| 88 | if (!file_exists("{$this->dataDir}{$type}.json")) return []; |
| 89 | |
| 90 | $content = file_get_contents("{$this->dataDir}{$type}.json"); |
| 91 | if ($content === false) return []; |
| 92 | |
| 93 | $data = json_decode($content, true); |
| 94 | if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) return []; |
| 95 | |
| 96 | return $data; |
| 97 | } |
| 98 | |
| 99 | /** |
| 100 | * キャッシュを破壊する |
| 101 | * |
| 102 | * @param string $name キャッシュのファイル名 |
| 103 | * @return Result |
| 104 | */ |
| 105 | public function murder(string $name): Result { |
| 106 | if (!$this->isSafeName($name)) return Result::Error('エラー:不正なキャッシュ名。'); |
| 107 | if (!file_exists("{$this->dataDir}{$name}.json")) return Result::Error('キャッシュファイルが存在しない。'); |
| 108 | if (!unlink("{$this->dataDir}{$name}.json")) return Result::Error('キャッシュファイルの削除に失敗。'); |
| 109 | return Result::Success(); |
| 110 | } |
| 111 | |
| 112 | /** |
| 113 | * 名前が「$prefix」で始まるキャッシュを全部破壊する(関係するキャッシュをまとめて消す為) |
| 114 | * |
| 115 | * @param string $prefix キャッシュ名の始まり |
| 116 | * @return int 削除した数 |
| 117 | */ |
| 118 | public function murderPrefix(string $prefix): int { |
| 119 | if (!$this->isSafeName($prefix)) return 0; |
| 120 | $n = 0; |
| 121 | foreach (glob($this->dataDir.'*.json') ?: [] as $f) { |
| 122 | if (str_starts_with(basename($f, '.json'), $prefix) && @unlink($f)) $n++; |
| 123 | } |
| 124 | return $n; |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * キャッシュ有効期限の確認 |
| 129 | * |
| 130 | * @param array $cache |
| 131 | * @param mixed $data デフォルト=null |
| 132 | * @param string $dataPoint デフォルト=query |
| 133 | * @return bool |
| 134 | */ |
| 135 | public function resurrect(array $cache, mixed $data = null, string $dataPoint = 'query'): bool { |
| 136 | if (NULL === $data) return (!empty($cache) && (isset($cache['lifespan']) && time() < ($cache['lifespan'] + $this->dataDuration))); |
| 137 | else return (!empty($cache) |
| 138 | && (isset($cache[$dataPoint]) |
| 139 | && $cache[$dataPoint] === $data) |
| 140 | && (isset($cache['lifespan']) && time() < ($cache['lifespan'] + $this->dataDuration))); |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * キャッシュの種類(data/cache/の下のディレクトリ)の一覧(無ければ空) |
| 145 | * |
| 146 | * @param string|null $baseDir 保存先(既定はdata/cache/、テスト用) |
| 147 | * @return array 名前 |
| 148 | */ |
| 149 | public static function kinds(?string $baseDir = null): array { |
| 150 | $base = rtrim($baseDir ?? ROOT.'/data/cache', '/'); |
| 151 | $out = []; |
| 152 | foreach (@scandir($base) ?: [] as $f) { |
| 153 | if (preg_match('/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/', $f) && !str_contains($f, '..') && is_dir("{$base}/{$f}")) $out[] = $f; |
| 154 | } |
| 155 | return $out; |
| 156 | } |
| 157 | |
| 158 | /** |
| 159 | * このキャッシュのファイル |
| 160 | * |
| 161 | * @return array name(キャッシュ名)、size、mtime、created(作った時刻)、fresh(有効期限内か)(名前の順) |
| 162 | */ |
| 163 | public function entries(): array { |
| 164 | $out = []; |
| 165 | foreach (glob($this->dataDir.'*.json') ?: [] as $f) { |
| 166 | $name = basename($f, '.json'); |
| 167 | if (!$this->isSafeName($name)) continue; |
| 168 | $data = $this->get($name); |
| 169 | $out[] = ['name' => $name, 'size' => (int)@filesize($f), 'mtime' => (int)@filemtime($f), |
| 170 | 'created' => isset($data['lifespan']) ? (int)$data['lifespan'] : null, 'fresh' => $this->resurrect($data)]; |
| 171 | } |
| 172 | usort($out, fn($a, $b) => strcmp($a['name'], $b['name'])); |
| 173 | return $out; |
| 174 | } |
| 175 | |
| 176 | /** |
| 177 | * このキャッシュを全部破壊する(空になったディレクトリも消す) |
| 178 | * |
| 179 | * @return int 削除した数 |
| 180 | */ |
| 181 | public function murderAll(): int { |
| 182 | $n = 0; |
| 183 | foreach (glob($this->dataDir.'*.json') ?: [] as $f) if (@unlink($f)) $n++; |
| 184 | @rmdir($this->dataDir); |
| 185 | return $n; |
| 186 | } |
| 187 | |
| 188 | /////// |
| 189 | |
| 190 | /** |
| 191 | * キャッシュ名はファイル名になるので、英数字・「.」「_」「-」だけを許可する(「..」は不可) |
| 192 | * |
| 193 | * @param string $name キャッシュ名 |
| 194 | * @return bool 安全ならtrue |
| 195 | */ |
| 196 | private function isSafeName(string $name): bool { |
| 197 | return preg_match('/^[A-Za-z0-9._-]{1,200}$/', $name) === 1 && !str_contains($name, '..'); |
| 198 | } |
| 199 | } |