$files name => bytes */ public static function zip(array $files): string { $out = ''; $central = ''; foreach ($files as $name => $bytes) { $crc = crc32($bytes); $size = strlen($bytes); $header = pack('vvvvvVVVvv', 20, 0, 0, 0, 0, $crc, $size, $size, strlen($name), 0); $offset = strlen($out); $out .= "PK\x03\x04" . $header . $name . $bytes; $central .= "PK\x01\x02" . pack('vvvvvvVVVvvvvvVV', 20, 20, 0, 0, 0, 0, $crc, $size, $size, strlen($name), 0, 0, 0, 0, 0, $offset) . $name; } return $out . $central . "PK\x05\x06" . pack('vvvvVVv', 0, 0, count($files), count($files), strlen($central), strlen($out), 0); } /** * The files of a zip (through its central directory), only the names a skin may have. * @return array */ public static function unzip(string $zip): array { $end = strrpos($zip, "PK\x05\x06"); if ($end === false || strlen($zip) < $end + 22) { throw new \InvalidArgumentException('not a zip file'); } $e = unpack('vdisk/vstart/vcount/vtotal/Vsize/Voffset', substr($zip, $end + 4, 16)); $pos = (int)$e['offset']; $files = []; $total = 0; for ($i = 0; $i < min((int)$e['total'], self::MAX_FILES); $i++) { if (substr($zip, $pos, 4) !== "PK\x01\x02") { break; } $c = unpack('vmade/vneed/vflags/vmethod/vtime/vdate/Vcrc/Vcsize/Vusize/vnlen/velen/vclen/vdisk/vint/Vext/Voffset', substr($zip, $pos + 4, 42)); $name = substr($zip, $pos + 46, (int)$c['nlen']); $pos += 46 + (int)$c['nlen'] + (int)$c['elen'] + (int)$c['clen']; $base = basename(str_replace('\\', '/', $name)); if (!preg_match(self::ALLOWED, $base)) { continue; } $l = unpack('vnlen/velen', substr($zip, (int)$c['offset'] + 26, 4)); $data = substr($zip, (int)$c['offset'] + 30 + (int)$l['nlen'] + (int)$l['elen'], (int)$c['csize']); // a zip bomb (a few KB that inflate to GB): never more than MAX_FILE per picture, MAX_TOTAL in all $room = min(self::MAX_FILE, self::MAX_TOTAL - $total); if ($room <= 0 || (int)$c['usize'] > $room || strlen($data) > $room) { continue; } $bytes = match ((int)$c['method']) { 0 => $data, 8 => function_exists('gzinflate') ? @gzinflate($data, $room) : false, default => false, }; if (is_string($bytes) && strlen($bytes) <= $room) { $files[$base] = $bytes; $total += strlen($bytes); } } return $files; } /** Puts a skin zip in a folder; @return bool false when it is not a skin (no INFO.txt or no main picture) */ public static function install(string $zip, string $dir): bool { $files = self::unzip($zip); $names = array_map('strtolower', array_keys($files)); if (!in_array('info.txt', $names, true) || !array_intersect(['main.png', 'main.bmp', 'main.gif', 'main.jpg'], $names)) { return false; } @mkdir($dir, 0777, true); foreach ($files as $name => $bytes) { file_put_contents("$dir/$name", $bytes); } return true; } }