Location: PHPKode > projects > Esvon Personals > esvon-personals/inc/pages/order.php
<?php

// --------------------------------------------------------------------------
//
// Esvon Classifieds v.4.0
// Copyright(C), Esvon LTD, 2001-2010, All Rights Reserved.
// E-mail: hide@address.com
//
// All forms of reproduction, including, but not limited to, internet posting, 
// printing, e-mailing, faxing and recording are strictly prohibited.
// One license required per site running Esvon Classifieds. 
// To obtain a license for using Esvon Classifieds, please register at
// http://www.esvon.com/pg/products/p_classifieds/
//
// --------------------------------------------------------------------------

if(!defined('SITE_PATH')) die('Access Denied');

// if(!isset($_REQUEST['pay_method'])) $_REQUEST['pay_method'] = '2checkout';

$o_type = (string)$_REQUEST['o_type'];
if($o_type!='SUB' && !hwSessionGetVar('u_ac_pp')) CheckLoggedIn();

$cid = (int)$_REQUEST['cid'];
if($_GET['pg']=='priceplans'){
  
  if($o_type != 'SUB') {
    $o_type = 'FEE';
    if(EN_PP_CAT && !$cid){
      header('Location: index.php?page=add&cid='.$cid);
      exit;
    }
  }
  
  ShowPayPlansForm();
  return;
}

$id = (int)$_REQUEST['id'];
if(!$id){
  $o_type = 'SUB';
  $id = (int)hwSessionGetVar('userid');
  $ql = 'SELECT email,exp_date,hw_pay_plan,exp_date<'.SQL_NOW.' FROM '.TBL_USER.' WHERE id='.$id;
}
else{

  /*if(hwSessionGetVar('exp_date') < HW_TIME){
    header('Location: index.php?page=account&pg=payment');
    exit;
  }*/

  $o_type = 'FEE';
  $ql = 'SELECT '.$TITLE_FIELD.',exp_date,hw_pay_plan,exp_date<'.SQL_NOW.' FROM '.TBL_AD." WHERE link_id='$id' AND catid='$cid'";
}

list($l_title,$exp_date,$hw_pay_plan,$hw_expired) = $db->one_row($ql);
if(!$l_title) die('Invalid request');

$P_TERMS = array();
if(!is_array($_POST['term'])) unset($_POST['term']);
if($_POST['term']) foreach($_POST['term'] as $k){ 
  if($k){ 
    if(strpos($k,'-') && preg_match('#^[^/]+/\d+$#',$k)) list($k) = explode('/', $k);
    $P_TERMS[$k] = 1;
  }
}

