<?php
set_time_limit(1);
ignore_user_abort(false); 

require '../conf/config.php';
require './common.php';
require 'lockfile.php';

//From http request or command line

if (!isset($_SERVER["HTTP_HOST"])) {
    parse_str($argv[1], $_POST);
    foreach($_POST as $key => $val){
        $_POST[$key] = rtrim($val);
    }
    chdir($_POST['path']);
    set_time_limit(0);
}

(isset($_POST['prm_fa_chr']) && !empty($_POST['prm_fa_chr'])) ? $prm_chr=$_POST['prm_fa_chr']:returnError("Error");
(isset($_POST['prm_fa_s']) && !empty($_POST['prm_fa_s'])) ? $prm_s=$_POST['prm_fa_s']:returnError("Error");
(isset($_POST['prm_fa_e']) && !empty($_POST['prm_fa_e'])) ? $prm_e=$_POST['prm_fa_e']:returnError("Error");
//(isset($_POST['prm_fa_flk']) && !empty($_POST['prm_fa_flk'])) ? $prm_fa_flk=$_POST['prm_fa_flk']:returnError("Error");
(isset($_POST['prm_fa_tgt']) && !empty($_POST['prm_fa_tgt'])) ? $prm_tgt=$_POST['prm_fa_tgt']:returnError("Error");
(isset($_POST['prm_fa_var']) && !empty($_POST['prm_fa_var'])) ? $prm_var=$_POST['prm_fa_var']:$prm_var=".";
(isset($_POST['prm_fa_qual'])) ? $prm_qual=$_POST['prm_fa_qual']:returnError("Error");
(isset($_POST['prm_fa_dp'])) ? $prm_dp=$_POST['prm_fa_dp']:returnError("Error");
(isset($_POST['prm_fa_list']) && !empty($_POST['prm_fa_list'])) ? $prm_list=$_POST['prm_fa_list'] : returnError("Error");
(isset($_POST['prm_fa_name']) && !empty($_POST['prm_fa_name'])) ? $prm_name=$_POST['prm_fa_name'] : returnError("Error");
(isset($_POST['prm_fa_nameS']) && !empty($_POST['prm_fa_nameS'])) ? $prm_nameS=$_POST['prm_fa_nameS'] : returnError("Error");
(isset($_POST['prm_fa_ref']) && !empty($_POST['prm_fa_ref'])) ? $prm_ref=$_POST['prm_fa_ref'] : returnError("Error");
(isset($_POST['prm_fa_width'])) ? $prm_width=$_POST['prm_fa_width'] : returnError("Error");
(isset($_POST['prm_fa_p3prm'])) ? $prm_p3prm=$_POST['prm_fa_p3prm'] : returnError("Error");
(isset($_POST['prm_fa_avd'])) ? $prm_avd=$_POST['prm_fa_avd'] : returnError("Error");
(isset($_POST['prm_fa_Ns'])) ? $prm_Ns=$_POST['prm_fa_Ns'] : returnError("Error");
(isset($_POST['prm_fa_DN'])) ? $prm_DN=$_POST['prm_fa_DN'] : returnError("Error");
(isset($_POST['prm_fa_DNnum'])) ? $prm_DNnum=$_POST['prm_fa_DNnum'] : returnError("Error");
(isset($_POST['prm_type']) && !empty($_POST['prm_type'])) ? $prm_type=$_POST['prm_type'] : returnError("Error");
(isset($_POST['prm_epcrprms'])) ? $prm_epcrprms=$_POST['prm_epcrprms'] : returnError("Error");
(isset($_POST['prm_numthread'])) ? $prm_numthread=$_POST['prm_numthread'] : returnError("Error");
(isset($_POST['sid']) && !empty($_POST['sid'])) ? $sid=$_POST['sid'] : returnError("Error");
$dir = __DIR__;

$php_flg=$_POST['prm_phpflg'];
if ($php_flg == 1) {
        $headurl = $_POST['prm_headurl'];
} else {
        $headers = apache_request_headers();

        foreach ($headers as $header => $value) {
            if($header == "Referer") {
                $headurl = $value;
            }
        }
}

if($sid && !isValidSession($tempdir, $sid)) { _stopError("Invalid connection"); }
//$fpath = sprintf("%s/../tmp/%s.lock",$dir,$sid);
//if (!file_exists($fpath) and $php_flg == 1) {
//        _stopError("Invalid connection");
//}

//Varidate params
if($prm_type != "a" && $prm_type != "b" && $prm_type != "c"){
        error_log("Invalid value: type.\n");
        exit;
}
if ($php_flg != 1 && $php_flg != "") {
        error_log("Invalid value: php_flg.\n");
        exit;
}

