#!/usr/bin/perl
require 'cgi_common.req';
 $SIG{__WARN__}=sub {
          $datetype=1;
          &get_date;
          plog2("At $date: Main prog returned - $@")};

# Counter directory

$cntdir="../counters/";
$qfile="./queries/data.txt";
$cfile='total';
&Inccounter;


eval {

use Socket;

 %oq=512;

$loging="1";


    ($IP)=($ENV{"REMOTE_ADDR"}=~s/\.//g);
    srand($$+$IP);
    $rndnum=int rand(1000000000);

$time0=0;

sub printhead {

$msg1= <<"(HEAD_BLOCK)";
<HTML>
<HEAD>
<TITLE> VHS.ru </TITLE>
<LINK rel="stylesheet" href="/vhs.css" type="text/css">
</HEAD>

<BODY background="/images/bg_5.jpg" BGCOLOR="#81ACF2" marginwidth=0 marginheight=0 topmargin=0 leftmargin=0 text="#000000">
<TABLE valign="top" width="790" HEIGHT="120" cellspacing=0 cellpadding=0 rules="0" frame="0" border="0">
<TR><TD WIDTH="110" HEIGHT="120" background="" align="left" valign="top"><IMG SRC="/images/001.jpg" BORDER=0 ALT=""></TD>
<TD WIDTH="470" HEIGHT="120" background="/images/002.jpg" align="center" valign="middle">
<a href="/advert/click.php3"><img src="/advert/phpads.php3?what=468x60&n=ban1" border="0"></a>
</TD><TD WIDTH="210" HEIGHT="120" align="left" valign="top"><IMG SRC="/images/logos.gif" BORDER=0 ALT=""></TD>
</TR>
<tr><td colspan="3">
<p align="center">
<br><br><br>
<b>СКАНИРУЮ МАГАЗИНЫ РУНЕТА НА ПРЕДМЕТ ВАШЕГО ЗАПРОСА<br>
ПОДОЖДИТЕ ПОЖАЛУЙСТА...</b>
</p>
</td></tr>
</TABLE>


    
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->
<!-- Just to flush data throught the mirror system and proxies    -->

<pre><p align="left">


(HEAD_BLOCK)


# printf ("$msg1\n");
# Тут вставляется шапка:
smartcat(undef, '/home/virtual/ceoinfo.ru/www/html/header_3.inc');

print "<br>";

#smartcat(undef, '/home/virtual/vhs.ru/www/html/left.html');

print "<br><br><center><b>СКАНИРУЮ МАГАЗИНЫ РУНЕТА НА ПРЕДМЕТ ВАШЕГО ЗАПРОСА<br>ПОДОЖДИТЕ ПОЖАЛУЙСТА...</b></center><br><br>";

$|=1;

};

sub printfoot {


$msg2= <<"(FOOT_BLOCK)";

<div align="left"><table border="0" cellpadding="0" cellspacing="0" align="left"
    width="790">
      <tr>
        <td align="center"><p align="center">Идет подготовка данных....</td>
      </tr>
    </table>
	
    </div>
</body>
</html>

<META HTTP-EQUIV="Refresh" CONTENT="2; URL=show.cgi?search=$snum&start=0">

(FOOT_BLOCK)

$msg3= <<"(FOOT1_BLOCK)";

<div align="left"><table border="0" cellpadding="0" cellspacing="0"
    width="100%">
      <tr>
        <td align="center"><p align="center"><small><small>- - -</small></small></td>
      </tr>
    </table>
    </div>
</body>
</html>

<META HTTP-EQUIV="Refresh" CONTENT="2; URL=show.cgi?search=$snum&start=0&noname=1">

(FOOT1_BLOCK)

if($noname == 1) {
 print "$msg3\n";

} else {
 print "$msg2\n";



};

$|=1;


};
	    print("Pragma: no-cache\r\n");
	    print("Cache: no-cache\r\n");
#            print("Connection: Close\r\n");
#            print("Refresh: 0; URL=http://booksearch.ru/show4.cgi?search=$rndnum\n");
            print("Content-type: text/html; charset=windows-1251\n\n");
            &printhead;

#########################################
# Get the input
   if ($ENV{'REQUEST_METHOD'} eq 'GET') {
        $buffer = $ENV{'QUERY_STRING'};
    }
    else {
       read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    }

# Split the name-value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
   ($name, $value) = split(/=/, $pair);
   # Un-Webify plus signs and %-encoding
   $value2=$value;
   $value2 =~ tr/+/ /;
   $value2 =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
   $value2 =~ s/<!--(.|\n)*-->//g;
   if($name eq 'string') {$string2=$value2;};
   if($name eq 'author') {$author2=$value2;};
   $form{$name} = $value;
}

if(defined($form{'noname'})) {$noname=1; };

$timehold=$form{'timeout'};
if ($timehold eq '') { $timehold=5; };

#Вставляем сюда свои партнерские ID
if((defined($form{'Ozon'})) && ($form{'Ozon'} eq '1')) { $form{'Ozon'}="ceoinfo";};
if((defined($form{'Bolero'})) && ($form{'Bolero'} eq '1')) { $form{'Bolero'}="ceoinfo"; };
if((defined($form{'Colibri'})) && ($form{'Colibri'} eq '1')) { $form{'Colibri'}="949"; };
if((defined($form{'Biblion'})) && ($form{'Biblion'} eq '1')) { $form{'Biblion'}=""; };
if((defined($form{'Arcadia'})) && ($form{'Arcadia'} eq '1')) { $form{'Arcadia'}=""; };
if((defined($form{'Amazon'})) && ($form{'Amazon'} eq '1')) { $form{'Amazon'}="splane";};

#########################################
#
# Debug zone
#
#$form{'Yandex'}=1;
#   $string=$form{'string'};
#   $string =~ s/%20/+/;
#   $string =~ tr/ /+/;
#  $endc=chr(255);
#   $string =~ s/([$startc-$endc])/"%".uc(unpack("H2",($1)))/eg;
#   $string =uc $string;

#Лог для журнала
$datetype=4;
&get_date;
plog("Start - $date");

#########################################
# Variables
#
# Ozon  1

#$oq - переменная по коророй делается запрос (URL)
#$oqs - ссылка на конкретный поисковик
#$met - метод запроса

$oq{'Ozon'}="http://www.ozon.ru/Searchresult.cfm?ent=2\&forsale=1\&Str=$string2\&AuthorStr=$form{'author'}";
$oqs{'Ozon'}="http://www.ozon.ru/Searchresult.cfm?ent=2\&forsale=1\&Str=$string2\&AuthorStr=$author2\&partner=$form{'Ozon'}";
$met{'Ozon'}="GET";
#
# Bolero  2
#$oq{'Bolero'}="http://www.bolero.ru/cgi-bin/search.cgi?sea_enh=1\&type=video\&root=1\&name=$form{'string'}\&author=$form{'author'}\&res=catlist";
#$oqs{'Bolero'}="http://www.bolero.ru/cgi-bin/search.cgi?sea_enh=1\&type=video\&root=1\&name=$string2\&author=$author2\&res=catlist";
$oq{'Bolero'}="http://www.bolero.ru/search?view_type=1\&type=book\&sea_key=$form{'string'}\&spec=\&author=$form{'author'}\&mannm=\&series=\&ISBN=\&year_l=\&year_h=\&pcid=1\&search.x=0\&search.y=0";
$oqs{'Bolero'}="http://www.bolero.ru/search?view_type=1\&type=book\&sea_key=$string2\&spec=\&author=$author2\&mannm=\&series=\&ISBN=\&year_l=\&year_h=\&pcid=1\&search.x=0\&search.y=0";

#
# 24x7  3
$oq{'24x7'}="http://www.24x7.ru/search/booksearch/searchresults.jsp?page_size=25\&bn_options=CONTAIN\&ba_options=USUAL\&sort_by=m_list_price\&book_title=$form{'string'}\&book_author=$form{'author'}\&page_number=0";
$oqs{'24x7'}="http://www.24x7.ru/search/booksearch/searchresults.jsp?page_size=25\&bn_options=CONTAIN\&ba_options=USUAL\&sort_by=m_list_price\&book_title=".$form{'string'}."\&book_author=$author2\&page_number=0";
#

# Colibri  4
$oq{'Colibri'}="http://www.colibri.ru/adsearch.asp";
$rqs{'Colibri'}="CodOfRP=0\&NameOfBook=$form{'string'}\&AutorOfBook=$form{'author'}\&TypeSort=1\&search=1\&addpic=1";
$oqs{'Colibri'}="http://www.colibri.ru/adsearch.asp?CodOfRP=0\&NameOfBook=$string2\&AutorOfBook=$author2\&TypeSort=1\&search=1\&addpic=1";
$met{'Colibri'}="POST";
#
# Biblion  5
$oq{'Biblion'}="http://www.biblion.ru/books/xt_find.asp?kind=-1\&Mode=new\&title=$form{'string'}\&author=$form{'author'}\&rpp=20";
$oqs{'Biblion'}="http://www.biblion.ru/books/xt_find.asp?kind=-1\&Mode=new\&title=$string2\&author=$author2\&rpp=20";
#
# Boomerang 6
$oq{'Boomerang'}="http://www.boomerang.ru/book/search.asp";
$rqs{'Boomerang'}="otdel=books\&title=$form{'string'}\&author=$form{'author'}";
$oqs{'Boomerang'}="otdel=books\&title=$string2\&author=$form{'author'}";
$met{'Boomerang'}="POST";
#
# Arcadia 7
$oq{'Arcadia'}="http://www.arcadia.ru/books/booklist.asp?SearchOption=Advanced\&strBookName=$form{'string'}\&lngAvailability=3000\&lngOrder=3\&strAuthorLastName=$form{'author'}";
$oqs{'Arcadia'}="http://www.arcadia.ru/books/booklist.asp?SearchOption=Advanced\&strBookName=$string2\&lngAvailability=3000\&lngOrder=3\&strAuthorLastName=$author2";
#
# Amazon 8
$oq{'Amazon'}="http://www.amazon.com/exec/obidos/search-handle-form";
$rqs{'Amazon'}="index=books\&field-keywords=$form{'string'} $form{'author'}";
$oqs{'Amazon'}="index=books\&field-keywords=$string2 $author2";
$met{'Amazon'}="POST";

###############################
# Process Ozon

$prtid="";
if(defined($form{'Ozon'})) {

  $prtid=$form{'Ozon'};
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос Ozon      ";
  &statline;

  $method=$met{'Ozon'};
  require "./ms_ozon.pm";
  &statline_end;

$|=1;

};

###############################
# Process Bolero

$prtid="";
if(defined($form{'Bolero'})) {

  $prtid=$form{'Bolero'};
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос Bolero    ";
  &statline;

  $method=$met{'Bolero'};
  require "./ms_bolero.pm";

  &statline_end;

$|=1;



};


###############################
# Process 24x7


if($form{'24x7'} == 1) {
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос 24x7      ";
  &statline;

  $method=$met{'24x7'};
  require "./ms_24x7.pm";

  &statline_end;

$|=1;

};

###############################
# Process Colibri


$prtid="";
if(defined($form{'Colibri'})) {

  $prtid=$form{'Colibri'};
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос Colibri   ";
  &statline;

  $method=$met{'Colibri'};
  $rqstr=$rqs{'Colibri'};
  require "./ms_colibri.pm";

  &statline_end;

$|=1;

};


###############################
# Process Biblion


$prtid="";
if(defined($form{'Biblion'})) {

  $prtid=$form{'Biblion'};
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос Biblion   ";
  &statline;

  $method=$met{'Biblion'};
  require "./ms_biblion.pm";

  &statline_end;

$|=1;

};


###############################
# Process Boomerang

$prtid="";
if(defined($form{'Boomerang'})) {

  $prtid=$form{'Boomerang'};
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос Boomerang ";
  &statline;

  $method=$met{'Boomerang'};
  $rqstr=$rqs{'Boomerang'};
  require "./ms_boomerang.pm";

  &statline_end;

$|=1;

};

###############################
# Process Arcadia


$prtid="";
if(defined($form{'Arcadia'})) {

  $prtid=$form{'Arcadia'};
  $statmsg="Arcadia (магазин закрыт)";
  &statline;

  $method=$met{'Arcadia'};
  require "./ms_arcadia.pm";

  &statline_end;

$|=1;

};

###############################
# Process Amazon

$prtid="";
if(defined($form{'Amazon'})) {

  $prtid=$form{'Amazon'};
  $statmsg="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Опрос Amazon   ";
  &statline;

  $method=$met{'Amazon'};
  $rqstr=$rqs{'Amazon'};
  require "./ms_amazon.pm";
  $method="";

  &statline_end;

$|=1;

};

$statmsg="<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Обработка и выдача результата... ";
&statline;
print "- (Полное время опроса $time0 сек.)</p></pre><br>\n";

#### Delete old temporary files #############
$workdir="./searches/";
$filekeeptime="0.021";
opendir (WORK, $workdir);
@catfiles=readdir(WORK);
closedir WORK;

foreach $diritem (@catfiles) {
  if(($diritem eq ".") || ($diritem eq "..")) { next;};
  $dfile=$workdir.$diritem;
  $a=(-C $dfile);
  if($a > $filekeeptime) { unlink ($dfile); };
};

#### Create temporary file ##################

$snum=$rndnum;
$sfile=">".$workdir.$snum.".txt";
$|=1;
$qbooks=0;
open (tfile,$sfile);
foreach $tmpsortline (sort @showline2) {
   print (tfile "$tmpsortline");
   $qbooks+=1;
};
close (tfile);

open (tfile,$qfile);
@qrs=<tfile>;
close (tfile);
unshift @qrs, ("$string2, $author2, $qbooks, $ENV{'HTTP_REFERER'}\n");
$tmp1=pop (@qrs);
$qfile=">".$qfile;

open (tfile,$qfile);
foreach $tmpline (@qrs) {
   print (tfile "$tmpline");
};
close (tfile);


### Print footer and go to show results #####

    &printfoot;
    exit;


sub error { 
    exit;
}

sub statline{
    print "\t$statmsg\t";
};

sub statline_end{
    $time3=$time2-$time1;
    $time1=$time2=0;
    $time0=$time0+$time3;
    if($iostat eq '') {
      print(" \t- время опроса $time3 сек.<br>\n");
    } else {
      print("\t$iostat.<br>\n");
    };
#    print <<"(STATLINEEND_BLOCK)";
# - время опроса   $time3  сек.</br>
#
#(STATLINEEND_BLOCK)
#  

};

sub IOsocket{
         close (SOCK_1);
         $iostat="";
### Wrap own error control #############
         $SIG{ALRM}= sub { plog("Not connected - $statmsg"); return 1};
         $SIG{PIPE}= sub { plog("Pipe error - $statmsg"); die };
         $SIG{IO}= sub { plog("IO error - $statmsg"); 1 };
         if ($method eq "") { $method = "GET"; };
         $lqry=$lpath;
reloc:
         $lqry=substr($lqry,7,300);
         $rhost=substr($lqry,0,index($lqry,"\/"));
         $rpath=substr($lqry,index($lqry,"\/"),300);
         alarm 8;
         if (not socket(SOCK_1, PF_INET, SOCK_STREAM, getprotobyname('http'))) { 
              plog ("Sock not created - $statmsg");
              alarm 0;
              return 1;
         };
#         $tmpa= inet_aton($rhost);

           $tmpa= inet_aton($rhost);

         plog("IPAddr - $tmpa");
         if( not $tmpa) {
              alarm 0;
              $iostat=" - связь не установлена";
              $|=1;
              return 1;
         };
	 $sin = sockaddr_in(80, $tmpa);
	 if(  not connect(SOCK_1, $sin)) {
              plog("Not connected - $statmsg");
#              print "<!-- last query $lqry, Socket not opened -->";
              $iostat=" - связь не установлена";
              alarm 0;
              $|=1;
              return 1;
         };
	$offset = 0;
	$buff ="$method $rpath HTTP/1.0\n";
        $biff.="Referer: $rhost\n";
	$buff.="Host: $rhost\n";
#        $buff.="Cookie: ASPSESSIONIDGQGGGGAR=NAHMCJHAPOFBLLKPABNALPOA;\n";
        if ($method eq "GET") {
           $buff.="User-Agent: $ENV{'HTTP_USER_AGENT'}\n\n";
        } else {
        $buff.="Accept: text/html\n";
        $buff.="User-Agent: $ENV{'HTTP_USER_AGENT'}\n";
        $buff.="Content-type: application/x-www-form-urlencoded\n";
        $buff.="Content-length: ".length($rqstr)."\n";
        $buff.="Connection: close\n\n";
        $buff.=$rqstr;
        };
	$len = length($buff);
	while($len) {
		$written = syswrite(SOCK_1,$buff,$len,$offset);
		$len -= $written;
		$offset += $written;
	}
        alarm 0;
        print "<img src=\"images/prog_block.gif\" width=\"6\" height=\"12\" vspace=\"0\" hspace=\"0\">";

############################ Timer zone ###############
        $counter=0;
        local $SIG{ALRM}=sub { 
              $counter=$counter+1;
              print "<img src=\"images/prog_block.gif\" width=\"6\" height=\"12\" vspace=\"0\" hspace=\"0\">";
              $|=1;
              if($counter > $timehold) {
                 close (SOCK_1);
                 plog("Timeout - $statmsg");
                 $iostat="- истекло время ожидания ответа";
              } else {
                 alarm 2;
              };
        1;
        };
        alarm 2;

        undef @output;
        @output = <SOCK_1>;
    open (file2,">./temp/test2.txt");

    foreach $out (@output) {
      printf (file2 "$out");
    };

    close (file2);

    open (file,">./temp/bufer.txt");

      printf (file "$buff\n");

    close (file);

#print "<!-- @output[0] -->\n";
        if ($output[0] =~ / 30/) {
          foreach $oline (@output) {
             if (substr($oline,0,10) eq 'Location: ') {
                $lqry=substr($oline,10,300);
             };
          };
############################ Timer zone - restore ###############
        local $SIG{ALRM}=sub {};
        alarm 0;
          close (SOCK_1);
#print "<!-- $lqry -->\n";
        $lqry=~ s/:80//;
        $lqry=~ s/\n//;
        $lqry=~ s/\r//;
        goto reloc;
        };
        local $SIG{ALRM}=sub {};
        alarm 0;
        close (SOCK_1);    
        return 1;
}


sub plog ($) {
 if($loging eq '1') {
   $logfile=">>./temp/slog.txt";
   $mess=$_[0];
   open (lfile,$logfile);
   print (lfile "$mess\n");
   close (lfile);
 };
};

sub get_date {

        @days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
        @months = ('January','February','March','April','May','June','July','August','September','October','November','December');

	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

	$mon_num = $mon+1;
	$savehour = $hour;
	$hour = "0$hour" if ($hour < 10);
	$min = "0$min" if ($min < 10);
	$sec = "0$sec" if ($sec < 10);
	$saveyear = ($year % 100);
	$year = 1900 + $year;

	if ($datetype == 1) {
		$date = "$days[$wday], $months[$mon] $mday, $year at $hour\:$min\:$sec";
	} elsif ($datetype == 2) {
		$date = "$months[$mon] $mday, $year at $hour\:$min\:$sec";
	} elsif ($datetype == 3) {
		$xxx3 = substr($months[$mon],1,3);
		$date = "$xxx3\. $mday, $year - $hour\:$min\:$sec";
	} elsif ($datetype == 4) {
		$mon_num = "0$mon_num" if ($mon_num < 10);
		$mday = "0$mday" if ($mday < 10);
		$saveyear = "0$saveyear" if ($saveyear < 10);
		$date = "$mon_num/$mday/$saveyear - $hour\:$min\:$sec";
	}

        return 1;
};

};

if ($@) { plog2("Main prog returned - $@");};



sub plog2 ($) {

   $logfile=">>./temp/slog.txt";
   $mess=$_[0];
   open (lfile,$logfile);
   printf (lfile "$mess\n");
   close (lfile);

};


sub Inccounter {

   $ffile=$cntdir.$cfile;
   open (lfile1,$ffile);
    $curr=<lfile1>;
   close (lfile1);
   $ffile=">".$cntdir.$cfile;
    $curr=$curr+1;
   open (lfile1,$ffile);
    print (lfile1 "$curr\n");
   close (lfile1);

};