if($_POST['term'] && !$_POST['hw_back']){

  include SITE_PATH.'inc/class.payment.php';

  $A_TERMS = hwGetPayPlans();

  // needed parameters: $amount, $id, $term

  $term = $_POST['term'];

  $A_OPT = hwGetPayOptions();
  $a_pp_fee = array();

  foreach($term as $term_key=>$pp_id){

    if(!$pp_id){ 
      unset($term[$term_key]);
      continue;
    }

    list($pp_id,$ex_val) = explode('-',$pp_id);
    if(!isset($ex_val)) $fee = $A_TERMS[$pp_id]['FEE'];
    else{
      if(preg_match('#^[^/]+/\d+$#',$ex_val)) list($ex_val, $ex_amt) = explode('/', $ex_val);
      else $ex_amt = (int)$_POST["eo_amt_$pp_id"];
      $fee = $A_OPT[$pp_id]['FEE'][$ex_val];
      if($ex_amt>1){ 
        $fee*=$ex_amt;
        $term[$term_key] = "$pp_id-$ex_val/$ex_amt";
      }
    }

    if(!isset($fee)) {
      //if(in_array($pp_id, array('CREDITS','AG_ICONS','COUPON','CART'))) $fee = 0; // exceptions
      if(preg_match('/^\w+$/',$pp_id)) $fee = 0;
      else {
        unset($term[$term_key]);
        continue;
      }
    }

    $a_pp_fee[$pp_id] = $fee;
    if($A_TERMS[$pp_id]['TYPE']=='SUB') $id = (int)hwSessionGetVar('userid'); // for subscr. payment
  }

  $total_gross = array_sum(array_values($a_pp_fee));

  $args = array(
    'PP_FEE' => $a_pp_fee,
    'TERM' => implode(' ',$term),
    'TOTAL_GROSS' => $total_gross,
    'TOTAL' => 0, // output
    'TOTAL_TAX' => 0, // output
  );

  hwOrderTotalCalc($args);

  $total_gross = $args['TOTAL_GROSS'];
  $total_tax = $args['TOTAL_TAX'];
  $total = $args['TOTAL'];

  $discount = sprintf('%.2f', $total_gross - $total + $total_tax);

  $term = explode(' ',$args['TERM']);

//  if($total>0 || $discount>0 || !empty($term)){
if($term){

    $term_out = implode(' ',$term);
    $pay_method = str_replace('.','',trim((string)$_POST['pay_method']));
    if(preg_match('/\W/', $pay_method)) die('Incorrect payment method: "'.$pay_method.'"');

    if(!$_POST['hw_submit']){ // preview page
      
      $_POST['term'] = $term; // adjust quantity if needed
      $post_vars = '';
      unset($_POST['hw_agree']);
      foreach($_POST as $k=>$v){
        if(is_array($v)){
          foreach($v as $z) $post_vars.=_inputGetHiddenField($k.'[]', $z);
        }
        elseif($k!='hw_submit') $post_vars.=_inputGetHiddenField($k, $v);
      }

      $o_id = $id;
      if($o_type=='SUB') $id = '';
      
      $pay_method_t = hwGetPayMethods($pay_method);
      $term_out = hwGetPayInfoFmt($term_out,'<br />');

      // payment gateway-specific % charges (processing fee)
      $proc_fee = '0.00';
      if($pay_method && file_exists(SITE_PATH.'inc/pay_modules/'.$pay_method.'.php')){
        include SITE_PATH.'inc/pay_modules/'.$pay_method.'.php';
        $cl_name = 'HawkPayment_'.$pay_method;
        $o_pay = new $cl_name;
        $real_total = $o_pay->getAdjustedAmount($total);
        if($real_total > $total){
          $proc_fee = sprintf('%.2f', $real_total - $total);
          $total = $real_total;
        }
      }
      $pp_id = $term[0];
      $pp_name = $db->one_data('SELECT name FROM '.TBL_PAY_PLAN.' WHERE id="'.$db->quote($pp_id).'"');
      
      $tpl = new HawkTpl;
      $tpl->InitArray('ex');
      
      if(method_exists($o_pay, 'getPreviewExtraFields')){
        $a_f = $o_pay->getPreviewExtraFields();
        $v = array();
        if($a_f){ 
          $tpl->AddCell('ex', '', 'start');
          foreach($a_f as $k){
            list($ftype,$fid,$v['f_t'],$v['f_txt'],$extra) = $k;
            if($ftype=='menu') {
              $v['f_v'] = '<select name="'.$fid.'">';
              $a_m = explode(',',$extra);
              foreach($a_m as $m) $v['f_v'].= '<option value="'.$m.'">'.$m;
              $v['f_v'].= '</select>';
            }
            elseif($ftype=='text') $v['f_v'] = '<input type=text size=40 name="'.$fid.'" />';
            else $v['f_v'] = $extra;
            $tpl->AddCell('ex', $v, 'row');
          }
          $tpl->AddCell('ex', '', 'end');
        }
      }

      $tpl->Parse(TPL_PATH.'order_preview.htm','$o_id,$id,$cid,$CURR_SIGN,$term_out,$total_gross,$total_tax,$TAX,'.
      '$discount,$proc_fee,$total,$pp_id,$pp_name,$pay_method_t,$post_vars',1);

    }
    elseif($total==0){

      // AutoPayment

      $args = array(
        'ID' => $id,
        'TERM' => $term_out,
      );

      $err_msg = Discount_Process_Payment($args);
      
      if($err_msg){
        ShowRenewForm();
        return;
      }

      hwLoginByUserID( hwSessionGetVar('userid') );
      EvalAdvTpl(TPL_PATH.'order_paid.htm','$id,$CURR_SIGN,$term_out,$total_gross,$discount,$total,$total_tax,$TAX',1);

    }
    else {

      $ses_uid = (int)hwSessionGetVar('userid');
      if($ses_uid){
        
        $adid = $o_type=='FEE' ? $id : 0;

    	  $order_exists = $db->one_data('SELECT COUNT(*) FROM '.TBL_PAY_PEND.
        " WHERE order_id='$id' AND userid='$ses_uid' AND adid='$adid' AND details='".$db->quote($term_out)."'");

        if(!$order_exists) $db->query('INSERT INTO '.TBL_PAY_PEND.' (userid,adid,order_id,details,amount,odate,ip,ttype)'.
        " VALUES ('$ses_uid','$adid','$id', ?,'$total',".SQL_NOW.', ?, ?)',
        array($term_out, $_SERVER['REMOTE_ADDR'], hwGetPayMethods($pay_method)) );
        
    	  //if($adid) $db->query('UPDATE '.TBL_AD.' SET hw_temp=0 WHERE link_id='.$adid);
      }

      if(file_exists(SITE_PATH.'inc/pay_modules/'.$pay_method.'.php')){

        include SITE_PATH.'inc/pay_modules/'.$pay_method.'.php';

        $cl_name = 'HawkPayment_'.$pay_method;
        $o_pay = new $cl_name;
        $o_pay->GATE_ID = $pay_method;
        $order_url = $o_pay->GetOrderURL($id,$term_out,$total,hwSessionGetVar('email'));
        if(substr($order_url,0,4)=='http') header('Location: '.$order_url);
        else{ echo $order_url; }
        exit;
      }
      elseif(file_exists(TPL_PATH.'order_pm_'.$pay_method.'.htm')){
        
        CheckLoggedIn();
        $userid = (int)hwSessionGetVar('userid');
        EvalAdvTpl(TPL_PATH.'order_pm_'.$pay_method.'.htm','$id,$userid,$CURR_SIGN,$term_out,$total,$total_tax,$TAX',1);
      }
      else {
        
        $args = array(
          'PAY_METHOD' => $pay_method,
          'ID' => $id,
          'TERM' => $term_out,
          'TOTAL' => $total,
          'TOTAL_GROSS' => $total_gross,
          'TYPE' => $o_type,
        );
        
        hwModEvent('onPaymentUnknown',$args);
        
      }
    }
    return;
  }
  
}

