<?php

class move_sxExe extends xIExecutor {

	public function main() {
		$toFolder = new xFolder((int)$_POST['toFid'], xUser::$cur);
		if($toFolder->isValid() && $toFolder->isOwner(xUser::$cur)) {
			$toFolderPath = substr($toFolder->paths, strlen(xUser::$cur->username));
			if(($toFolderPath . $toFolder->name . '/' != '/AppData/') && (substr($toFolderPath,0,9) != '/AppData/')) {
				$msg = '';
				if(isset($_POST['checkbox']['folder'])) {
					// --- 移动文件夹 ---
					foreach($_POST['checkbox']['folder'] as $folderID) {
						$folder = new xFolder((int)$folderID);
						if($folder->isValid() && $folder->isOwner(xUser::$cur)) {
							$folderPath = substr($folder->paths, strlen(xUser::$cur->username));
							if(($folderPath . $folder->name . '/' != '/AppData/') && (substr($folderPath,0,9) != '/AppData/')) {
								$toFolderIsShare = xShare::access($toFolder, false);
								if($folder->is(FILEM_SHARED_R0) && $toFolderIsShare)
									$msg .= '<br />"' . $folderPath . $folder->name . '" 禁止将已分享的移动到另一个已分享的';
								else {
									if(($toFolderIsShare && !$folder->containShare()) || !$toFolderIsShare) {
										try {
											$folder->move($toFolder);
										} catch(xError $e) {
											if($e->getCode() == xError::ERR_DUP) {
												$msg .= '<br />"' . $folderPath . $folder->name . '" 目标包含重名文件夹';
											} else if($e->getCode() == xError::ERR_MOVE_TO_CHILD) {
												$msg .= '<br />"' . $folderPath . $folder->name . '" 禁止将自己移动到自己的子文件夹里';
											}
										}
									} else
										$msg .= '<br />"' . $folderPath . $folder->name . '" 禁止将已包含分享项目的文件夹移动到另一个已分享的';
								}
							} else {
								$msg .= '<br />"' . $folderPath . $folder->name . '" 禁止被移动';
							}
						}
					}
				}
				if(isset($_POST['checkbox']['file'])) {
					// --- 移动文件 ---
					foreach($_POST['checkbox']['file'] as $fileID) {
						$file = new xFile((int)$fileID);
						if($file->isValid() && $file->isOwner(xUser::$cur)) {
							$filePath = substr($file->paths, strlen(xUser::$cur->username));
							if(substr($filePath,0,9) != '/AppData/') {
								if($file->is(FILEM_SHARED_R0) && xShare::access($toFolder, false))
									$msg .= '<br />"' . $filePath . $file->name . '" 禁止将已分享的移动到另一个已分享的';
								else {
									try {
										$file->move($toFolder);
									} catch(xError $e) {
										if($e->getCode() == xError::ERR_DUP) {
											$msg .= '<br />"' . $folderPath . $folder->name . '" 目标包含重名文件';
										}
									}
								}
							} else {
								$msg .= '<br />"' . $folderPath . $folder->name . '" 不允许被移动';
							}
						}
					}
				}
				echo json_encode(array(
					'result' => '1',
					'msg' => ($msg == '') ? '所选文件和文件夹都已移动成功' : '部分项目移动失败：<br />' . $msg
				));
			} else {
				echo json_encode(array(
					'result' => '0',
					'msg' => '不允许将项目移动到 AppData 目录当中'
				));
			}
		} else {
			echo json_encode(array(
				'result' => '0',
				'msg' => '目录不存在'
			));
		}
	}

	public function onError($result) {

	}
}

