<?php


require("CookiesManager.php");
function randUA() {
  $uas = explode("\n",file_get_contents("uas.txt"));
  return $uas[array_rand($uas)];
}
function randProxy() {
  global $proxies;
  return $proxies[array_rand($proxies)];
}

function isJson($string) {
  try {
   json_decode($string);
   return (json_last_error() == JSON_ERROR_NONE);
  } catch (exception $e) {
   return false;
  }
}

function listAccount() {
  global $pathaccs;
  $d = dir($pathaccs."/");
  $accs = Array();
  while(false !== ($entry = $d->read())) {
    if (strstr($entry, "account_"))
      $accs[] = $entry;
  }
  $d->close();
  return $accs;
}

function doPost($cookiesManager, $proxy, $acc, $ua, $url, $referer = false, $post = false, $bearer = false) {
  global $pathaccs, $cfbypassProxy;
  toLog("[$acc] $proxy request: ".($post ? "POST" : "GET")." ".$url.($post ? "\nData: ".json_encode($post) : '').($bearer ? "\nBearer: ".$bearer : ""));
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($curl, CURLOPT_URL, $url);
	//curl_setopt($curl, CURLOPT_URL, str_replace("https://", "http://", $url));
	//curl_setopt($curl, CURLOPT_COOKIEJAR, $pathaccs.'/'.$acc.'/cookies.txt');
	//url_setopt($curl, CURLOPT_COOKIEFILE, $pathaccs.'/'.$acc.'/cookies.txt');
	curl_setopt($curl, CURLOPT_PROXYPORT, "32421");
	curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
	curl_setopt($curl, CURLOPT_PROXY, "38.79.101.70");
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,15);
  curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
  curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	//curl_setopt($curl, CURLOPT_PROXYUSERPWD, "haseebx2010:E2A85FDC015A9A03358FE4F9C6A483A1");
  //curl_setopt($curl, CURLOPT_PROXY, $cfbypassProxy);
  curl_setopt($curl, CURLOPT_HEADER, 1);
  //["https://haseebx2010:E2A85FDC015A9A03358FE4F9C6A483A1@38.79.90.196:12440","https://haseebx2010:E2A85FDC015A9A03358FE4F9C6A483A1@38.79.91.29:12440", "https://haseebx2010:E2A85FDC015A9A03358FE4F9C6A483A1@38.79.100.126:32421"]
  $headers = array(
    "User-Agent: ". ($ua && $ua != "" ? $ua : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/535.36 (KHTML, like Gecko) Chrome/91.0.4433.0 Safari/537.36'),
    "Referer: ". ($referer ? $referer : "https://www.google.com")
  );
  $f = null;
  $cooks = $cookiesManager->get();
  if ($cooks && $cooks != "" && !$post && !$token) {
    $headers[] = "Cookie: ".$cooks;
  }
  if (!$post && !$token) {
    $headers[] = "Accept-Language: en-US,en;q=0.5";
    $headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    $headers[] = "Accept-Encoding: gzip, deflate, br";
    $headers[] = "Connection: keep-alive";
    $headers[] = "Upgrade-Insecure-Requests: 1";
    $headers[] = "Pragma: no-cache";
    $headers[] = "Cache-Control: no-cache";
    $headers[] = "TE: Trailers";
    $headers[] = "sec-fetch-dest: empty";
    $headers[] = "sec-fetch-mode: cors";
    $headers[] = "sec-fetch-site: cross-site";
  }


  $f = tmpfile();
  curl_setopt($curl, CURLOPT_VERBOSE, 1);
  curl_setopt($curl, CURLOPT_STDERR, $f);


	if ($post) {
		array_push($headers, 'Content-Type: application/json');
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode((array) $post));
	}

	if ($bearer && $bearer != "") {
		array_push($headers, 'Authorization: Bearer ' . $bearer);
	}

	if (count($headers) > 0)
		curl_setopt($curl, CURLOPT_HTTPHEADER,$headers);

  //toLog("Sending headers: ".json_encode($headers));
	$resp = curl_exec($curl);
  //toLog("Response: ".$resp);
  $isredirect = false;
  $curl_info = curl_getinfo($curl);
  $header_size = $curl_info['header_size'];
  $headersx = explode("\n",substr($resp, 0, $header_size));
  $responseBody = substr($resp, $header_size);
  $headers = Array();
  foreach($headersx as $h) {
    $fixh = explode(":", $h);
    $ht = strtolower($fixh[0]);
    unset($fixh[0]);
    $hr = join(":", $fixh);
    if ($headers[$ht]) {
      $headers[$ht] = [$headers[$ht], $hr];
    } else {
      $headers[$ht] = $hr;
    }
  }

  $responseBody = gzdecode($responseBody);


  $saveHeaders = Array();
  if (isset($headers["set-cookie"])) {
    if (strstr($headers["set-cookie"], "\n")) {
      foreach(split("\n", $headers["set-cookie"]) as $c) {
        $saveHeaders[] = $c;
      }
    } else {
      $saveHeaders[] = $headers["set-cookie"];
    }
    $cookiesManager->update($saveHeaders);
  }

  if($curl_info['url'] != $url) {
    $isredirect = $curl_info['url'];
  }

  if ($f) {
    fseek($f, 0);
    echo fread($f, 32*1024); # output up to 32 KB cURL verbose log
    fclose($f);
  }

  $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

  /*
  if ( strlen($resp) && (curl_errno($curl)==CURLE_OK) && ($httpcode==200) ) {
      // check for gzipped content
      if ( (ord($resp[0])==0x1f) && (ord($resp[1])==0x8b) ) {
          // skip header and ungzip the data
          $resp = gzinflate(substr($resp,10));
      }
  }
  */

	curl_close($curl);
	return $responseBody;
}