ShowRenewForm();

// functions

function SQL_PP_Get($no_realm){
global $o_type,$cid;

  $ql = 'SELECT p.id AS pp_id,p.name AS pp_name,p.fee AS pp_fee,p.exp_days AS pp_exp_days,
  p.descr AS pp_descr,p.pp_url FROM '.TBL_PAY_PLAN.' p';
  
  $ql_where = '';
  if($o_type=='FEE'){
    if(EN_PP_CAT){
      $ql.=' INNER JOIN '.TBL_PP_CAT.' pc ON p.id=pc.ppid';
      $ql_where.=' AND pc.cid="'.$cid.'"';
    }
  }

  $ql.=' WHERE 1 '.$ql_where.' AND p.type="'.$o_type.'" AND p.enabled="1" AND p.realm<>"'.$no_realm.'"';

  if($o_type=='FEE'){ 
    $u_ac_pp = hwSessionGetVar('u_ac_pp');
    if($u_ac_pp){
      global $db;
      $a_p = $db->one_col_array("SELECT fee_id FROM ".TBL_PP_USER.' WHERE sub_id='.$db->esc($u_ac_pp));
      if($a_p) $ql.=" AND p.id NOT IN ('".implode("','",$a_p)."')";
    }
  }
  
  $ql.=' ORDER by p.weight DESC,p.fee';
  return $ql;
}

