<?php
class CommonAction extends Action {
	// 生成验证码图片
	public function captcha() {
		$captcha = new Captcha();
		$captcha -> image();
	}
	// 验证输入的验证码
	public function checkCaptcha() {
		$captcha = new Captcha();
		echo $captcha -> check(R('captcha'))?'success':iconv(C('APP_CHARSET', 1), 'utf-8', L('CAPTCHA_ERROR'));
	}
	// 上传文件
	public function upload() {
		$type = R('type')?R('type'):'image';
		$immediate = intval(R('immediate'));
		$attachmentObj = M('attachment', '', R('module'));
		$response = array('err' => '', 'msg' => '');
		switch ($type) {
			case 'image':
				$alowExts = C('uploadimage', 0, 'attachment');
				break;
			case 'flash':
				$alowExts = C('uploadflash', 0, 'attachment');
				break;
			case 'file':
				$alowExts = C('uploadfile', 0, 'attachment');
				break;
			case 'media':
				$alowExts = C('uploadmedia', 0, 'attachment');
				break;
			default:
				$alowExts = C('uploadimage', 0, 'attachment') . '|' . C('uploadflash', 0, 'attachment') . '|' . C('uploadfile', 0, 'attachment') . '|' . C('uploadmedia', 0, 'attachment');
				break;
		}
		if (isset($_SERVER['HTTP_CONTENT_DISPOSITION']) && preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i', $_SERVER['HTTP_CONTENT_DISPOSITION'], $info)) { // 在线编辑器中HTML5上传
			$upfield = 'filedata';
			$attachments = $attachmentObj -> html5Upload($info[2], $alowExts, '', 0, $type == 'attach'?1:0);
		} else {
			if (isset($_FILES['filedata'])) { // 在线编辑器中普通上传
				$upfield = 'filedata';
			} else $upfield = 'fileToUpload'; //精迅通用上传对话框上传
			$attachments = $attachmentObj -> upload($upfield, $alowExts, '', 0, $type == 'attach'?1:0);
		}
		if (is_array($attachments)) {
			if ($type == 'image' && $upfield == 'filedata' && C('watermarkenable', 0, 'attachment')) { // 编辑器上传的图片加水印
				foreach($attachments as $attachment) {
					$attachmentObj -> waterMark($attachment['path']);
				}
			}
			// 附件模型支持多文件上传,这里暂时仅支持返回单文件上传结果
			$response['msg'] = $attachments[0]['path'];
			if ($upfield == 'filedata' && $type == 'file') $response['msg'] .= '||' . iconv(C('APP_CHARSET', 1), 'utf-8', $attachments[0]['name']);
		} else $response['err'] = iconv(C('APP_CHARSET', 1), 'utf-8', $attachmentObj -> error());
		if ($immediate) $response['msg'] = '!' . $response['msg'];
		echo json_encode($response);
	}
	public function getUploadType() {
		$uploadType = array('image' => C('uploadimage', 0, 'attachment'), 'flash' => C('uploadflash', 0, 'attachment'), 'file' => C('uploadfile', 0, 'attachment'), 'media' => C('uploadmedia', 0, 'attachment'));
		echo json_encode($uploadType);
	}
}