$prm_DNnum=0;
$prm_DN=0;
if (!(ctype_digit($prm_tgt)) || !(is_numeric($prm_s)) || !(is_numeric($prm_e)) || !(is_numeric($prm_qual)) || !(is_numeric($prm_dp)) || !(is_numeric($prm_width)) || !(is_numeric($prm_avd)) || !(is_numeric($prm_Ns)) || !(is_numeric($prm_numthread)) || !(is_numeric($prm_DN)) || !(is_numeric($prm_DNnum))) {
        $errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid Value!!</font></div>";
        echo $errmsg;
        exit;
}

if ($php_flg == 1) {
/*
        if(($prm_e - $prm_s) > 19999) {
                $errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid target length!!</font></div>";
                echo $errmsg;
                exit;
        }
*/
} else if($php_flg == "") {
        if(($prm_e - $prm_s) > 199999) {
                $errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid target length!!</font></div>";
                echo $errmsg;
                exit;
        }
}
_pregMatch($prm_name);
_pregMatch($prm_nameS);
_pregMatch($headurl);
_pregMatch($prm_list);
_pregMatch($prm_var);
_pregMatch($prm_p3prm);
_pregMatch($prm_epcrprms);
_pregMatch($prm_chr);

$headurl_grep = preg_replace('/^([^\:]+\:\/\/[^\/]+)\:\d+/', '$1', $headurl);	// remove port.
//if(!empty($headurl_grep)) { $headurl = $headurl_grep; }	// Error occur if Portforwarding!! 
$headurl = preg_replace('/\/index\.html$/i', '', $headurl);	// If the path contains index.html, remove it.
$url = $headurl. '/bin/fasta.php';
$request_content_base = [
	"prm_fa_chr"	=> $prm_chr,
	"prm_fa_s"	=> $prm_s,
	"prm_fa_e"	=> $prm_e,
	"prm_fa_tgt"	=> $prm_tgt,
	"prm_fa_flk"	=> $prm_fa_flk,
	"prm_fa_qual"	=> $prm_qual,
	"prm_fa_dp"	=> $prm_dp,
	"prm_fa_list"	=> $prm_list,
	"prm_fa_name"	=> $prm_name,
	"prm_fa_nameS"	=> $prm_nameS,
	"prm_fa_ref"	=> $prm_ref,
	"prm_fa_width"	=> $prm_width,
	"prm_fa_avd"	=> $prm_avd,
	"prm_fa_p3prm"	=> "",
	"prm_fa_Ns"	=> $prm_Ns,
	"prm_fa_DN"	=> $prm_DN,
	"prm_type"	=> $prm_type,
	"prm_phpflg"	=> $php_flg,
	"prm_numthread"	=> $prm_numthread
];

// 複数URLを同時に取得する
$timeout = 0;	// 0だと無制限
$mh = curl_multi_init();
$chs = array();
for ($i=0;$i<$prm_numthread;$i++) {
	$ch = curl_init();
	$chs[] = $ch;
	$request_content = $request_content_base;	// deep copy(not reference copy).
	$request_content["pid"] = $i;
	curl_setopt_array($ch, [
		CURLOPT_URL	=> $url,
		CURLOPT_RETURNTRANSFER	=> 1,
		CURLOPT_POST	=> true,
		CURLOPT_POSTFIELDS	=> http_build_query($request_content),
		CURLOPT_FAILONERROR	=> 1,
		CURLOPT_FOLLOWLOCATION	=> 1,
		CURLOPT_MAXREDIRS	=> 3,

		//SSL証明書を無視
		CURLOPT_SSL_VERIFYPEER	=> false,
		CURLOPT_SSL_VERIFYHOST	=> false,
	]);
	if(!empty($_SERVER['PHP_AUTH_USER'])) {
		curl_setopt($ch, CURLOPT_USERPWD, $_SERVER['PHP_AUTH_USER']. ":".  $_SERVER['PHP_AUTH_PW']);
	}

	//タイムアウト
	if ($timeout){ curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); }

	curl_multi_add_handle($mh, $ch);
}

//URLを取得
//すべて取得するまでループ
$active = null;
do {
    $mrc = curl_multi_exec($mh,$active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
do {
    curl_multi_exec($mh, $active);
    curl_multi_select($mh);
} while ($active > 0);
if ($mrc != CURLM_OK) {
    echo '読み込みエラーが発生しました:'.$mrc;
}
//ソースコードを取得
$res = array();
$chslen = count($chs);
for($i=0; $i<$chslen; $i++) {
    if (($err = curl_error($chs[$i])) == '') {
        $res[$i] = curl_multi_getcontent($chs[$i]);
    } else {
        //echo '取得に失敗しました:'.$chs[$i].'<br />';
    }
    curl_multi_remove_handle($mh, $chs[$i]);
    curl_close($chs[$i]);
}
curl_multi_close($mh);

echo json_encode($res);

function returnError($str){
    echo $str;
}
function _stopError($str){
    echo $str;
    exit;
}