function ShowRenewForm(){
  global $db,$o_type,$id,$l_title,$pay_method,
  $cid,$err_msg,$exp_date,$hw_pay_plan,$hw_expired,
  $P_TERMS,$IS_FREE;

  if($_POST['hw_ref'] && ctype_print($_POST['hw_ref']) && $err_msg){
    header('Location: '.$_POST['hw_ref'].'&err_msg='.urlencode($err_msg));
    exit;
  }

  $exp_zero = $exp_date == '0000-00-00 00:00:00' ? 1 : 0;

  $IS_FREE = 0;
  if($exp_zero){ 
    list($pp_zero) = hwGetBasePlanFromStr($hw_pay_plan);
    if($o_type=='FEE'){
      if(EN_1AD_FREE && !hwSessionGetVar('free_ad_used')) $IS_FREE = 1;
      else{
        // $v_price = $db->one_data('SELECT v_price FROM '.TBL_AD.' WHERE link_id='.$id);
        // if($v_price<500) $IS_FREE = 1;
        // $ses_uid = (int)hwSessionGetVar('userid');
        // if($ses_uid) $IS_FREE = $db->one_data('SELECT en_exp_modify FROM '.TBL_USER.' WHERE id='.$ses_uid);
      }
    }
  }
  
  $tpl = new HawkTpl;
  $tpl->InitArray('row');

  $ql = SQL_PP_Get($exp_zero ? 'R' : 'P');
  $A_PP = $db->select($ql);

  // PP Name/Description translation
  $A_TRAN = hwLangPhrase();
  if($A_TRAN) foreach($A_PP as $k=>$v){
    if($A_TRAN["pp_name-$v[pp_id]"]) $A_PP[$k]['pp_name'] = $A_TRAN["pp_name-$v[pp_id]"];
    if($A_TRAN["pp_txt-$v[pp_id]"]) $A_PP[$k]['pp_descr'] = $A_TRAN["pp_txt-$v[pp_id]"];
  }

  /*
  $A_TERMS = hwGetPayPlans();
  $A_PAYOPT = array();
  foreach (array_keys(hwGetPayOptions()) AS $k) $A_PAYOPT[$k] = ''; 
  */
  foreach($A_PP as $v){
    
    $v['pp_checked'] = '';
    if($P_TERMS){ // POST has priority
      if($P_TERMS[$v['pp_id']]) $v['pp_checked'] = 'checked';
    }
    elseif($exp_zero){ 
      if($pp_zero == $v['pp_id']) $v['pp_checked'] = 'checked';
      else continue; // show only $pp_zero plan
    }
    
//    $v = array_merge($v, $A_PAYOPT, $A_TERMS[$v['pp_id']]['OPTS']);
    
    $tpl->AddCell('row',$v);
  }

//  $A_OPTS = hwGetPayOptions($o_type=='FEE' ? 'AD_' : 'U_');
  $A_OPTS = $o_type=='FEE' ? hwGetExtraOptions() : false;

  $skipped = 0;
  if($A_OPTS){     
    foreach(array_keys($A_OPTS) as $k){
      if(!$A_OPTS[$k]['FEE'] || !$A_OPTS[$k]['EN_ORD']) $skipped++;
    }    
  }
  
// Don't show extra options for fee plans if EN_SUB_AD enabled
// if(EN_SUB_AD && $o_type=='FEE') $skipped = count($A_OPTS);

  if($A_OPTS && $skipped < count($A_OPTS)){
    $tpl->AddCell('row','','extra_start');
    $v = array();
    foreach(array_keys($A_OPTS) as $k){
      if(!$A_OPTS[$k]['FEE'] || !$A_OPTS[$k]['EN_ORD']) continue;
      
      $v['e_id'] = $A_OPTS[$k]['ID'];
      $v['e_title'] = $A_OPTS[$k]['NAME'];
      $v['e_ctl'] = pp_GetPayOptOrderCtl($A_OPTS[$k]);
      $v['e_amt'] = pp_GetPayOptAmountCtl($A_OPTS[$k]);
      //$v['e_term'] = intval($A_OPTS[$k]['DT']/86400); // days
      $tpl->AddCell('row',$v,'extra');
    } 
    $tpl->AddCell('row','','extra_end');
  }

  $pay_method = hwGetPayMethods();
  
  /*
  if($o_type=='SUB') $pay_method = preg_replace('/<OPTION\s.*?VALUE="credits".*?(?=<)/is','',$pay_method);
  else $pay_method = preg_replace('/<OPTION.*?(?=<\/SELECT)/is','<option value="credits">{Credits}',$pay_method);
  */

  if(!$err_msg && $_GET['err_msg']) $err_msg = html_esc($_GET['err_msg']);
  $tpl->Parse(TPL_PATH.'order_'.$o_type.'.htm','$id,$CURR_SIGN,$IS_FREE,$EX_OPT_EXP,$hw_expired,$l_title,$err_msg,$pay_method',1);

}

