<?php
/*
* search.php
* http://tasuke.dna.affrc.go.jp/
*
* Author: Ryutaro Itoh
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences   
*
*/

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

//////////////////////////////////  Connecting with DB
if( !$conn = new mysqli($host, $user, $pswd, $db)) {
error_log("Connection failed.\n");
exit;
}

////////////////////////////////////////////////////////// Parameters
(isset($_GET['prm_keyword']) && !empty($_GET['prm_keyword'])) ? $prm_keyword=$_GET['prm_keyword'] : returnError("Error");
(isset($_GET['prm_chr']) && !empty($_GET['prm_chr'])) ? $prm_chr=$_GET['prm_chr'] : returnError("Error");
(isset($_GET['prm_zoom']) && !empty($_GET['prm_zoom'])) ? $prm_zoom=$_GET['prm_zoom'] : returnError("Error");

///Validation///
//_pregMatch($prm_keyword);
if(preg_match("/<script>/",$prm_keyword)) {
        $errmsg = "Error: Input Parameter Invalid!";
        echo $errmsg;
        exit;
}
if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$prm_Zoom)) {
        $prm_Zoom = "1k";
}
if(!_validate_chrs($conn,$prm_chr)){_stopError("||Invalid value");}
///////////////////////////////////////////////////////// Searching locus id
$stmt = $conn->stmt_init();
$prequety="show columns from sys_track where Field = 'note'";
$stmt->prepare($prequety);
$stmt->execute();
$stmt->store_result();
$flag = $stmt->num_rows();
$stmt->free_result();
$stmt->close();
$stmt = $conn->stmt_init();

if($flag > 0){
    $param1=preg_replace('/[ ]/', '* +', "+".$prm_keyword);
    $param1=$param1."*";
    $param2="%".$prm_keyword."%";
    $query = "SELECT id,pos,end,chr,note from sys_track where (parent=1 and match(note) against( ? in boolean mode)) OR ".
             "(id like ? and parent=1) OR ".
             "(name like ? and parent=1) ".
             "ORDER BY chr,pos";
//    $query = "SELECT id,pos,end,chr,note from sys_track where parent=1 and match(note) against( ? in boolean mode) 
//                union SELECT id,pos,end,chr,note from sys_track where id like ? and parent=1 order by chr,pos";
    $rtnString="";
    $stmtflag=0;
    $num=0;
    $rowcount=0;
    $stmt->prepare($query);
    $stmt->bind_param("sss", $param1,$param2, $param2);
//    $stmt->bind_param("ss", $param1,$param2); 
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($row0,$row1,$row2,$row3,$row4);
    $num = $stmt->num_rows();
    while ($stmt->fetch()) {
        $rtnString.= $row0."|".$row1."|".$row2."|".$num."|".$row3."|".$row4."~";
        $stmtflag=1;
        $rowcount++;
        if($rowcount >= 1000){
            break;
        }
    }
    $stmt->free_result();
    
    if($stmtflag==0){
        $replace_pos=0;
        $rowcount=0;
        $param2="";
        $key_len=strlen($prm_keyword);
        if($key_len>10){$key_len=10;}
        for($i=0; $i < $key_len; $i++){
            $strkey=substr($prm_keyword, $replace_pos, 1);
            if(preg_match('/\D/', $strkey)){
                $rps_keyword=substr_replace($prm_keyword, "%", $replace_pos, 1 );
                $param2="%".$rps_keyword."%";
                $stmt->bind_param("ss", $param1,$param2); 
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($row0,$row1,$row2,$row3,$row4);
                $num = $stmt->num_rows();
                while ($stmt->fetch()) {
                    $rtnString.= $row0."|".$row1."|".$row2."|".$num."|".$row3."|".$row4."~";
                    $stmtflag=2;
                    $rowcount++;
                    if($rowcount >= 1000){
                        break;
                    }
                }
                $stmt->free_result();
                if($stmtflag==2){
                    break;
                }
            }
            $replace_pos++;
        }
    }
    if($num < 1){
        $rtnString= "false|false2|false|false|false|~";
    }
}else{
    $param1="%".$prm_keyword."%";
    $query = "SELECT id, pos, end, chr, '' FROM sys_track WHERE id LIKE ? and parent=1 order by chr, pos";
    $rtnString="";
    $stmtflag=0;
    $num=0;
    $rowcount=0;
    $stmt->prepare($query);
    $stmt->bind_param("s", $param1); 
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($row0,$row1,$row2,$row3,$row4);
    $num = $stmt->num_rows();
    while ($stmt->fetch()) {
        $rtnString.= $row0."|".$row1."|".$row2."|".$num."|".$row3."|".$row4."~";
        $stmtflag=1;
        $rowcount++;
        if($rowcount >= 1000){
            break;
        }
    }
    $stmt->free_result();
    
    if($stmtflag==0){
        $replace_pos=0;
        $rowcount=0;
        $key_len=strlen($prm_keyword);
        if($key_len>10){$key_len=10;}
        for($i=0; $i < $key_len; $i++){
            $strkey=substr($prm_keyword, $replace_pos, 1);
            if(preg_match('/\D/', $strkey)){
                $rps_keyword=substr_replace($prm_keyword, "%", $replace_pos, 1 );
                $param1="%".$rps_keyword."%";
                $stmt->bind_param("s", $param1);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($row0,$row1,$row2,$row3,$row4);
                $num = $stmt->num_rows();
                while ($stmt->fetch()) {
                    $rtnString.= $row0."|".$row1."|".$row2."|".$num."|".$row3."|".$row4."~";
                    $stmtflag=2;
                    $rowcount++;
                    if($rowcount >= 1000){
                        break;
                    }
                }
                $stmt->free_result();
                if($stmtflag==2){
                    break;
                }
             }
             $replace_pos++;
        }
        if($stmtflag!=2){
            $rtnString="||||";
        }
    }
}
$stmt->close();
mysqli_close($conn);
$rtnString=rtrim($rtnString, "~");
echo $rtnString;

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

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

function _cvtZoom($str) {
preg_match("/^[0-9]+/", $str, $r1);
preg_match('/[b,k]$/', $str, $r2);
$v=$r1[0];
if($r2[0] == "b"){
    $r=1*(int)$v;
} else {
    $r=1000*(int)$v;
}
return (int)$r;
}

function _validate_chrs($conn, $prm_Chr){
    $flag = false;
    $query = "select seq from sys_chromosome where id=? limit 1";
    $stmt = $conn->stmt_init();
    $stmt->prepare($query);
    $stmt->bind_param("s", $prm_Chr);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($row0);
    while ($stmt->fetch()) {
        $flag = true;
    }
    $stmt->free_result();
    $stmt->close();
    if($flag){
       return true;
    }else{
       return false;
    }
}

?>

