<?php
	/*   
	 Copyright (c) 2012, Paul G Talaga
	 All rights reserved.
	 
	 Redistribution and use in source and binary forms, with or without
	 modification, are permitted provided that the following conditions are met:
	 * Redistributions of source code must retain the above copyright
	 notice, this list of conditions and the following disclaimer.
	 * Redistributions in binary form must reproduce the above copyright
	 notice, this list of conditions and the following disclaimer in the
	 documentation and/or other materials provided with the distribution.
	 
	 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
	 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
	 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
	 DISCLAIMED. IN NO EVENT SHALL Paul G Talaga BE LIABLE FOR ANY
	 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	 */

	/*
		Background Database Caller
		Given a queue of database statements saved via file, send them out every second.
		
		APC is not used as there is no way to start a script and garuntee it exists in the same process as the caller
		and thus see the same data.  Additionally memory is not shared between processes/threads.
		
		We use 3 files in /tmp , toUse.txt which contains a single digit, and queries<digit>.txt.  toUse acts as a switch so clients can write
		to the file while the cleaner executes the queries in the other digit files.  On completion it changes toUse.txt.
	*/
	include('includes/configure.php');
    global $link;
    
    $toUse = '/tmp/toUse.txt';
    $queryprefix = '/tmp/queries';
    
    // connect to database
    $link = mysql_pconnect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD);
    if(!$link){die("Can't connect to $server !\n");}
    if ($link) mysql_select_db(DB_DATABASE,$link);
    
    $queries = array();
    
    // 
    $num_files = 3;
    $i = 0; // we always clean i-1, so many query files can exist and we clear the oldest
    while(1){
        $to_clean = ($i + $num_files + 1) % $num_files;
        echo "i: $i toclean: $to_clean\n";
        $clean = fopen($toUse, 'w');
        fwrite($clean,$i);
        fclose($clean);
        $min_write = PHP_INT_MAX;
        // do queries
        $handle = @fopen($queryprefix . $i . '.txt', "r");
        if ($handle) {
            while (($buffer = fgets($handle, 4096)) !== false) {
                $q = unserialize(rtrim($buffer));
                $query = $q['query'];
                if($q['now'] < $min_write)$min_write = $q['now']; // keep track of the oldest query time
                if(strlen($query) > 0)$queries[] = $query;
            }
            if(count($queries) > 0)executeQueries($queries,$min_write);
            $queries = array();
            if (!feof($handle)) {
                echo "Error: unexpected fgets() fail\n";
            }
            fclose($handle);
        }
        // clear file
        $handle = @fopen($queryprefix . $i . '.txt', "w");
        fclose($handle);
        
        $i++;
        $i = $i % $num_files;
        usleep(200000);
    }
    
function executeQueries(&$queries,$min_write){
    $tosend = serialize(array('min_write' => $min_write, 'queries' => $queries,'client' => TENT_CLIENT_ID));
    $tosend = gzcompress($tosend);
    // send it!
    echo "Sent \n";
    $response = url_request('POST','http://' . TENT_CENTRAL_HTTP . '/remote-sql-access.php',array('r' => $tosend));
    echo $response['content'];
    echo "Back\n";
}    
    
function executeQuery($query){
    global $link;
    $return = mysql_query($query, $link) or tep_db_error($query . ' (write request)', mysql_errno(), mysql_error());
    echo "Returned $return\n";
    return $return;
}

  function url_request($type,$url, $data, $headers = '') {
      // Convert the data array into URL Parameters like a=b&foo=bar etc.
      $data = http_build_query($data);
   
      // parse the given URL
      $url = parse_url($url);
   
      if ($url['scheme'] != 'http') { 
          die('Error: Only HTTP request are supported !');
      }
      // extract host and path:
      $host = $url['host'];
      $path = $url['path'] ;
   
      // open a socket connection on port 80 - timeout: 30 sec
      $fp = fsockopen($host, 80, $errno, $errstr, 30);
   
      if ($fp){
   
          // send the request headers:
          if($type == 'POST'){
            fputs($fp, "POST $path HTTP/1.1\r\n");
          }else{
            fputs($fp, "GET $path HTTP/1.1\r\n");
          }
          fputs($fp, "Host: $host\r\n");
   
          if ($headers != ''){
              foreach($headers as $k => $d){
                if($k != 'Content-Length'){
                fputs($fp, "$k: $d\r\n");}
              }
          }
          if($type == 'POST'){
            fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
            fputs($fp, "Content-length: ". strlen($data) ."\r\n");
            fputs($fp, "Connection: close\r\n\r\n");
            fputs($fp, $data);
          }
   
          $result = ''; 
          while(!feof($fp)) {
              // receive the results of the request
              $result .= fgets($fp, 128);
          }
      }
      else { 
          return array(
              'status' => 'err', 
              'error' => "$errstr ($errno)"
          );
      }
   
      // close the socket connection:
      fclose($fp);
   
      // split the result header from the content
      $result = explode("\r\n\r\n", $result, 2);
   
      $header = isset($result[0]) ? $result[0] : '';
      $content = isset($result[1]) ? $result[1] : '';
   
      // return as structured array:
      return array(
          'status' => 'ok',
          'header' => $header,
          'content' => $content
      );
  }

?>