function ShowPayPlansForm(){
global $db,$cid,$o_type,$IS_FREE;

  $tpl = new HawkTpl;
  $tpl->InitArray('row');

  $ql = SQL_PP_Get('R');
  $A_PP = $db->select($ql);
  $num_rows = count($A_PP);

  if($num_rows>0){
    
    if($num_rows==1){ // no need to show page with one price plan
      $v = $A_PP[0];
      $url = $o_type == 'FEE' ? 'index.php?page=add&hw_pay_plan='.$v['pp_id'].'&cid='.$cid : 'index.php?page=reg&hw_pay_plan='.$v['pp_id'];
      header('Location: '.$url);
      exit;
    }

    $IS_FREE = 0;
    if($o_type == 'FEE'){ 
      if(EN_1AD_FREE && !hwSessionGetVar('free_ad_used')) $IS_FREE = 1;
      else{
        // $ses_uid = (int)hwSessionGetVar('userid');
        // if($ses_uid) $IS_FREE = $db->one_data('SELECT en_exp_modify FROM '.TBL_USER.' WHERE id="'.$ses_uid.'"');
      }
    }
    
    // PP Name/Description translation
    $A_TRAN = hwLangPhrase();
    if($A_TRAN) foreach($A_PP as $k=>$v){
      if($A_TRAN["pp_name-$v[pp_id]"]) $A_PP[$k]['pp_name'] = $A_TRAN["pp_name-$v[pp_id]"];
      if($A_TRAN["pp_txt-$v[pp_id]"]) $A_PP[$k]['pp_descr'] = $A_TRAN["pp_txt-$v[pp_id]"];
    }

  /*
  $A_TERMS = hwGetPayPlans();
  $A_PAYOPT = array();
  foreach (array_keys(hwGetPayOptions()) AS $k) $A_PAYOPT[$k] = ''; 
  */
    foreach($A_PP as $v){ 
//    $v = array_merge($v, $A_PAYOPT, $A_TERMS[$v['pp_id']]['OPTS']);
      $tpl->AddCell('row',$v);
    }

  }
  else{ // no matching fee-based price plans, try to find subscr. based

    $ql = 'SELECT COUNT(*) FROM '.TBL_PAY_PLAN.' WHERE type="SUB" AND enabled="1" AND options LIKE "%U_ADS_EXP%"';
    if($db->one_data($ql)>0){
      header('Location: index.php?page=order');
      exit;
    }
    else die('No price plans defined');
    
  }

  $tpl->Parse(TPL_PATH.'order_'.$o_type.'_new.htm','$cid,$CURR_SIGN,$IS_FREE',1);

}

function pp_GetPayOptOrderCtl($a_v){
  global $P_TERMS;
  
  $s = '';
  foreach($a_v['FEE'] as $id => $fee){
  	$val = $a_v['DESCR'][$id];
  	if(!$val) $val = $id;
  	$k = $id ? $a_v['ID'].'-'.$id : '';
    $s.='<option '.($P_TERMS[$k]?'selected ':'')."value=\"$k\">$val - ".CURR_SIGN.$fee;
  }
  return $s;
}

function pp_GetPayOptAmountCtl($a_v){
  $name = 'eo_amt_'.$a_v['ID'];
  //$s = '<select name="'.$name.'">';
  $s = '';
  for($i=1;$i<=12;$i++){
    $s.='<option '.($_POST[$name]==$i?'selected ':'')."value=\"$i\">x $i";
  }
  //$s.= '</select>';
  return $s;
}

function Discount_Process_Payment($args){

  $o_pay = new HawkPayment;
  $o_pay->UPDATE_PAY_LOG = 0;
  $token = strtoupper(substr( md5(uniqid(mt_rand(), TRUE)), 0, 6));
  $o_pay->TXN_ID = 'DS-'.$o_pay->ID.'-'.time().'-'.$token;
  $o_pay->ID = $args['ID'];
  $o_pay->TERM = $args['TERM'];
  $o_pay->AMOUNT = 0;
  $o_pay->MANUAL = TRUE;
  $o_pay->STATUS = 'Y';
  $o_pay->Process();
  return $o_pay->ERR_MSG;

}

function _inputGetHiddenField($name, $value){
  return '<input type=hidden name="'.html_esc($name).'" value="'.html_esc($value).'">'."\n";
}

?>
Return current item: Esvon Personals