<?php
declare(strict_types=1);
$path=parse_url($_SERVER['REQUEST_URI']??'',PHP_URL_PATH);$allowed=['/__poc_boundary'=>'GET'];
foreach(['store','terminal'] as $module){foreach(['list'=>'GET','edit'=>'POST','moveGroup'=>'POST'] as $a=>$m)$allowed['/'.$module.'/Files/'.$a]=$m;foreach(['list'=>'GET','add'=>'POST','edit'=>'POST'] as $a=>$m)$allowed['/'.$module.'/files.Group/'.$a]=$m;}
if(!isset($allowed[$path])||$allowed[$path]!==($_SERVER['REQUEST_METHOD']??'')){http_response_code(403);echo '{"metadata_allowlist":false}';return;}
$root=getenv('FILES_APP_ROOT');$runtime=getenv('PILOT_RUNTIME');$tenant=1930301010;$marker='CDXFM10B27A4D6E9C01';
$_SERVER['SCRIPT_FILENAME']=$root.'/public/index.php';$_SERVER['SCRIPT_NAME']='/index.php';$_SERVER['PHP_SELF']='/index.php';
define('TP_ENV','poc');define('BUSINESS','aizhct');define('ENTERPRISE_NO','10001');$loader=require $root.'/vendor/autoload.php';$loader->setPsr4('app\\',$root.'/app');$loader->setPsr4('cores\\',$root.'/cores');require $root.'/external_stubs.php';
$storageAttempts=0;spl_autoload_register(static function($class)use(&$storageAttempts):void{if(strpos(strtolower($class),'app\\common\\library\\storage\\')===0||strtolower($class)==='app\\common\\library\\upload'){++$storageAttempts;throw new RuntimeException('Upload/storage forbidden in metadata HTTP test');}},true,true);
try{
    $app=new \think\App($root);$app->setEnvName('poc');$app->setRuntimePath($runtime.'/runtime/');$app->initialize();$app->debug(false);$app->env->set('APP_DEBUG',false);\think\App::$store_id=$tenant;
    if(realpath(root_path())!==realpath($root))throw new RuntimeException('Actual application root is not new private root');
    $app->config->set(['default'=>'file','stores'=>['file'=>['type'=>'File','path'=>$runtime.'/cache/','prefix'=>'','expire'=>0]]],'cache');
    $app->config->set(['close'=>true,'default'=>'file','channels'=>['file'=>['type'=>'FileFormat','path'=>$runtime.'/logs/','close'=>true]]],'log');
    if($path==='/__poc_boundary'){echo json_encode(['external_stubs'=>class_exists(\app\common\Serve::class,false)&&class_exists(\app\common\UserApi::class,false),'metadata_allowlist'=>true,'new_private_app_root'=>true,'storage_guard'=>true]);return;}
    $scenario=$_SERVER['HTTP_X_PILOT_SCENARIO']??'';if(!preg_match('/^PILOT_FILES_[A-Z0-9_]{1,60}$/D',$scenario)){http_response_code(403);echo '{"scenario":false}';return;}
    if(strpos($path,'/Files/list')!==false){
        $targets=['vendor/topthink/framework/src/think/Filesystem.php','vendor/topthink/framework/src/think/facade/Filesystem.php','vendor/topthink/framework/tests/FilesystemTest.php','vendor/topthink/framework/src/think/filesystem/'];
        $exists=[];foreach($targets as $target)$exists[$target]=file_exists(root_path().$target)||is_link(root_path().$target);
        $version=\cores\library\Version::getVersion();$sha=hash_file('sha256',root_path().'version.json');
        $valid=realpath(root_path())===realpath($root)&&$sha==='c4183782e45ec544e34be623297955ef183135347f8b43c944d3579bd6a94e78'&&$version==='0.0.1'&&\cores\library\Version::compare($version,'2.0.7')<0&&!in_array(true,$exists,true);
        file_put_contents($runtime.'/list_guards.jsonl',json_encode(['scenario'=>$scenario,'actual_new_root'=>realpath(root_path())===realpath($root),'version_sha256'=>$sha,'actual_version'=>$version,'below_2_0_7'=>\cores\library\Version::compare($version,'2.0.7')<0,'deletion_targets_exist'=>$exists,'allowed'=>$valid])."\n",FILE_APPEND|LOCK_EX);
        if(!$valid){http_response_code(409);echo '{"list_environment_limited":true}';return;}
    }
    $payload=[];if(($_SERVER['REQUEST_METHOD']??'')==='POST'){$payload=json_decode((string)file_get_contents('php://input'),true);if(!is_array($payload))throw new RuntimeException('Expected actual-client JSON body');}
    $params=array_merge($_GET,$payload);$ownGroup=static function($id)use($app,$tenant,$marker):bool{if((string)$id==='0')return true;if(!is_int($id)&&!(is_string($id)&&preg_match('/^\d+$/D',$id)))return false;return (int)$app->db->connect()->name('upload_group')->where('group_id',(int)$id)->where('store_id',$tenant)->where('name','like',$marker.'%')->count()===1;};
    $ownFile=static function($id)use($app,$tenant,$marker):bool{if(!is_int($id)&&!(is_string($id)&&preg_match('/^\d+$/D',$id)))return false;return (int)$app->db->connect()->name('upload_file')->where('file_id',(int)$id)->where('store_id',$tenant)->where('file_path','like',$marker.'%')->count()===1;};
    $safe=true;
    if(strpos($path,'/Files/edit')!==false){$form=$payload['form']??[];$safe=$ownFile($params['fileId']??null)&&is_array($form)&&!array_diff(array_keys($form),['file_name','group_id'])&&isset($form['file_name'])&&strpos($form['file_name'],$marker)===0&&(!isset($form['group_id'])||$ownGroup($form['group_id']));}
    if(strpos($path,'/Files/moveGroup')!==false){$safe=$ownGroup($params['groupId']??null)&&is_array($params['fileIds']??null)&&count($params['fileIds'])>0;foreach($params['fileIds']??[] as $id)$safe=$safe&&$ownFile($id);}
    if(strpos($path,'/files.Group/add')!==false||strpos($path,'/files.Group/edit')!==false){$form=$payload['form']??[];$safe=is_array($form)&&!array_diff(array_keys($form),['name','parent_id','sort'])&&isset($form['name'])&&strpos($form['name'],$marker)===0&&$ownGroup($form['parent_id']??0);if(strpos($path,'/edit')!==false)$safe=$safe&&(string)($params['groupId']??'0')!=='0'&&$ownGroup($params['groupId']??null);}
    if(!$safe){http_response_code(403);echo '{"owned_metadata_guard":false}';return;}
    require __DIR__.'/SqlCoverageRecorder.php';$config=$app->config->get('database');foreach($config['connections'] as &$conn){$conn['trigger_sql']=true;$conn['debug']=false;}unset($conn);$app->config->set($config,'database');$app->db->setConfig($app->config);
    $recorder=new SqlCoverageRecorder($runtime.'/queries.jsonl',realpath($root),$scenario);$app->db->listen(static function($sql,$time=null)use($recorder){if(strpos($sql,'CONNECT:')!==0)$recorder->observe($sql,$time);});register_shutdown_function([$recorder,'finish']);
    register_shutdown_function(static function()use(&$storageAttempts,$runtime,$scenario):void{file_put_contents($runtime.'/storage_guard.jsonl',json_encode(['scenario'=>$scenario,'forbidden_attempts'=>$storageAttempts])."\n",FILE_APPEND|LOCK_EX);});
    $http=$app->http;$response=$http->run();$response->send();$http->end($response);
}catch(Throwable $e){http_response_code(500);echo json_encode(['private_bootstrap_error'=>get_class($e),'file'=>basename($e->getFile()),'line'=>$e->getLine()]);file_put_contents($runtime.'/error-private.jsonl',json_encode(['class'=>get_class($e),'file'=>basename($e->getFile()),'line'=>$e->getLine(),'message_base64'=>base64_encode($e->getMessage())])."\n",FILE_APPEND|LOCK_EX);chmod($runtime.'/error-private.jsonl',0600);}