function justUpdate($id, $acc) {
  global $pathaccs, $accsProxies, $path, $THIS_DOMAIN, $cfbypassAPI;
  $ua = randUA();

  if (!file_exists($pathaccs."/".$acc."/auth.required") && file_exists($pathaccs.'/'.$acc.'/cookies.json')) {
    toLog("Account $acc needs no auth");
    return false;
  }
  $cookiesManager = new CookiesManager($pathaccs.'/'.$acc.'/cookies.file');

  if (!file_exists($pathaccs."/".$acc."/auth.json")) {
    toLog("Account $acc has no auth.json");
    return false;
  }

  $loginInfo = file_get_contents($pathaccs."/".$acc."/auth.json");
  if (!isJson($loginInfo)) {
    toLog("Account $acc bad json");
    return false;
  }

  try {
    @unlink($pathaccs."/".$acc . '/cookies.file');
    @unlink($pathaccs."/".$acc . '/cookies.json');
    @unlink($pathaccs."/".$acc . '/localStorage.json');
    @unlink($pathaccs."/".$acc . '/main.html');
    @unlink($pathaccs."/".$acc . '/ua.txt');
    $loginInfo = json_decode($loginInfo);
    $cookiesManager = new CookiesManager($pathaccs.'/'.$acc.'/cookies.file');
    toLog("[$acc] Logging in...".json_encode($loginInfo));
    $cfbypassed = localCurl($cfbypassAPI, [
      "type" => base64_encode("ahreflogin"),
      "fromurl" => base64_encode($THIS_DOMAIN),
      "proxy" => base64_encode($accsProxies[$id]),
      "userag" => base64_encode($ua),
      "username" => base64_encode($loginInfo->username),
      "password" => base64_encode($loginInfo->password)
    ]);
    //toLog("[$acc] ".$cfbypassed);
    $cfbypassed = json_decode($cfbypassed);

    if (@$cfbypassed->error) {
      toLog("[$acc] ".$cfbypassed->error);
      return false;
    }

    if (@$cfbypassed->working) {
      toLog("[$acc] working...");
      return false;
    }

    // Store new cookies
    if (@$cfbypassed->cookies) {
      $cookiesManager->empty();
      $allcook = [];
      foreach($cfbypassed->cookies as $c) {
        //login_session=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/;
        $addcook = $c->name."=".$c->value;
        if (isset($c->expires))
          $addcook .= "; expires=".date('D j-M-Y H:i:s', $c->expires)." GMT";
        $addcook .= "; Max-Age=0";
        if (isset($c->path))
          $addcook .= "; path=".$c->path;
        if (isset($c->domain))
          $addcook .= "; domain=".$c->domain;
        if (isset($c->sameSite))
          $addcook .= "; sameSite=".$c->sameSite;
        $addcook .= ";";
        $allcook[] = $addcook;
      }

      $cookiesManager->update($allcook);
      file_put_contents($pathaccs."/".$acc . '/cookies.json', json_encode($cfbypassed->cookies));
    }
    if (@$cfbypassed->ua) {
      file_put_contents($pathaccs."/".$acc . '/ua.txt', @$cfbypassed->ua);
    }
    if (@$cfbypassed->body) {
      file_put_contents($pathaccs."/".$acc . '/main.html', $cfbypassed->body);
    }
    if (@$cfbypassed->localStorage) {
      file_put_contents($pathaccs."/".$acc . '/localStorage.json', json_encode($cfbypassed->localStorage));
    }
    @unlink($pathaccs."/".$acc . '/auth.required');
    toLog("[$acc] Logged in!");
  } catch (exception $e) {
    toLog($pathaccs." Error CFBypass: ".$e->getMessage());
    echo "Try again later...";
  }
}
function extractBetween($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_\-\.\~]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}
function localCurl($url, $post) {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
  curl_setopt($curl, CURLOPT_TIMEOUT, 400); //timeout in seconds

  if ($post) {
    curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
    curl_setopt( $curl, CURLOPT_POSTFIELDS, json_encode((array) $post) );
  }

  $resp = curl_exec($curl);
  curl_close($curl);
  return $resp;
}

