<?php
// 设置错误报告级别，排除NOTICE和DEPRECATED
error_reporting(E_ALL & ~(E_NOTICE | E_DEPRECATED));

require_once('vendor/autoload.php'); // 导入WebDriver库

use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Firefox\FirefoxOptions;


function getUrlData($url, $simple = true) {
    if( $simple ){
        return file_get_contents($url);
    }
    // 初始化 cURL 会话
    $ch = curl_init($url);
    // 设置 cURL 选项
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 证书验证（仅在必要时使用）
    // 发送请求并获取响应
    $response = curl_exec($ch);
    // 检查请求是否成功
    if ($response === FALSE) {
        // 关闭 cURL 会话
        curl_close($ch);
        return ['error' => 'Error occurred: ' . curl_error($ch)];
    }
    // 关闭 cURL 会话
    curl_close($ch);
    // 检查解码是否成功
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['error' => 'Error decoding JSON: ' . json_last_error_msg()];
    }
    // 返回解码后的数据
    return $response;
}

function getRandProxyInfo(){
    $url = 'https://getproxy.bzpl.tech/get/';
    $response = getUrlData($url);
    if ($response) {
        $ret = json_decode($response, true);
        if ($ret && $ret['proxy']) {
            return array(
                'proxyType' => 'manual',
                'httpProxy' => $ret['proxy'],
                'sslProxy' => $ret['proxy'],
            );
        } else {
            return null;
        }
    }
    return null;
}

$driverType = 'chrome';
$capabilities = null;

// selenium-server-standalone-#.jar (version 2.x or 3.x)
$serverUrl = 'http://localhost:4444/wd/hub';
$webUrl = 'https://www.baidu.com/';
$customHeaders = null;

$postData = $_REQUEST;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $contentType = $_SERVER['CONTENT_TYPE'];
    if (strpos($contentType, 'application/json') !== false) {
        $jsonData = file_get_contents('php://input');
        try {
            $postData = json_decode($jsonData, true);
        } catch (Exception $e) {
            $postData = $_REQUEST;
        }
    } elseif (strpos($contentType, 'application/x-www-form-urlencoded') !== false) {
        // echo "POST数据格式为表单数据";
        $postData = $_REQUEST;
    } elseif (strpos($contentType, 'multipart/form-data') !== false) {
        $postData = $_FILES['file'];
    } else {
        $jsonData = file_get_contents('php://input');
        try {
            $postData = json_decode($jsonData, true);
        } catch (Exception $e) {
            $postData = $_REQUEST;
        }
    }
}

$isRspMoreInfo = false;
if (isset($postData['url'])) {
    $webUrl = urldecode($postData['url']);
    if (!preg_match('/^(http:\/\/|https:\/\/)/', $webUrl)) {
        $webUrl = 'http://' . $webUrl;
    }
}
if (isset($postData['headers'])) {
    try {
        if(is_string($postData['headers']) && !empty($postData['headers'])) {
            $customHeaders = json_decode($postData['headers'], true);
        } else {
            $customHeaders = $postData['headers'];
        }
    } catch (Exception $e) {
        $customHeaders = null;
    }
}

$isUseProxy = false;
$proxy = null;
if (isset($postData['useProxy'])) {
    $isUseProxy = $postData['useProxy'] == 1 ? true : false;
    if(isset($postData['proxy'])){
        $proxy = [
            'proxyType' => 'manual',
            'httpProxy' => $postData['proxy'],
            'sslProxy' => $postData['proxy'],
        ];
    }else{
        $proxy = getRandProxyInfo();
    }
}

if (isset($postData['rspMore'])) {
    $isRspMoreInfo = $postData['rspMore'] == 1 ? true : false;
}

// selenium-server-standalone-#.jar (version 4.x)
switch ($driverType) {
    case 'chrome':
        // Chrome
        $capabilities = DesiredCapabilities::chrome();
        $options = new ChromeOptions();
        $userAgent =  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3';
        if($customHeaders && isset($customHeaders['User-Agent'])){
            $capabilities->setCapability('userAgent', $customHeaders['User-Agent']);
            $capabilities->setCapability('user-agent', $customHeaders['User-Agent']);
            $userAgent = $customHeaders['User-Agent'];
        }
        $options->addArguments([
            '--headless', // 启用无头模式
            '--disable-gpu', // 禁用GPU加速
            '--user-agent='.$userAgent,
            '--disable-blink-features=AutomationControlled',
            '--disable-browser-side-navigation',
            '--no-sandbox',
            '--disable-dev-shm-usage',
            '--disable-extensions'
        ]);
        $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
        break;
    case 'firefox':
        // Firefox
        $capabilities = DesiredCapabilities::firefox();
        break;
    case 'edge':
        // Microsoft Edge
        $capabilities = DesiredCapabilities::microsoftEdge();
        break;
    default:
        // Chrome
        $capabilities = DesiredCapabilities::chrome();
        break;
}

// Disable accepting SSL certificates
$capabilities->setCapability('acceptSslCerts', false);
if($proxy){
    $capabilities->setCapability('proxy', $proxy);
}

$driver = RemoteWebDriver::create($serverUrl, $capabilities);

$driver->get($webUrl);

// 读取stealth.min.js文件内容
$stealthJsPath = __DIR__ . '/stealth.min.js';
$stealthJsContent = file_get_contents($stealthJsPath);
// 注入stealth.min.js内容
$driver->executeScript($stealthJsContent);

if($customHeaders && isset($customHeaders['Cookie'])){
    $cookieString = $customHeaders['Cookie'];
    $cookies = explode('; ', $cookieString);
    foreach ($cookies as $cookie) {
        list($name, $value) = explode('=', $cookie, 2);
        $driver->manage()->addCookie([
            'name' => $name,
            'value' => $value,
        ]);
    }
    sleep(1);
    // 刷新页面以确保Cookie生效
    $driver->navigate()->refresh();
    $driver->executeScript($stealthJsContent);
}

$content = $driver->getPageSource();

if($isRspMoreInfo){
    $cookies = $driver->manage()->getCookies();
    $rspData = array(
        'cookie' => $cookies,
        'content' => $content
    );
    if($proxy && isset($proxy['httpProxy'])) {
        $rspData['proxy'] = $proxy['httpProxy'];
    }
    echo json_encode($rspData);
} else {
    echo $content;
}

$driver->quit();
?>
