NoticeController.php 8.9 KB
<?php
/**
 * Created by PhpStorm.
 * User: zhl
 * Date: 2023/09/02
 * Time: 10:36
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ZipArchive;

/**
 * Class NoticeController
 * @package App\Http\Controllers\Api
 */
class NoticeController extends Controller
{
    const SUCCESS = 200;
    const ERROR = 400;
    const SERVERERROR = 500;
    protected $header = [];//设置请求头参数

    /**
     * @param array $data
     * @param string $message
     * @param int $status
     * @return string
     */
    protected function success($data = [], $message = 'success', $status = 200)
    {
        $array = compact('status', 'message', 'data');
        return json_encode($array, JSON_UNESCAPED_UNICODE);
    }

    /**
     * @param int $status
     * @param string $message
     * @param array $data
     * @return string
     */
    protected function error($message = 'error', $status = 400, $data = [])
    {
        $array = compact('status', 'message', 'data');
        return json_encode($array, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 响应
     * @param null $msg
     * @param string $code
     * @param array $data
     * @param int $result_code
     * @param string $type
     * @return JsonResponse
     */
    public function response($msg = null,string $code = self::SUCCESS,$data = [],$result_code = 200,$type = 'application/json'): JsonResponse
    {
        $result = [
            'msg' => $msg,
            'code' => $code,
            'data' => $data,
        ];
        $this->header['Content-Type'] = $type;
        $response =  response($result,$result_code,$this->header);
        throw new HttpResponseException($response);
    }

    /**
     * GET请求
     * @param $url
     * @return mixed
     */
    public function curlGet($url){
        $ch1     = curl_init();
        $timeout = 0;
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch1, CURLOPT_ENCODING, '');
        curl_setopt($ch1, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch1, CURLOPT_HTTPHEADER, array());
        curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch1, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        $access_txt = curl_exec($ch1);
        curl_close($ch1);
        return json_decode($access_txt, true);
    }

    /**
     * A端上传验证代码
     */
        public function uploadVerifyFile(Request $request): string
    {
        $domain = $request->getHost();
        $files = $request->allFiles();
        foreach ($files as $file) {
            $destinationPath = public_path($domain);
            $file->move($destinationPath, $file->getClientOriginalName());
            $filePath = $destinationPath . '/' . $file->getClientOriginalName();
            @file_put_contents(storage_path('logs/upload_file.log'), date('Y-m-d H:i:s') . " ".$filePath . PHP_EOL, FILE_APPEND);
        }
        return $this->success();
    }

    /**
     * A端上传amp站验证代码
     * @param Request $request
     * @return string
     */
    public function uploadAmpVerifyFile(Request $request): string
    {
        $domain = $request->getHost();

        $domain_array = parse_url($domain);
        $host = $domain_array['host'] ?? $domain_array['path'];
        $host_array = explode('.',$host);
        if(count($host_array) <= 2){
            array_unshift($host_array,'m');
        }else{
            $host_array[0] = 'm';
        }
        $amp_domain = implode('.',$host_array);

        $files = $request->allFiles();
        foreach ($files as $file) {
            $destinationPath = public_path($amp_domain);
            $file->move($destinationPath, $file->getClientOriginalName());
            $filePath = $destinationPath . '/' . $file->getClientOriginalName();
            @file_put_contents(storage_path('logs/upload_file.log'), date('Y-m-d H:i:s') . " ".$filePath . PHP_EOL, FILE_APPEND);
        }
        return $this->success();
    }


    /**
     * 获取需要下载的文件url
     * @param Request $request
     * @return string
     */
    public function websiteHtml(Request $request){
//        $domain = $request->getHost();
        //临时测试域名
        $domain = "demo.globalso.site";
        $token = env("WEB_SITE_TOKEN");
        $apiUrl = env("API_URL");
        $requestUrl = $apiUrl."?domain=".$domain."&token=".$token;
        @file_put_contents(storage_path('logs/notify_get_url.log'), date('Y-m-d H:i:s') . "接收到通知:". $requestUrl . PHP_EOL, FILE_APPEND);


        try {
            $res = $this->curlGet($requestUrl);
            $url = isset($res["data"]["url"]) && !empty($res["data"]["url"]) ? urldecode($res["data"]["url"]) : "";
            if ($res["status"] != self::SUCCESS || $url == ""){
                $msg = isset($res["message"]) && !empty($res["message"]) ? $res["message"] : "请求失败!";
                return $this->error($msg);
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->websiteHtmlHandle($url,$domain);
    }

/**
 * 网站html解压
 * @param $url
 * @return string
 */
public function websiteHtmlHandle($url,$domain)
{
    $pathInfo = pathinfo($url);
    $extension = $pathInfo['extension'];
    //只允许解压zip格式文件
    if (in_array($extension, ["zip"])) {
        try {
            $targetFile = $this->downLoadFile($url);
            $zip = new ZipArchive();
            if ($zip->open($targetFile) === TRUE) {
                $outputFolder = public_path($domain);
                if (!is_dir($outputFolder)) {
                    mkdir($outputFolder, 0777, true);
                }
                // 解压缩文件,保留原文件结构
                $zip->extractTo($outputFolder);
                $zip->close();
                $this->deleteDirectory($targetFile);
            } else {
                return $this->error('解压失败!');
                // 处理打开压缩文件失败的情况
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }else{
        return $this->error('不允许解压改格式压缩包!');
    }
    return  $this->success();
}

    /**
     * 下载文件(下载到public目录下)
     * @param $url
     * @return string
     */
    public function downLoadFile($url){
        $savePath = public_path();
        if (!file_exists($savePath)) {
            mkdir($savePath, 0777, true);
        }
        $targetFile = $savePath . '/' . basename($url);
        $context = stream_context_create([
            'http' => [
                'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
            ],
        ]);
        $fileContent = @file_get_contents($url, false, $context);
        if ($fileContent !== false) {
            file_put_contents($targetFile, $fileContent);
             return $targetFile;
        } else {
            return "";
        }
    }


    /**
     * 删除文件
     * @param $path
     * @return bool
     */
    public function deleteDirectory($path): bool
    {
        if (!is_dir($path)) {
            try {
                unlink($path);
            } catch (\Exception $e) {
                return true;
            }
            return true;
        }
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file) {
            $filePath = $path . '/' . $file;
            if (is_dir($filePath)) {
                $this->deleteDirectory($filePath);
            } else {
                try {
                    unlink($filePath);
                } catch (\Exception $e) {
                    return true;
                }
            }
        }
        rmdir($path);
        return true;
    }

    /**
     * 搜索
     * @param Request $request
     */
    public function search(Request $request)
    {
        $project = $request->get('project');
        $data = $request->all();

        //获取搜索参数
        $searchContent = '';
        if (isset($data['s'])) {
            $searchContent = $data['s'];
        }
        if (isset($data['search'])) {
            $searchContent = $data['search'];
        }

        $page = 1;
        if (isset($data['page']) && (int)$data['page'] > 1) {
            $page = (int)$data['page'];
        }

//        $htmlService = new HtmlService();


//        return $htmlService->getSearchHtml($project, $data, $searchContent, $page);
    }
}