<?php

/**
 *--------------------------------------
 * editror json data
 *--------------------------------------
 * @project		: loga
 * @author		: cblee
 * @created		: 2016-06-29
 * @copyright	: (c)2016 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class EditorjsonCtrlr extends ManageCtrlr {
	public function upload() {
		vendor('Json#class');
		$json = new Services_JSON();

		if(!check_token()) {
			echo $json->encode(array('error' => 1, 'message' => L('DATA_INVALID')));
			exit;
		}

		$thumb = ('yes' == ARequest::get('thumb') ? true : false);

		$field = 'imgFile'; /* file field name */

		$_ou = M('Option')->get_option('upload');

		$uploadDir = ROOT_PATH.D_S.$_ou['dir'].D_S.date($_ou['sub_dir']);
		$u_params = array();
		$u_params['uploadDir'] = $uploadDir;
		$u_params['typeset'] = array_merge(explode(',', $_ou['imgtype']), explode(',', $_ou['filetype']));

		$_u = get_instance('AUpload', $u_params);
		$upload = $_u->do_upload($field);

		$err = $_u->uploadError['msg'][0];
		if(!empty($err)) {
			echo $json->encode(array('error' => 1, 'message' => $err));
			exit;
		}

		if($thumb) {
			$_oi = M('Option')->get_option('image');
			$i_params = array();
			$i_params['sourceDir'] = $uploadDir;
			$i_params['outputDir'] = $uploadDir;
			$_i = get_instance('AImage', $i_params);
			$upload = $_i->thumbnail($upload['name'], $_oi['thumb_width'], $_oi['thumb_height'], $_oi['thumb_prefix'], $_oi['thumb_proportional']);

			$err = $_i->imageError[0];
			if(!empty($err)) {
				echo $json->encode(array('error' => 1, 'message' => $err));
				exit;
			}
		}

		$filePath = __APP__.$_ou['dir'].'/'.date($_ou['sub_dir']).'/'.$upload['name'];

		echo $json->encode(array('error' => 0, 'url' => $filePath));
		exit;
	}

	public function file_manage() {
		vendor('Json#class');

		$_ou = M('Option')->get_option('upload');

		$uploadDir = ROOT_PATH.D_S.$_ou['dir'].D_S.date($_ou['sub_dir']);

		/* such as /var/www/attached/ */
		$root_path = ROOT_PATH.D_S.$_ou['dir'].D_S;
		/* such as http://www.yoursite.com/attached/ */
		$root_url = __APP__.$_ou['dir'].'/';
		/* img ext */
		$ext_arr = explode(',', $_ou['imgtype']);

		if(empty($_GET['path'])) {
			$current_path = realpath($root_path).'/';
			$current_url = $root_url;
			$current_dir_path = '';
			$moveup_dir_path = '';
		}
		else {
			$current_path = realpath($root_path).'/'.$_GET['path'];
			$current_url = $root_url . $_GET['path'];
			$current_dir_path = $_GET['path'];
			$moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
		}

		/* name or size or type */
		$order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);

		/* not allow .. move to parent dir */
		if(preg_match('/\.\./', $current_path)) {
			echo 'Access is not allowed.';
			exit;
		}

		/* the last char is not / */
		if(!preg_match('/\/$/', $current_path)) {
			echo 'Parameter is not valid.';
			exit;
		}

		/* dir not exists */
		if(!file_exists($current_path) || !is_dir($current_path)) {
			echo 'Directory does not exist.';
			exit;
		}

		$file_list = array();
		if($handle = opendir($current_path)) {
			$i = 0;
			while(false !== ($filename = readdir($handle))) {
				if($filename{0} == '.') continue;
				$file = $current_path.$filename;
				if(is_dir($file)) {
					$file_list[$i]['is_dir'] = true;
					$file_list[$i]['has_file'] = (count(scandir($file)) > 2);
					$file_list[$i]['filesize'] = 0;
					$file_list[$i]['is_photo'] = false;
					$file_list[$i]['filetype'] = '';
				}
				else {
					$file_list[$i]['is_dir'] = false;
					$file_list[$i]['has_file'] = false;
					$file_list[$i]['filesize'] = filesize($file);
					$file_list[$i]['dir_path'] = '';
					$file_ext = strtolower(array_pop(explode('.', trim($file))));
					$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
					$file_list[$i]['filetype'] = $file_ext;
				}
				$file_list[$i]['filename'] = $filename; /* filename, include ext */
				$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); /* file last modify date time */
				$i++;
			}
			closedir($handle);
		}

		usort($file_list, array('EditorjsonCtrlr', 'cmp_func'));
		$result = array();

		$result['moveup_dir_path'] = $moveup_dir_path;
		$result['current_dir_path'] = $current_dir_path;
		/* current dir URL */
		$result['current_url'] = $current_url;
		/* total count */
		$result['total_count'] = count($file_list);
		/* file list array */
		$result['file_list'] = $file_list;

		/* output JSON string */
		header('Content-type: application/json; charset=UTF-8');
		$json = new Services_JSON();
		echo $json->encode($result);
		exit;
	}

	/* order */
	protected static function cmp_func($a, $b) {
		global $order;
		if($a['is_dir'] && !$b['is_dir']) {
			return -1;
		}
		else if(!$a['is_dir'] && $b['is_dir']) {
			return 1;
		}
		else {
			if($order == 'size') {
				if($a['filesize'] > $b['filesize']) {
					return 1;
				}
				else if($a['filesize'] < $b['filesize']) {
					return -1;
				}
				else {
					return 0;
				}
			}
			else if($order == 'type') {
				return strcmp($a['filetype'], $b['filetype']);
			}
			else {
				return strcmp($a['filename'], $b['filename']);
			}
		}
	}

}
?>