function toLog($txt) {
  global $path;
  echo "$txt<br>\n";
  file_put_contents($path."/auth.log", $txt."\n", FILE_APPEND);
}

function assocArray($arr1, $arr2) {
  $k = 0;
  $arr= Array();
  foreach($arr2 as $kk => $obj) {
    $arr[$kk] = $arr1[$k];
    if ($k == (count($arr1) - 1)) {
      $k = 0;
    } else $k++;
  }
  return $arr;
}

function getProxies() {
  global $path;
  return json_decode(file_get_contents($path."/proxies.json"));
}

function delProxy($proxy) {
  global $path;
  $proxies = getProxies();
  $reProxies = [];
  foreach($proxies as $prox) {
    if ($proxy != $prox)
      $reProxies[] = $prox;
  }
  file_put_contents($path."/proxies.json", json_encode($reProxies));
}

function getConfig() {
  if (!file_exists("./config.json"))
    return false;
  $config = file_get_contents("./config.json");
  if (!isJson($config))
    return false;
  return json_decode($config);
}

// 196.16.162.160 179.43.137.235
toLog("Starting cornjob...");
// Check/Update members access
$config = getConfig();

if ($config) {
  $path = $config->path;
  $pathaccs = $config->pathaccs;
  $THIS_DOMAIN = $config->domain;
  $cfbypassProxy = $config->cfbypassProxy;
  $cfbypassAPI = "http://".str_replace("5958", "5959", $config->cfbypassProxy);
}
$accs = listAccount();


if (file_exists($path."/working")) {
  die("Working already...\n");
}

file_put_contents($path."/working","1");
set_time_limit(610);
$proxies = getProxies();
$accsProxies = assocArray($proxies, $accs);

foreach ($accs as $id => $acc) {
  toLog("Checking/Updating $acc ($id)");
  justUpdate($id, $acc);
}
@unlink($path."/working");
