<?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.
	 * Neither the name of the <organization> nor the
	 names of its contributors may be used to endorse or promote products
	 derived from this software without specific prior written permission.
	 
	 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 <COPYRIGHT HOLDER> 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.
	 */
  include('includes/configure.php');
  // responds to requests from edge servers
  // TODO: add authentication!
  //phpinfo();
  if(!isset($_POST['r']))die; 
  $request = $_POST['r'];
  $request = gzuncompress($request);
  list($rUri,$headers,$rtype,$postvars,$session) = unserialize($request);  
  // Connect to Memcache and set session info
  $return = true;
  $servers = explode(',', MEMCACHE_SERVERS);
  $memcache = new MemcachePool();
  foreach($servers as $sv){
     list($s,$p) = explode(':',$sv);
     $ret = $memcache->addServer($s,$p);
      $return = $return && $ret;
            //echo "Server $s, port $p ok?$ret\n";
   } 
   if(!$return){error_log('could not connect to memcache');die('Could not connect to memcache');}
   
   
   foreach($session as $s){
     session_decode($s['value']);
   }
   
 
  // 
  $cookie = $headers['Cookie'];  
  if($rtype == 'GET'){
    $opts = array(
          'http' =>array(
            'method' =>$rtype,
            'header' => "Cookie: $cookie\r\n"));
    $context = stream_context_create($opts);
    $reply['content'] = file_get_contents('http://' .$_SERVER['SERVER_ADDR'] . $rUri, false,$context);
    $reply['header'] = '';
  }else{
    $reply = url_request($rtype,'http://' .$_SERVER['SERVER_ADDR'] . $rUri,$postvars,$headers);
  }
  $newsession = array();
  $debug = '';
  foreach($session as $s){
     $newsession[] = array('key' => $s['key'], 'value' => $memcache->get($s['key'])); 
  }
   $return = gzcompress(serialize(array($reply['content'],  $reply['header'] ,$newsession)));
 
  echo $return;
  exit();
  
  //////////////////////////////////////////////////////////////////////////////
  
  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'];
      if(isset($url['query'])){
        $path = $url['path'] . '?' . $url['query'];
      }else{
        $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
      );
  }

?>
