<?php
if (!defined('USING_SYSTEM')) exit;

class p402_sxExe extends xIExecutor {
	
	public function main() {
		if(isset($_GET['do'])) {
			// --- 一个个删 ---
			if($_GET['do']=='unlink') {
				$server = new xVolume($_POST['sid']+0);
				$files = xVFile::getUnlink();
				$needUnlinkFids = '';
				$freeSize = '0';
				$sqls = array();
				while($file = $files->fetch_assoc()) {
					$freeSize .= '+'.$file['size'];
					$servid = -1;
					if($file['serv0'] == $server->id) $servid = 0;
					else if($file['serv1'] == $server->id) $servid = 1;
					else if($file['serv2'] == $server->id) $servid = 2;
					else if($file['serv3'] == $server->id) $servid = 3;
					if($servid !== -1) {
						$needUnlinkFids .= $file['id'].',';
						$file['serv'.$servid] = '0';
						if(($file['serv0']=='0')&&($file['serv1']=='0')&&($file['serv2']=='0')&&($file['serv3']=='0'))
							$sqls[] = 'DELETE FROM `'.TB_VFILES.'` WHERE `id` = "'.$file['id'].'";';
						else
							$sqls[] = 'UPDATE `'.TB_VFILES.'` SET `serv'.$servid.'` = 0 WHERE `id` = "'.$file['id'].'";';
					}
				}
				$files->free();
				if($needUnlinkFids!='') {
					$needUnlinkFids = substr($needUnlinkFids, 0, -1);
					if($server->id == '1') {
						// --- 本地卷 ---
						$vfr = xGbl::$mysql->exec('SELECT * FROM `fa_volume_vfiles` WHERE `id` IN('.$needUnlinkFids.');');
						while($f = $vfr->fetch_assoc()) {
							if(is_file(__ROOT__.'volume/'.$f['path']))
								unlink(__ROOT__.'volume/'.$f['path']);
						}
						$vfr->free();
						xGbl::$mysql->exec('DELETE FROM `fa_volume_vfiles` WHERE `id` IN('.$needUnlinkFids.');');
					}
				}
				// --- 执行主站的相关 SQL ---
				foreach($sqls as $sql)
					xGbl::$mysql->exec($sql);
				if($freeSize !== '0')
					xGbl::$mysql->exec('UPDATE `fa_servers` SET `rsize` = `size` - (`size` - `rsize` - ('.$freeSize.')) WHERE `id` = '.$server->id.';');
				echo json_encode(array(
					'result' => '1',
					'id' => $server->id
				));
			}
		} else {
			include_once(__ROOT__.'admin/ui.p402.php');
		}
	}
	
	public function onError($result) {
		
	}
	
}
