<?php

/*
  PHP version 5
  Copyright (c) 2002-2018 ECISP.CN、EarcLink.COM
  警告：这不是一个免费的软件，请在许可范围内使用，请尊重知识产权，侵权必究，举报有奖
  作者：黄祥云 E-mail:6326420@qq.com  QQ:6326420 TEL:18665655030 / 13797552220
 */

namespace application;

class ESPCMS_FileTool {

	public static function filemode($file, $checktype = 'w') {
		if (!file_exists($file)) {
			return false;
		}
		$file = realpath($file);
		if (is_dir($file)) {
			$testfile = $file . '/isfwrite.text';
			$dir = @opendir($file);
			if (!$dir) {
				return false;
			}
			if ($checktype == 'r') {
				$mode = (@readdir($dir) != false) ? true : false;
				@closedir($dir);
				return $mode;
			}
			if ($checktype == 'w') {
				$fp = @fopen($testfile, 'wb');
				if ($fp != false) {
					$wp = @fwrite($fp, " ");
					$mode = ($wp != false) ? true : false;
					@fclose($fp);
					@unlink($testfile);
					return $mode;
				} else {
					return false;
				}
			}
		} else {
			if ($checktype == 'r') {
				$fp = @is_readable($file);
				$mode = ($fp) ? true : false;
				return $mode;
			}
			if ($checktype == 'w') {
				$fp = @is_writable($file);
				$mode = ($fp) ? true : false;
				return $mode;
			}
		}
	}

	public static function downloadFile($file_url = false, $save_path = false) {
		if (!$file_url || !$save_path) {
			return false;
		}
		$file_content = file_get_contents($file_url);
		if (!$file_content) {
			return false;
		}
		return self::writeFile($save_path, $file_content);
	}

	public static function writeFile($fileName, $content, $type = "wb+") {
		if (empty($fileName)) {
			return false;
		}
		$fd = fopen($fileName, $type);
		if ($fd) {
			fwrite($fd, $content);
			fclose($fd);
			return true;
		} else {
			return false;
		}
	}

	public static function fileArrayet($path) {
		if (!file_exists($path)) {
			return false;
		}
		$arr = array();
		$str = file_get_contents($path);
		if (!$str) {
			$tmp_arr = explode("\n", $str);
			foreach ($tmp_arr as $val) {
				$val = trim($val, "\r;");
				if (!empty($val)) {
					list($table, $count) = explode(':', $val);
					$arr[$table] = $count;
				}
			}
		}
		return $arr;
	}

	public static function delFile($file) {
		if (!is_dir($file)) {
			if (is_file($file)) {
				if (!is_writable($file)) {
					chmod($file, 0777);
				}
				return unlink($file);
			} else {
				return false;
			}
		} else {
			return self::delDir($file);
		}
	}

	public static function delDir($dirName) {
		if ($handle = opendir($dirName)) {
			while (false !== ($item = readdir($handle))) {
				if ($item != '.' && $item != '..') {
					if (is_dir("$dirName/$item")) {
						self::delDir("$dirName/$item");
					} else {
						@unlink("$dirName/$item");
					}
				}
			}
			closedir($handle);
			if (!@rmdir($dirName)) {
				return false;
			}
		} else {
			return false;
		}
	}

	public static function delDirFile($dirPath) {
		if (!$dirPath) {
			return false;
		}
		if (file_exists($dirPath)) {
			$dirname = opendir($dirPath);
			while ($val = readdir($dirname)) {
				if ($val == '.' || $val == '..') {
					continue;
				}
				$value = $dirPath . $val;
				unlink($value);
			}
			closedir($dirname);
			return true;
		} else {
			return false;
		}
	}

