<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/8/10
 * Time: 18:50
 */

namespace file;


use network\CurlHelper;
use network\IpHelper;

class FileHelper
{

    /**
     * 读取文件文字内容
     * @param $filePath
     * @return mixed
     */
    public static function read($filePath)
    {
        return file_get_contents($filePath);
    }

    /**
     * 创建并保存文件
     * @param $filePath [指定目录]
     * @param $content [文字内容]
     * @throws \Exception
     */
    public static function save($filePath, $content)
    {
        if (file_exists($filePath)) {//file_exists检查文件是否存在
            $File = new \think\template\driver\File();
            $File->write($filePath, $content);
        } else {
            DirHelper::makeDir(PathHelper::getDir($filePath));//创建目录
            if (false == file_put_contents($filePath, $content) && !empty($content)) {
                throw new \Exception('创建文件失败,请检查目录权限');
            }
        }
    }

    /**
     * 重命名文件
     * @param $old_path
     * @param $new_path
     * @param $overWrite [如果新的文件已存在,false提示异常,true覆盖]
     * @return bool
     * @throws \Exception
     */
    public static function rename($old_path, $new_path, $overWrite = false)
    {
        $old_path = replaceDS($old_path);
        $new_path = replaceDS($new_path);
        if (!file_exists($old_path)) {
            throw new \Exception("old_path not exits:" . $old_path);
        }
        if (file_exists($new_path)) {
            if ($overWrite) {
                unlink($new_path);
            } else {
                throw new \Exception("new_path exits:" . $new_path);
            }
        }
        @rename($old_path, $new_path);
        return true;
    }

    /**
     * 输出文件到浏览器下载
     * @param $filepath [文件物理路径]
     */
    public static function downloadFile($filepath)
    {
        if (file_exists($filepath)) {
            $filename = PathHelper::getFilename($filepath);
            //打开文件
            $file1 = fopen($filepath, "r");
            //输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: " . filesize($filepath));
            Header("Content-Disposition: attachment; filename=$filename");
            echo fread($file1, filesize($filepath));
            fclose($file1);
        }
        echo "文件不存在,请联系客服处理!";
    }

    /**
     * 采集文件
     * @param $downlink [文件下载地址]
     * @param $savePath [文件保存目录路径]
     * @param $saveName [文件保存名称]
     * @return string [返回文件物理路径]
     */
    public static function fetchDownFile($downlink, $savePath, $saveName)
    {
        DirHelper::makeDir($savePath);
        $loaclFile = $savePath . $saveName;
        if (startWith($downlink, 'https')) {
            $user_agent = 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)';
            $referer = 'https://www.baidu.com/s?wd=%E7%99%BE%E5%BA%A6&rsv_spt=1&rsv_iqid=0xe5a39f3b0003c303&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=6&rsv_sug1=4&rsv_sug7=100';
            $randip = IpHelper::getRandIp();
            $arrContextOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                ],
                'http' => [
                    'method' => "GET",
                    'header' => "User-Agent: {$user_agent}\r\nReferer: {$referer}\r\nX-FORWARDED-FOR: {$randip}\r\nCLIENT-IP: {$randip}\r\n",
                    'timeout' => 10,
                ]
            ];
            //下载文件忽略ssl
            $response = file_get_contents($downlink, false, stream_context_create($arrContextOptions)) || die('服务器不支持采集');
            file_put_contents($loaclFile, $response);
        } else {
            ob_start(); //打开输出
            readfile($downlink); //输出图片文件
            $img = ob_get_contents(); //得到浏览器输出
            ob_end_clean(); //清除输出并关闭
            file_put_contents($loaclFile, $img);
        }
        return $loaclFile;
    }

    /**
     * 采集文件
     * @param $downlink [文件下载地址]
     * @param $savePath [文件保存目录路径]
     * @param $saveName [文件保存名称]
     * @return string [返回文件物理路径]
     */
    public static function fetchDownFile2($downlink, $savePath, $saveName)
    {
        DirHelper::makeDir($savePath);
        $loaclFile = $savePath . $saveName;
        $curl = new CurlHelper($downlink);
        $randip = IpHelper::getRandIp();
        $curl->setHeader([
            'CLIENT-IP:' . $randip,
            'X-FORWARDED-FOR:' . $randip
        ]);
        $curl->setReferer("https://www.baidu.com/s?wd=%E7%99%BE%E5%BA%A6&rsv_spt=1&rsv_iqid=0xe5a39f3b0003c303&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=6&rsv_sug1=4&rsv_sug7=100");
        $curl->exec();
        $response = $curl->getResponse();
        if ($response && 200 == $curl->getHttpCode() && !$curl->getError()) {
            file_put_contents($loaclFile, $response);
        }
        return $loaclFile;
    }
}