| 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\Fedi; |
| 39 | |
| 40 | use Std\Lib\Image; |
| 41 | |
| 42 | /** |
| 43 | * アップロードされた画像と動画(投稿の添付とアイコン) |
| 44 | * |
| 45 | * 種類はファイルの中身で判断し(PNG・JPEG・GIF・WebP、動画はMP4・MKV・WebM)、位置情報等が入る部分 |
| 46 | * (JPEGのAPPn、PNGのeXIf・テキスト、WebPのEXIF・XMP、MP4のudta・meta・uuid)を取り除く。 |
| 47 | */ |
| 48 | final class Media { |
| 49 | public const MAX_BYTES = 20971520; // 20 MiB |
| 50 | public const MAX_VIDEO_BYTES = 419430400; // 400 MiB |
| 51 | private const TYPES = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp', 'video/mp4' => 'mp4', 'video/matroska' => 'mkv', 'video/webm' => 'webm']; |
| 52 | |
| 53 | /** |
| 54 | * $_FILESの1件を保存する |
| 55 | * |
| 56 | * @param array $file $_FILES['name']の1件(name, tmp_name, size, error) |
| 57 | * @param string $dir 保存先(ASS_DOMAINの下、例:「media/ユーザー」) |
| 58 | * @param string $prefix ファイル名の接頭辞 |
| 59 | * @param bool $uploaded is_uploaded_fileで確認するか(テストではfalse) |
| 60 | * @param bool $video 動画も受け付けるか(アイコンは画像だけ) |
| 61 | * @return \Result data:path(public/からのパス)、url、type、width、height |
| 62 | */ |
| 63 | public static function save(array $file, string $dir, string $prefix = '', bool $uploaded = true, bool $video = false): \Result { |
| 64 | if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) { |
| 65 | return \Result::Error(($file['error'] ?? 0) === UPLOAD_ERR_INI_SIZE || ($file['error'] ?? 0) === UPLOAD_ERR_FORM_SIZE |
| 66 | ? 'ファイルが大き過ぎます。' : 'ファイルのアップロードに失敗しました。'); |
| 67 | } |
| 68 | $tmp = (string)($file['tmp_name'] ?? ''); |
| 69 | if ($uploaded && !is_uploaded_file($tmp)) return \Result::Error('ファイルのアップロードに失敗しました。'); |
| 70 | $size = filesize($tmp); |
| 71 | if ($size === false || $size === 0) return \Result::Error('ファイルが空です。'); |
| 72 | if ($size > ($video ? self::MAX_VIDEO_BYTES : self::MAX_BYTES)) return \Result::Error(self::tooLarge($video)); |
| 73 | |
| 74 | // 種類は先頭だけで分かる(動画は数百MiBになるので、全部は読まない) |
| 75 | $fh = fopen($tmp, 'rb'); |
| 76 | $type = self::detect($fh ? (string)fread($fh, 64) : ''); |
| 77 | if ($fh) fclose($fh); |
| 78 | $isVideo = $type !== null && str_starts_with($type, 'video/'); |
| 79 | if ($type === null || ($isVideo && !$video)) { |
| 80 | return \Result::Error($video ? 'PNG・JPEG・GIF・WebPの画像と、MP4・MKV・WebMの動画だけアップロード出来ます。' : 'PNG・JPEG・GIF・WebPの画像だけアップロード出来ます。'); |
| 81 | } |
| 82 | if (!$isVideo && $size > self::MAX_BYTES) return \Result::Error(self::tooLarge(false)); |
| 83 | |
| 84 | $rel = ass_path(trim($dir, '/')).'/'; |
| 85 | $abs = ROOT.$rel; |
| 86 | if (!is_dir($abs) && !@mkdir($abs, 0755, true) && !is_dir($abs)) return \Result::Error('保存先を作れません。'); |
| 87 | $name = $prefix.bin2hex(random_bytes(12)).'.'.self::TYPES[$type]; |
| 88 | if ($isVideo) { |
| 89 | // 動画はファイルのまま移して、その場でメタデータを消す |
| 90 | if (!($uploaded ? move_uploaded_file($tmp, $abs.$name) : copy($tmp, $abs.$name))) return \Result::Error('ファイルの保存に失敗しました。'); |
| 91 | if ($type === 'video/mp4' && !self::stripFile($abs.$name)) { |
| 92 | @unlink($abs.$name); |
| 93 | return \Result::Error('動画を読めません。'); |
| 94 | } |
| 95 | } else { |
| 96 | $data = self::strip((string)file_get_contents($tmp), $type); |
| 97 | if (file_put_contents($abs.$name, $data) === false) return \Result::Error('ファイルの保存に失敗しました。'); |
| 98 | } |
| 99 | @chmod($abs.$name, 0644); |
| 100 | |
| 101 | // 大きさ(読めなくても保存は成功) |
| 102 | $w = $h = 0; |
| 103 | if (!$isVideo) { |
| 104 | try { |
| 105 | $img = new Image($rel.$name); |
| 106 | $w = (int)($img->fullInfo->width ?? 0); |
| 107 | $h = (int)($img->fullInfo->height ?? 0); |
| 108 | } catch (\Throwable $e) { |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | return \Result::Success('', [ |
| 113 | 'name' => $name, |
| 114 | 'path' => $rel.$name, |
| 115 | 'url' => ass_url(trim($dir, '/').'/'.$name, Fedi::base()), |
| 116 | 'type' => $type, |
| 117 | 'width' => $w, |
| 118 | 'height' => $h, |
| 119 | ]); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * ファイルの中身から種類を判断する |
| 124 | */ |
| 125 | public static function detect(string $data): ?string { |
| 126 | if (str_starts_with($data, "\x89PNG\r\n\x1a\n")) return 'image/png'; |
| 127 | if (str_starts_with($data, "\xff\xd8\xff")) return 'image/jpeg'; |
| 128 | if (str_starts_with($data, 'GIF87a') || str_starts_with($data, 'GIF89a')) return 'image/gif'; |
| 129 | if (str_starts_with($data, 'RIFF') && substr($data, 8, 4) === 'WEBP') return 'image/webp'; |
| 130 | // ISO BMFF:AVIF・HEIC(画像)とQuickTime(ブラウザで再生出来ない事が多い)は除く |
| 131 | if (substr($data, 4, 4) === 'ftyp') { |
| 132 | $brand = substr($data, 8, 4); |
| 133 | return in_array($brand, ['avif', 'avis', 'heic', 'heix', 'mif1', 'msf1', 'qt '], true) ? null : 'video/mp4'; |
| 134 | } |
| 135 | // Matroska(DocTypeでWebMと分ける) |
| 136 | if (str_starts_with($data, "\x1a\x45\xdf\xa3")) { |
| 137 | $head = substr($data, 0, 64); |
| 138 | if (str_contains($head, "\x42\x82\x84webm")) return 'video/webm'; |
| 139 | if (str_contains($head, "\x42\x82\x88matroska")) return 'video/matroska'; |
| 140 | } |
| 141 | return null; |
| 142 | } |
| 143 | |
| 144 | private static function tooLarge(bool $video): string { |
| 145 | return $video |
| 146 | ? 'ファイルが大き過ぎます(画像は'.(self::MAX_BYTES >> 20).'MiB、動画は'.(self::MAX_VIDEO_BYTES >> 20).'MiBまで)。' |
| 147 | : 'ファイルが大き過ぎます('.(self::MAX_BYTES >> 20).'MiBまで)。'; |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * メタデータを取り除く |
| 152 | * |
| 153 | * JPEG:APP1〜APP15(Exif、XMP等)とCOMを消す(APP0のJFIFは残す) |
| 154 | * PNG:eXIf、tEXt、zTXt、iTXt、tIMEを消す |
| 155 | * WebP:EXIFとXMPのチャンクを消す(VP8Xの印も外す) |
| 156 | * MP4:udta、meta、uuid(位置、機種、XMP等)を同じ大きさの「free」にし、mvhd・tkhd・mdhdの日時を0にする |
| 157 | */ |
| 158 | public static function strip(string $data, string $type): string { |
| 159 | if ($type === 'video/mp4') { |
| 160 | $fh = fopen('php://memory', 'w+b'); |
| 161 | fwrite($fh, $data); |
| 162 | self::blankBoxes($fh, 0, strlen($data), 0); |
| 163 | rewind($fh); |
| 164 | $data = (string)stream_get_contents($fh); |
| 165 | fclose($fh); |
| 166 | return $data; |
| 167 | } |
| 168 | if ($type === 'image/jpeg') { |
| 169 | $out = substr($data, 0, 2); |
| 170 | $pos = 2; |
| 171 | $len = strlen($data); |
| 172 | while ($pos + 4 <= $len && $data[$pos] === "\xff") { |
| 173 | $marker = ord($data[$pos + 1]); |
| 174 | // SOS(画像データの始まり)以降はそのまま |
| 175 | if ($marker === 0xda) break; |
| 176 | $seg = unpack('n', substr($data, $pos + 2, 2))[1]; |
| 177 | if ($seg < 2) break; |
| 178 | $isMeta = ($marker >= 0xe1 && $marker <= 0xef) || $marker === 0xfe; |
| 179 | if (!$isMeta) $out .= substr($data, $pos, $seg + 2); |
| 180 | $pos += $seg + 2; |
| 181 | } |
| 182 | return $out.substr($data, $pos); |
| 183 | } |
| 184 | if ($type === 'image/png') { |
| 185 | $out = substr($data, 0, 8); |
| 186 | $pos = 8; |
| 187 | $len = strlen($data); |
| 188 | while ($pos + 12 <= $len) { |
| 189 | $clen = unpack('N', substr($data, $pos, 4))[1]; |
| 190 | $ctype = substr($data, $pos + 4, 4); |
| 191 | $total = $clen + 12; |
| 192 | if ($pos + $total > $len) break; |
| 193 | if (!in_array($ctype, ['eXIf', 'tEXt', 'zTXt', 'iTXt', 'tIME'], true)) $out .= substr($data, $pos, $total); |
| 194 | $pos += $total; |
| 195 | } |
| 196 | return $out; |
| 197 | } |
| 198 | if ($type === 'image/webp') { |
| 199 | $out = ''; |
| 200 | $pos = 12; |
| 201 | $len = min(strlen($data), 8 + unpack('V', substr($data, 4, 4) ?: "\0\0\0\0")[1]); |
| 202 | while ($pos + 8 <= $len) { |
| 203 | $ctype = substr($data, $pos, 4); |
| 204 | $total = 8 + unpack('V', substr($data, $pos + 4, 4))[1]; |
| 205 | $total += $total & 1; |
| 206 | if ($ctype === 'VP8X') { |
| 207 | $chunk = substr($data, $pos, $total); |
| 208 | if (strlen($chunk) > 8) $chunk[8] = chr(ord($chunk[8]) & ~0x0c); |
| 209 | $out .= $chunk; |
| 210 | } else if ($ctype !== 'EXIF' && $ctype !== 'XMP ') { |
| 211 | $out .= substr($data, $pos, $total); |
| 212 | } |
| 213 | $pos += $total; |
| 214 | } |
| 215 | return 'RIFF'.pack('V', 4 + strlen($out)).'WEBP'.$out; |
| 216 | } |
| 217 | return $data; |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * 保存したMP4のメタデータを消す(ファイルの中で書き換える) |
| 222 | */ |
| 223 | public static function stripFile(string $path): bool { |
| 224 | $size = filesize($path); |
| 225 | $fh = $size ? fopen($path, 'r+b') : false; |
| 226 | if (!$fh) return false; |
| 227 | self::blankBoxes($fh, 0, $size, 0); |
| 228 | return fclose($fh); |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * MP4の箱を辿り、メタデータの箱の中身を0にして「free」にする |
| 233 | * 大きさを変えないので、サンプルの位置(stco・co64)を直さなくて良い |
| 234 | * |
| 235 | * @param resource $fh 読み書き出来るファイル |
| 236 | */ |
| 237 | private static function blankBoxes($fh, int $pos, int $end, int $depth): void { |
| 238 | while ($pos + 8 <= $end) { |
| 239 | fseek($fh, $pos); |
| 240 | $hdr = (string)fread($fh, 16); |
| 241 | if (strlen($hdr) < 8) return; |
| 242 | $size = unpack('N', substr($hdr, 0, 4))[1]; |
| 243 | $type = substr($hdr, 4, 4); |
| 244 | $head = 8; |
| 245 | if ($size === 1) { |
| 246 | if (strlen($hdr) < 16) return; |
| 247 | $size = unpack('J', substr($hdr, 8, 8))[1]; |
| 248 | $head = 16; |
| 249 | } else if ($size === 0) { |
| 250 | $size = $end - $pos; |
| 251 | } |
| 252 | if ($size < $head || $pos + $size > $end) return; |
| 253 | |
| 254 | if (in_array($type, ['udta', 'meta', 'uuid'], true)) { |
| 255 | fseek($fh, $pos + 4); |
| 256 | fwrite($fh, 'free'); |
| 257 | self::zero($fh, $pos + $head, $size - $head); |
| 258 | } else if (in_array($type, ['mvhd', 'tkhd', 'mdhd'], true) && $size >= $head + 20) { |
| 259 | // 作成・変更日時(バージョン1は64ビット) |
| 260 | fseek($fh, $pos + $head); |
| 261 | $len = fread($fh, 1) === "\1" ? 16 : 8; |
| 262 | self::zero($fh, $pos + $head + 4, $len); |
| 263 | } else if ($depth < 4 && in_array($type, ['moov', 'trak', 'mdia', 'minf'], true)) { |
| 264 | self::blankBoxes($fh, $pos + $head, $pos + $size, $depth + 1); |
| 265 | } |
| 266 | $pos += $size; |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /** $posから$len個の0を書く(1MiBずつ) */ |
| 271 | private static function zero($fh, int $pos, int $len): void { |
| 272 | fseek($fh, $pos); |
| 273 | $chunk = str_repeat("\0", min($len, 1048576)); |
| 274 | while ($len > 0) { |
| 275 | $n = min($len, strlen($chunk)); |
| 276 | fwrite($fh, $n === strlen($chunk) ? $chunk : substr($chunk, 0, $n)); |
| 277 | $len -= $n; |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * 保存した画像を消す(public/からのパス) |
| 283 | */ |
| 284 | public static function remove(string $path): void { |
| 285 | $abs = realpath(ROOT.$path); |
| 286 | $root = realpath(ROOT.ass_path()); |
| 287 | if ($abs && $root && str_starts_with($abs, $root.DIRECTORY_SEPARATOR) && is_file($abs)) @unlink($abs); |
| 288 | } |
| 289 | } |