	public static function list_dir($dirpath, $extension = array(), $file_type = 'dir', $is_traversal = true) {
		if ($is_traversal && $file_type = 'dir') {
			static $result_file_array = array();
		} else {
			$result_file_array = array();
		}
		if ($dirpath[strlen($dirpath) - 1] != "/") {
			$dirpath .= "/";
		}
		if (is_dir($dirpath)) {
			$handle = opendir($dirpath);
			while (false !== ( $file = readdir($handle))) {
				if ($file == "." || $file == "..") {
					continue;
				}
				$filename = $dirpath . $file;
				if (is_dir($filename) && $is_traversal) {
					array_push($result_file_array, $filename);
					self::list_dir($filename, $extension, $file_type, $is_traversal);
				} else {
					if ($file_type == 'all' && $filename) {
						array_push($result_file_array, $filename);
					}
					if ($file_type == 'dir' && $filename) {
						if (!is_dir($filename)) {
							continue;
						}
						array_push($result_file_array, $filename);
					}
					if ($file_type == 'file') {
						if (is_dir($filename)) {
							continue;
						}
						$options = pathinfo($filename);
						if (is_array($extension) && !in_array($options['extension'], $extension)) {
							continue;
						}
						$options['filepath'] = $filename;
						array_push($result_file_array, $options);
					}
					if ($file_type == 'allfile') {
						if (is_dir($filename)) {
							continue;
						}
						$options = pathinfo($filename);
						$options['filepath'] = $filename;
						array_push($result_file_array, $options);
					}
				}
			}
			closedir($handle);
		}
		return $result_file_array;
	}

	public static function getMimeType($file) {
		return is_dir($file) ? $file : self::mime($file);
	}

	public static function mime($file) {
		$file_f = realpath($file);
		$options = pathinfo($file_f, PATHINFO_EXTENSION);
		return $options;
	}

	public static function format_size($size) {
		if ($size < 1000) {
			$size_BKM = (string) $size . ' B';
		} elseif ($size < (1000 * 1000)) {
			$size_BKM = number_format((double) ($size / 1000), 1) . ' KB';
		} else {
			$size_BKM = number_format((double) ($size / (1000 * 1000)), 1) . ' MB';
		}
		return $size_BKM;
	}

	public static function get_file_format($filetitle_list = array(), $filepath_list = array(), $fileext_list = array(), $filesize_list = array(), $filecontent_list = array()) {
		if (!is_array($filetitle_list) || !is_array($filepath_list) || !is_array($fileext_list) || !is_array($filesize_list)) {
			return false;
		}
		$news_array = array();
		$key = 0;
		foreach ($filetitle_list as $value) {
			$file_attachment_size = $filesize_list[$key];
			$file_attachment_filepath = $filepath_list[$key];
			$news_array[$key]['file_attachment_formatsize'] = espcms_ismatches($file_attachment_size) ? self::format_size($file_attachment_size) : '0K';
			$news_array[$key]['file_attachment_formatfilepath'] = urlencode(espcms_encrypt($file_attachment_filepath, ESPCMS_ENCRYPT_CODE));
			$news_array[$key]['file_attachment_content'] = $filecontent_list[$key];
			$news_array[$key]['file_attachment_title'] = $value;
			$news_array[$key]['file_attachment_filepath'] = $file_attachment_filepath;
			$news_array[$key]['file_attachment_ext'] = $fileext_list[$key];
			$news_array[$key]['file_attachment_size'] = $file_attachment_size;
			switch ($fileext_list[$key]) {
				case 'ai':
					$news_array[$key]['file_icon'] = 'file_list_icon_ai';
					break;
				case 'psd':
					$news_array[$key]['file_icon'] = 'file_list_icon_psd';
					break;
				case 'swf':
					$news_array[$key]['file_icon'] = 'file_list_icon_swf';
					break;
				case 'doc':
					$news_array[$key]['file_icon'] = 'file_list_icon_doc';
					break;
				case 'wps':
					$news_array[$key]['file_icon'] = 'file_list_icon_doc';
					break;
				case 'docx':
					$news_array[$key]['file_icon'] = 'file_list_icon_doc';
					break;
				case 'pdf':
					$news_array[$key]['file_icon'] = 'file_list_icon_pdf';
					break;
				case 'ppt':
					$news_array[$key]['file_icon'] = 'file_list_icon_ppt';
					break;
				case 'pptx':
					$news_array[$key]['file_icon'] = 'file_list_icon_ppt';
					break;
				case 'txt':
					$news_array[$key]['file_icon'] = 'file_list_icon_text';
					break;
				case 'xls':
					$news_array[$key]['file_icon'] = 'file_list_icon_xls';
					break;
				case 'xlsx':
					$news_array[$key]['file_icon'] = 'file_list_icon_xls';
					break;
				case 'gif':
					$news_array[$key]['file_icon'] = 'file_list_icon_gif';
					break;
				case 'jpg':
					$news_array[$key]['file_icon'] = 'file_list_icon_jpg';
					break;
				case 'jpeg':
					$news_array[$key]['file_icon'] = 'file_list_icon_jpg';
					break;
				case 'png':
					$news_array[$key]['file_icon'] = 'file_list_icon_png';
					break;
				case 'rar':
					$news_array[$key]['file_icon'] = 'file_list_icon_rar';
					break;
				case 'zip':
					$news_array[$key]['file_icon'] = 'file_list_icon_zip';
					break;
				case 'mp3':
					$news_array[$key]['file_icon'] = 'file_list_icon_mp3';
					break;
				case 'wav':
					$news_array[$key]['file_icon'] = 'file_list_icon_wav';
					break;
				case 'avi':
					$news_array[$key]['file_icon'] = 'file_list_icon_avi';
					break;
				case 'wmv':
					$news_array[$key]['file_icon'] = 'file_list_icon_wmv';
					break;
				case 'mp4':
					$news_array[$key]['file_icon'] = 'file_list_icon_mp4';
					break;
				case 'mpeg':
					$news_array[$key]['file_icon'] = 'file_list_icon_mpeg';
					break;
				case 'flv':
					$news_array[$key]['file_icon'] = 'file_list_icon_flv';
					break;
				default:
					$news_array[$key]['file_icon'] = 'file_list_icon_file';
					break;
			}
			$key++;
		}
		return $news_array;
	}

	public static function fgetcsv_reg(& $handle, $length = null, $d = ',', $e = '"') {
		$d = preg_quote($d);
		$e = preg_quote($e);
		$_line = "";
		$eof = false;
		while ($eof != true) {
			$_line .= empty($length) ? @fgets($handle) : @fgets($handle, $length);
			$itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
			if ($itemcnt % 2 == 0) {
				$eof = true;
			}
		}
		$_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
		$_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
		preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
		$_csv_data = $_csv_matches[1];
		for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
			$_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1', $_csv_data[$_csv_i]);
			$_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
		}
		return empty($_line) ? false : $_csv_data;
	}

	public static function file_type_screen($extension = false) {
		if (!$extension) {
			return false;
		}
		$images_type_array = array('jpg', 'png', 'jpeg', 'gif');
		$mover_type_array = array('mp4', 'avi', 'flv', 'mpge', 'mkv');
		if (in_array($extension, $images_type_array)) {
			$type = 'image';
		} elseif (in_array($extension, $mover_type_array)) {
			$type = 'mover';
		} else {
			$type = 'file';
		}
		return $type;
	}

	public static function file_copy($path, $dest) {
		if (is_dir($path)) {
			if (!is_dir($dest)) {
				if (!mkdir($dest)) {
					return false;
				}
			}
			$objects = scandir($path);
			if (count($objects) < 1) {
				return false;
			}
			foreach ($objects as $file) {
				if ($file == "." || $file == "..") {
					continue;
				}
				if (is_dir($path . DIRECTORY_SEPARATOR . $file)) {
					self::file_copy($path . DIRECTORY_SEPARATOR . $file, $dest . DIRECTORY_SEPARATOR . $file);
				} else {
					copy($path . DIRECTORY_SEPARATOR . $file, $dest . DIRECTORY_SEPARATOR . $file);
				}
			}
			return true;
		} elseif (is_file($path)) {
			return copy($path, $dest);
		} else {
			return false;
		}
	}

	public static function is_dir_writeable($dir) {
		$writeable = 0;
		if (!is_dir($dir)) {
			@mkdir($dir, 0777);
		}
		if (is_dir($dir)) {
			if ($fp = fopen("$dir/test.txt", 'w')) {
				fclose($fp);
				unlink("$dir/test.txt");
				$writeable = 1;
			} else {
				$writeable = 0;
			}
		}
		return $writeable;
	}

}
