<?php
/*
	 
	
Freeway eCommerce
http://www.openfreeway.org
Copyright (c) 2007 ZacWare
	
	Released under the GNU General Public License
*/
////
// Return true if the events category has subcategories
// TABLES: events_categories
// use condition in all event status checking 
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
//set_time_limit(30);
        if( !ini_get('safe_mode') ){
            set_time_limit(30);
        }
////
// Stop from parsing any further PHP code
// v2.3.3.1 now closes the session through a registered shutdown function
  function tep_exit() {
   exit();
  }
// get the admin groups name by providing the group id
function tep_get_group_name($group_id){
    $group_query=tep_db_query("SELECT admin_groups_name from " . TABLE_ADMIN_GROUPS . " where admin_groups_id='" . (int)$group_id . "'"); 
    if ($group_result=tep_db_fetch_array($group_query)){
      return $group_result['admin_groups_name'];
    } 
 }
 
 // get the html content for question input from user
 function tep_get_question_input($type){
   $result='';
   $param="size=30 maxlength=100";
   //if the type is text or numeric, create a textbox
    if ($type=='T' || $type=='N'){
		if ($type=='N') $param="size=15 maxlength=10";
       $result.=tep_draw_input_field('question_value_data','',$param);
    } else if ($type=='D'){
		// if the type is a date, create a dropdownlist for month,day,year
		
       $result.=tep_draw_hidden_field('question_value_data','');
       $month=array('','January','February','March','April','May','June','July','August','September','October','November','December');
       $date_query=tep_db_query("SELECT date_format(current_date,'%d') as day, date_format(current_date,'%m') as month, date_format(current_date,'%Y') as year");
       $date_result=tep_db_fetch_array($date_query);
       $month_array=array();
       for($icnt=0;$icnt<=12;$icnt++)
          $month_array[]=array('id'=>$icnt,'text'=>$month[$icnt]);
       $result.=tep_draw_pull_down_menu('question_month',$month_array);
       $day_array=array();
       for($icnt=0;$icnt<=31;$icnt++){
	   	$text=$icnt;
	   	if ($icnt==0) $text='';
          $day_array[]=array('id'=>$icnt,'text'=>$text);
		}  
       $result.='&nbsp;' . tep_draw_pull_down_menu('question_day',$day_array);
       $year_array=array();
       $year_array[]=array('id'=>0,'text'=>'');
       $year_array[]=array('id'=>$date_result['year'],'text'=>$date_result['year']);
       $year_array[]=array('id'=>$date_result['year']+1,'text'=>$date_result['year']+1);
       $result.='&nbsp' . tep_draw_pull_down_menu('question_year',$year_array);
    }
    return $result . '<font color="red">&nbsp;*</font>';
 }
 
// replace the test email with default merge details
function tep_replace_test_mail_content($mail_content){
  global $currencies;
      $replace_array=array(TEXT_FN=>TEST_MAIL_FN,
							TEXT_LN=>TEST_MAIL_LN,
							TEXT_DF=>TEST_MAIL_DF,
							TEXT_EM=>TEST_MAIL_EM,
							TEXT_TN=>TEST_MAIL_TN,
							TEXT_FX=>TEST_MAIL_FX,
							TEXT_SA=>TEST_MAIL_SA,
							TEXT_SU=>TEST_MAIL_SU,
							TEXT_PC=>TEST_MAIL_PC,
							TEXT_CT=>TEST_MAIL_CT,
							TEXT_ST=>TEST_MAIL_ST,
							TEXT_CY=>TEST_MAIL_CY,
    
							TEXT_EN=>TEST_MAIL_EN,
							TEXT_SD=>getServerDate(),
							TEXT_SI=>TEST_MAIL_SI,
							TEXT_EI=>TEST_MAIL_EI,
							TEXT_EF=>TEST_MAIL_EF,
							TEXT_IN=>TEST_MAIL_IN,
							TEXT_EL=>TEST_MAIL_EL,
							TEXT_IV=>TEST_MAIL_IV,
							TEXT_IC=>TEST_MAIL_IC,
							TEXT_IF=>TEST_MAIL_IF,
							TEXT_UN=>TEST_MAIL_UN,
							TEXT_RE=>TEST_MAIL_RE,
							TEXT_FE=>TEST_MAIL_FE,
							TEXT_CF=>TEST_MAIL_CF,
							TEXT_CL=>TEST_MAIL_CL,
							TEXT_SS=>sprintf(TEST_MAIL_FORMAT_SS,TEST_MAIL_EN,TEST_MAIL_SI,TEST_MAIL_EI,date('l, jS F'),TEST_MAIL_EL),
							TEXT_SSM=>date(str_replace("/","-",EVENTS_DATE_FORMAT)),
							TEXT_RL=>TEST_MAIL_RL,
							TEXT_RM=>TEST_MAIL_RM,
							TEXT_RV=>TEST_MAIL_RV,
							TEXT_WV=>TEST_MAIL_WV,
							TEXT_FV=>TEST_MAIL_FV,
							
							TEXT_ON=>TEST_MAIL_ON,
							TEXT_OC=>TEST_MAIL_OC,
							TEXT_OD=>TEST_MAIL_OD,
							TEXT_BT=>TEST_MAIL_BT,
							TEXT_BA=>TEST_MAIL_BA,
							TEXT_PY=>TEST_MAIL_PY,
							TEXT_SB=>$currencies->format(TEST_MAIL_SB),
							TEXT_TX=>$currencies->format(TEST_MAIL_TX),
							TEXT_TL=>$currencies->format(TEST_MAIL_TL),
							TEXT_IL=>TEST_MAIL_IL,
							TEXT_PDF=>TEST_MAIL_PDF,
			 );
   while (list($key, $value) = each($replace_array))
      //$mail_content=eregi_replace("%%" . $key  . "%%",$value . "",$mail_content);
		$mail_content=preg_replace("/%%" . $key  . "%%/i",$value,$mail_content);
		
  return $mail_content;
}
//default mail handling function with type,merge_details,send_address details
	function tep_send_default_email($type,$merge_details,$send_details,$filename=''){
		$details=array();
		$details['type']=$type;
		
		$details['table']=TABLE_EMAIL_MESSAGES;
		tep_get_template($details);      	  // get template using type and table   
		if ($details['html_text']=="") {	
			if($type!='PRD') return;
			$fp=@fopen(DIR_FS_CATALOG . DIR_WS_TEMPLATES . TEMPLATE_NAME . "/images/product_email_template.html","r");
			if (!$fp) return;
			$details['html_text']=fread($fp,filesize(DIR_FS_CATALOG . DIR_WS_TEMPLATES . TEMPLATE_NAME . "/images/product_email_template.html"));
			if ($details['html_text']=="") return false;
			$details['text']=strip_tags($details['html_text']);
			$details['format']="B";
		}
		tep_replace_template($details,$merge_details); // replace template content with merge details
		tep_strip_html($details); // strip tags;
		//send mails to given addresses
		for ($icnt=0;$icnt<sizeof($send_details);$icnt++){
			$details['to_name']=$send_details[$icnt]['to_name'];
			$details['to_email']=$send_details[$icnt]['to_email'];
			$details['from_name']=$send_details[$icnt]['from_name'];
			$details['from_email']=$send_details[$icnt]['from_email'];
			tep_send_email($details,true,$filename); // send email
		}
		
	}
// function to add   to given date
function tep_dateadd($timestamp, $unit, $amount) {
		$rtime=0;
		if($timestamp>0){
			$timestring=date("Y-m-d H:i:s",$timestamp);
			$timestring = preg_replace("#\s#","",$timestring); 
			$timestring = preg_replace("#\:#","",$timestring);
			$timestring = preg_replace("#\.#","",$timestring);
			$timestring = preg_replace("#\/#","",$timestring);
			$timestring = preg_replace("#\-#","",$timestring);
			$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
			$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;
			$array['yr']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
			$array['mon']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
			$array['day']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
			$array['hr']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
			$array['min']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
			$array['sec']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);
			$array[$unit]+=$amount;
			$rtime = mktime ($array['hr'],$array['min'],$array['sec'],$array['mon'],$array['day'],$array['yr']); 
		}
	return $rtime;
}
// subtract specified interval to a given date
function tep_datesub($timestamp, $unit, $amount) {
		$timestring=date("Y-m-d H:i:s",$timestamp);
		$timestring = preg_replace("#\s#","",$timestring);
		$timestring = preg_replace("#\:#","",$timestring);
		$timestring = preg_replace("#\.#","",$timestring);
		$timestring = preg_replace("#\/#","",$timestring);
		$timestring = preg_replace("#\-#","",$timestring);
		$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
		$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;
		$array['yr']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
		$array['mon']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
		$array['day']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
		$array['hr']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
		$array['min']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
		$array['sec']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);
		$array[$unit]-=$amount;
		   $rtime = mktime ($array['hr'],$array['min'],$array['sec'],$array['mon'],$array['day'],$array['yr']);
	return $rtime;
} 
 function tep_get_count($table,$condition){
    $count_query=tep_db_query("select count(*) as total from " . $table . " where " . $condition);
    if($count_result=tep_db_fetch_array($count_query))
       return (int)$count_result['total'];
    return 0;
 }
 
 
// count the no of days in given start and end date
function tep_count_days($start, $end)
{
   if( $start != '0000-00-00' and $end != '0000-00-00' )
   {
       $timestamp_start = strtotime($start);
       $timestamp_end = strtotime($end);
       if( $timestamp_start >= $timestamp_end ) return 0;
       $start_year = date("Y",$timestamp_start);
       $end_year = date("Y", $timestamp_end);
       $num_days_start = date("z",strtotime($start));
       $num_days_end = date("z", strtotime($end));
       $num_days = 0;
       $i = 0;
       if( $end_year > $start_year )
       {
           while( $i < ( $end_year - $start_year ) )
           {
             $num_days = $num_days + date("z", strtotime(($start_year + $i)."-12-31"));
             $i++;
           }
         }
         return ( $num_days_end + $num_days ) - $num_days_start;
   }
   else
   {
         return 0;
     }
}
	function tep_get_sms_address($mobile){
	return $mobile . '@' . EVENTS_SMS_GATEWAY;
	}
	
	// format date according to date setting in configuration
  function format_date($raw_date,$simple=false){
    if ( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '0000-00-00') || ($raw_date == '') || ($raw_date <= 0)) return false;
	$format=EVENTS_DATE_FORMAT;
	if ($simple) $format=strtolower($format);
    $year = substr($raw_date, 0, 4);
    $month = (int)substr($raw_date, 5, 2);
    $day = (int)substr($raw_date, 8, 2);
    $hour = (int)substr($raw_date, 11, 2);
    $minute = (int)substr($raw_date, 14, 2);
    $second = (int)substr($raw_date, 17, 2);
	if (@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year) {
      return date($format, mktime($hour, $minute, $second, $month, $day, $year));
    } else {
      return preg_replace('/2037$/', $year, date($format, mktime($hour, $minute, $second, $month, $day, 2037)));
    }

  }
    // if (@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year) {
      // return date($format, mktime($hour, $minute, $second, $month, $day, $year));
    // } else {
      // return ereg_replace('2037' . '$', $year, date($format, mktime($hour, $minute, $second, $month, $day, 2037)));
    // }
	
	// Replace the template content
	function tep_replace_template(&$details,&$replace_array){
		reset($replace_array);
		//FOREACH
		//while(list($key,$value)=each($replace_array)){
		foreach($replace_array as $key => $value) {
			$details['html_text']=preg_replace("#%%" . $key . "%%#i",preg_escape_back($value). "",$details['html_text']);
		}
		$details['html_text']=preg_replace("/%%current_url%%/i",HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_TEMPLATES . TEMPLATE_NAME . "/",$details['html_text']);
		//or add order number to subject line
		//$details['subject']=preg_replace("#%%" . $key . "%%#i",$value . "",$details['subject']);
	}
	
	function preg_escape_back($string) {
    // Replace $ with \$ 
    $string = preg_replace('#(\\$|\\\\)#', '\\\\$1', $string);
    return $string;
		} 
	// common function to send email
	// edited to handle pdf attachment
	function tep_send_email(&$details,$default=false,$filename){
		$result=false;
		if ($default==false && (int)EMAIL_ACTIVATE!=1) return $result;
		 $message = new email(array('X-Mailer: osConcert'));
			
		 if ($details['format'] != 'T') {
			 $message->add_html($details['html_text'], $details['text']);
		 } else {
			 $message->add_text($details['text']);
		 }
	     	  
		//new code pdf send
		//Feb 2020 add in smtp attachment
		if(DISPLAY_PDF_DELIVERED_ONLY=='true' && isset($filename) && $filename !==''){ 
			  $message->add_attachment($message->get_file($filename),'eticket.pdf','application/pdf');
			  //smtp
			  $message->add_smtp_attachment($filename,'eticket.pdf');
			  }
		  
		 $message->build_message();
		  if(strpos($details['to_email'],',')!==false) {
                 $to_email=array();
                 $to_email=explode(",",$details['to_email']);
                 $details['to_email']=$to_email;
             }
			 
		
		 $result=$message->send($details['to_name'], $details['to_email'], $details['from_name'], $details['from_email'], $details['subject']);
		 unset($message);
		 return $result;
	}
	// function to fetch template content from database table
	function tep_get_template(&$details){
		$details['html_text']='';
		$details['text']='';
		$add_option="";
		// if (isset($details['events_id'])){
			// $add_option=" and events_id='" . tep_db_input($details['events_id']) . "' ";
		// } else if (isset($details['subscription_id'])){
			// $add_option=" and subscription_id='" . tep_db_input($details['subscription_id']) . "' ";
		// }
		$mail_data_query=tep_db_query("SELECT * from " . $details["table"] . " where message_type='" . tep_db_input($details["type"]) . "'" . $add_option);
		if (tep_db_num_rows($mail_data_query)>0){
			$mail_data_result=tep_db_fetch_array($mail_data_query);
			//get message content
			$details['format']=$mail_data_result['message_format'];
			$details['html_text']=$mail_data_result['message_text'];
			$details['subject']=$mail_data_result['message_subject'];
			//or to add the order number to the subject line
			//if($mail_data_result['message_type'] == 'PRD'){
//                $details['subject']=$mail_data_result['message_subject'].' - Order Number: %%Order_Number%%';
//            }
//            else{
//                $details['subject']=$mail_data_result['message_subject'];
//            }
		}
	}
	// strip the html tags
	function tep_strip_html(&$details){
		$details['text']=strip_tags($details['html_text'],'<br>');
		$details['text']=str_replace(array('<br />','<br>','<BR>','<BR />','<br/>','<BR/>'),chr(13). chr(10),$details['text']);
	}
	//common function to send sms 
	function send_sms($to,$from,$text,$country){
		global $sms,$messageStack;
		$to=str_replace(" ","",$to);
		if (!$sms->connecthost()){
			$messageStack->add_session("SMS Error:" . $sms->get_error(), 'error');
			return false;
		}
		if (!$sms->send_sms($to,$from,$text,$country)){
			$messageStack->add_session($sms->get_failed_messages(), 'error');
			return false;
		}
		return true;
	}
	// get rounded amount according to rounding factor in configuration
 function tep_get_rounded_amount($amount){
 	$result=0;
	$round_digit=0;
	$decimal=0;
 	$round_type=EVENTS_ORDER_AMOUNT_ROUND;
	$decimal=floor((($amount-floor($amount))*100)+0.5);
	switch($round_type){
		case "0.01":
			$result=$amount;
			break;
		case "0.05":
			$round_digit=$decimal%10;
			if ($round_digit>7) {
				$decimal=(floor($decimal/10)+1)*10;
			} else if ($round_digit>2) {
				$decimal=(floor($decimal/10)*10)+5;
			} else {
				$decimal=floor($decimal/10)*10;			
			}
			$result=floor($amount)+$decimal/100;
			break;
		case "0.1":
			$decimal=(floor($decimal/10))*10;
			$result=floor($amount)+$decimal/100;
			break;
		case "0":
		default:
			if ($decimal>=50)
				$result=floor($amount)+1;
			else
				$result=floor($amount);
	}
	return $result;
 }
 
 // format may be in format dd mm yyyy in any combinations but length must be equal to this
 function tep_check_date_raw($date,$format,$sep_char="/-/"){
 	$date_details=array('y'=>0,'m'=>0,'d'=>0);
	$split_arr=preg_split($sep_char,$date);
	$split_format=preg_split($sep_char,$format);
	if (!(sizeof($split_arr)==sizeof($split_format) && sizeof($split_arr)>0 && sizeof($split_arr)<=3)) return false;
	
	for ($icnt=0;$icnt<sizeof($split_arr);$icnt++){
		if (isset($date_details[strtolower($split_format[$icnt])]))
			$date_details[strtolower($split_format[$icnt])]=(int)$split_arr[$icnt];
	}
	return checkdate($date_details['m'],$date_details['d'],$date_details['y']);
 }
 
 function tep_convert_date_raw($date,$format=EVENTS_DATE_FORMAT,$sep_char="/-/"){
 	$date_details=array('y'=>0,'m'=>0,'d'=>0);
	$split_arr=preg_split($sep_char,$date);
	$split_format=preg_split($sep_char,$format);
	if (!(sizeof($split_arr)==sizeof($split_format) && sizeof($split_arr)>0 && sizeof($split_arr)<=3)) return "";
	
	for ($icnt=0;$icnt<sizeof($split_arr);$icnt++){
		if (isset($date_details[strtolower($split_format[$icnt])]))
			$date_details[strtolower($split_format[$icnt])]=(int)$split_arr[$icnt];
	}
	return $date_details['y'] . '-' . $date_details['m'] . '-' . $date_details['d'];
 }
  
 
 // get the current server date considering date offset settings
 function getServerDate($date=true){
	$offset=(float)EVENTS_SERVER_DATE_OFFSET;
	if($offset>0){
		if(strpos($offset,'.')>0){
			$cur_offset_time = mktime(date('H')+abs($offset),date('i')+30,date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}else{
			$cur_offset_time = mktime(date('H')+abs($offset),date('i'),date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}
	}else{
		if(strpos($offset,'.')>0){
			$cur_offset_time = mktime(date('H')-abs($offset)+1,date('i')-30,date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}else{
			$cur_offset_time = mktime(date('H')-abs($offset),date('i'),date('s'),date('m'),date('d'),date('y'));
			if($date)
				return date('Y-m-d',$cur_offset_time);
			else
				return $cur_offset_time;
		}
	}
 }
 
   ////rmh referral
// Returns an array with sources
// TABLES: sources
  function tep_get_sources($sources_id = '') {
    $sources_array = array();
    if (tep_not_null($sources_id)) {
        $sources = tep_db_query("select sources_name from " . TABLE_SOURCES . " where sources_id = '" . (int)$sources_id . "'");
        $sources_values = tep_db_fetch_array($sources);
        $sources_array = array('sources_name' => $sources_values['sources_name']);
    } else {
      $sources = tep_db_query("select sources_id, sources_name from " . TABLE_SOURCES . " order by sources_name");
      while ($sources_values = tep_db_fetch_array($sources)) {
        $sources_array[] = array('sources_id' => $sources_values['sources_id'],
                                   'sources_name' => $sources_values['sources_name']);
      }
    }
    return $sources_array;
  }
////rmh referral
// Creates a pull-down list of countries
  function tep_get_source_list($name, $selected = '', $parameters = '') {
    $sources_array = array(array('id' => '', 'text' => PULL_DOWN_DEFAULT));
    $sources = tep_get_sources();
    for ($i=0, $n=sizeof($sources); $i<$n; $i++) {
      	$sources_array[] = array('id' => $sources[$i]['sources_id'], 'text' => $sources[$i]['sources_name']);
    }
	if (DISPLAY_REFERRAL_OTHER=='true'){
		$sources_array[] = array('id' => '9999', 'text' => TEXT_REFERRAL_OTHER);
	}
    return tep_draw_pull_down_menu($name, $sources_array, $selected, $parameters);
  }
  
  function tep_get_customer_options($type) {
    $options_array = array();
	$options_array[] = array('id' => '', 'text' => PULL_DOWN_DEFAULT);
    $options = tep_db_query("select options_id, options_name from " . TABLE_CUSTOMER_OPTIONS . " where options_type='". tep_db_input($type)  ."' order by options_name");
      while ($options_values = tep_db_fetch_array($options)) {
        $options_array[] = array('id' => $options_values['options_id'],
                                   'text' => $options_values['options_name']);
      }
    return $options_array;
  }
  function tep_draw_hidden($name, $value = '', $parameters = '') {
    $field = '<input type="hidden" name="' . tep_output_string($name) . '"';
      $field .= ' value="' . tep_output_string($value) . '"';
    if (tep_not_null($parameters)) $field .= ' ' . $parameters;
    $field .= '>';
    return $field;
  }
  function tep_get_all_input_params($exclude_array = '') {
    global $FGET,$FSESSION;
    if (!is_array($exclude_array)) $exclude_array = array();
    $get_url = '';
    if (is_array($FGET) && (sizeof($FGET) > 0)) {
      reset($FGET);
      while (list($key, $value) = each($FGET)) {
        if ( (strlen($value) > 0) && ($key != $FSESSION->name) && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') ) {
          $get_url .= $key . '=' . urlencode(stripslashes($value)) . '&';
        }
      }
    }
    return $get_url;
  }
  
function tep_payment_installed($module){
		$modules=MODULE_PAYMENT_INSTALLED;
		if ($modules!=""){
			$modules_array=preg_split("/;/",$modules);
			if (array_search($module,$modules_array)===false){
				return false;
			}
			else {
				return true;
			}
		}
	}
	
	function tep_product_small_image($image,$title,$parameters=""){
		
		if($image==''){
		$image='pixel_trans.gif';	
		}
		
		if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
			//return tep_image(DIR_WS_IMAGES . "small/" . $image,$title,'','',$parameters);
			//give it width
			return tep_image(DIR_WS_IMAGES . "small/" . $image,$title,SMALL_IMAGE_WIDTH,'',$parameters);
		}
		else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
			return tep_image(DIR_WS_IMAGES . "big/" . $image,$title,SMALL_IMAGE_WIDTH,'',$parameters);
		}
		else {
			return tep_image(DIR_WS_IMAGES . $image,$title,SMALL_IMAGE_WIDTH,'',$parameters);
		}
	}
	
	function tep_product_email_image($image,$title,$parameters=""){
		
		if($image==''){
		$image='pixel_trans.gif';	
		}
		
		file_put_contents('mail.txt',DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image);
		if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
			return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . "small/" . $image . '" width=50 height=50 ' . $parameters . '>';
		}
		else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
			return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . "big/" . $image . '" width=50 height=50 ' . $parameters . '>';
		}
		else if(file_exists(HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image))  {
			return '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . '" width=50 height=50 ' . $parameters . '>';
		}
		else {
			return tep_image(DIR_WS_IMAGES . 'pixel_trans.gif','', '50','50');
		}
	}
	
	function tep_product_custom_image($image,$title,$parameters="",$width=50,$height=50,$calculate=true){
		$filename=$image;
		if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "small/" . $image)){
			$filename="small/" . $image;
		} else if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $image)){
			$filename="big/" . $image;
		}
		if ($calculate){
		  if ($image_size = @getimagesize(DIR_FS_CATALOG . DIR_WS_IMAGES . $filename)) {
			  if ($image_size[0]>$width){
				  $ratio = $width / $image_size[0];
				  $height = intval($image_size[1] * $ratio);
			  } elseif ($image_size[1]>$height) {
				  $ratio = $height / $image_size[1];
				  $width = intval($image_size[0] * $ratio);
			  } else {
				  $width = $image_size[0];
				  $height = $image_size[1];
			  }
		  }
		}
		return '<img class="img-fluid" src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $filename . '" width="' .$width . '" height="' . $height. '" ' . $parameters . '>';
	} 

 function getGMTTime(){
		$timestring=date("Y-m-d H:i:s",mktime());
		$offset=date("O");
		$timestring = preg_replace("#\s#","",$timestring);
		$timestring = preg_replace("#\:#","",$timestring);
		$timestring = preg_replace("#\.#","",$timestring);
		$timestring = preg_replace("#\/#","",$timestring);
		$timestring = preg_replace("#\-#","",$timestring);
		$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
		$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;
		$array['years']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
		$array['months']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
		$array['days']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
		$array['hours']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
		$array['minutes']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
		$array['seconds']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);
		$hour=(int)substr($offset,1,2);
		$min=(int)substr($offset,3);
		if (substr($offset,0,1)=="-"){
		   $rtime = mktime ( $array['hours']      +     $hour,
							$array['minutes'] +     $min,
							$array['seconds'] +     0,
							$array['months']  +     0,
							$array['days']      +     0,
							$array['years']      +     0);
		} else {
		   $rtime = mktime ( $array['hours']      -     $hour,
							$array['minutes'] -    $min,
							$array['seconds'] -     0,
							$array['months']  -     0,
							$array['days']      -     0,
							$array['years']      -     0);
		}
	return $rtime;
 }
	function tep_owd_costs($type='',$value=0){
		$cost_total = 0;
		if($type=='') return;
		
		if($type=="order" && defined('MODULE_FULFILLER_ONEWORLD_COST_PER_ORDER')){
			$cost_total = MODULE_FULFILLER_ONEWORLD_COST_PER_ORDER;
		
		} else if($type=="overweight" && defined('MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_HANDLING_FEE')){
			if (defined("MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_THRESHOLD") && MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_THRESHOLD>0){
				if($value>MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_THRESHOLD) {
					$cost_total = MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_HANDLING_FEE;
				}
			}
		} else if($type=='quantity' && defined('MODULE_FULFILLER_ONEWORLD_COST_PER_ITEM')) {
			$cost_total = MODULE_FULFILLER_ONEWORLD_COST_PER_ITEM*$value;
		
		} else if($type=="packing" && defined('MODULE_FULFILLER_ONEWORLD_COST_PER_PACKING') && defined('SHIPPING_MAX_WEIGHT')) {
			$cost_total = MODULE_FULFILLER_ONEWORLD_COST_PER_PACKING*(ceil($value/SHIPPING_MAX_WEIGHT));
		}
		
		return $cost_total;
	}
	function tep_get_OWD_shipping_type($type=''){
		switch($type){
			case 'usps_Express':
				$shipping="POS.EXP"; 
			break;
			case 'usps_Parcel':
				$shipping="OWD.4th.PARCEL";
			break;
			case 'ups_GND':
				$shipping="UPS.GND";
			break;
			case 'ups_1DA':
				$shipping="UPS.NDA";
			break;
			default:
			$shipping="OWD.1ST.PRIORITY";
		}
		return $shipping; 
	}	
	
	function tep_get_unit_name(){
		if (!defined("SHOP_WEIGHT_UNIT")) return TEXT_KG;
		if (!defined("TEXT_" . SHOP_WEIGHT_UNIT)) return TEXT_KG;
		return constant("TEXT_" . SHOP_WEIGHT_UNIT);
	}
	function tep_get_display_weight($weight){
		return $weight . '&nbsp;' . tep_get_unit_name();
	}		
	  function tep_get_customer_survey_options($type,$other_option=false) {
    $options_array = array();
	$options_array[] = array('id' => '', 'text' => PULL_DOWN_DEFAULT);
    $options = tep_db_query("select options_id, options_name from " . TABLE_CUSTOMER_OPTIONS . " where options_type='". tep_db_input($type)  ."' order by options_name");
      while ($options_values = tep_db_fetch_array($options)) {
        $options_array[] = array('id' => $options_values['options_id'],
                                   'text' => $options_values['options_name']);
      }
	 if($other_option) 	$options_array[] = array('id'=>'9999', 'text' => TEXT_REFERRAL_OTHER); 
    return $options_array;
  }
  $nwords = array(    "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
                     "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
                     "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
                     "Nineteen", "Twenty", 30 => "Thirty", 40 => "Forty",
                     50 => "Fifty", 60 => "Sixty", 70 => "Seventy", 80 => "Eighty",
                     90 => "Ninety" );
function int_to_words($x)
{
     global $nwords;
     if(!is_numeric($x))
     {
         $w = '#';
     }else if(fmod($x, 1) != 0)
     {
         $w = '#';
     }else{
         if($x < 0)
         {
             $w = 'minus ';
             $x = -$x;
         }else{
             $w = '';
         }
         if($x < 21)
         {
             $w .= $nwords[$x];
         }else if($x < 100)
         {
             $w .= $nwords[10 * floor($x/10)];
             $r = fmod($x, 10);
             if($r > 0)
             {
                 $w .= '-'. $nwords[$r];
             }
         } else if($x < 1000)
         {
             $w .= $nwords[floor($x/100)] .' Hundred';
             $r = fmod($x, 100);
             if($r > 0)
             {
                 $w .= ' and '. int_to_words($r);
             }
         } else if($x < 1000000)
         {
             $w .= int_to_words(floor($x/1000)) .' Thousand';
             $r = fmod($x, 1000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $w .= 'and ';
                 }
                 $w .= int_to_words($r);
             }
         } else {
             $w .= int_to_words(floor($x/1000000)) .' Million';
             $r = fmod($x, 1000000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $word .= 'and ';
                 }
                 $w .= int_to_words($r);
             }
         }
     }
     return $w; 
	}
	function tep_check_module_status(&$module,$payment_zone,$except_zone_list,$except_country_list){
		global $order, $FSESSION;
	  //Box Office - look for the session
	  //  if ($_SESSION['BoxOffice']== 999){
	  if($FSESSION->get("customer_country_id") == 999){
	  // there is a Box Office operator in the checkout pages
	  $the_zone_id = 999;}else{
	  $the_zone_id = (int)$order->billing['country']['id'];}
	  //Box Office end
	  if ( ($module->enabled == true) && (($except_zone_list!='' && substr($except_zone_list,0,1)!='M') || ($except_country_list!='' && substr($except_country_list,0,1)!='M'))) {
	  	$add_option='';
		if ($except_zone_list!='' && substr($except_zone_list,0,1)!='M') $add_option.=" geo_zone_id in(" . tep_db_input($except_zone_list) . ") ";
		if ($except_country_list!='' && substr($except_country_list,0,1)!='M') {
			if ($add_option!='') $add_option.=' or ';
			$add_option.=" zone_country_id in(" . tep_db_input($except_country_list) . ") ";
		}
		if ($add_option!=""){
			$check_query=tep_db_query("SELECT zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where  (" . $add_option. ") and zone_country_id='" . $the_zone_id . "' and (zone_id is null or zone_id = '0' or zone_id ='" . (int)$order->billing['zone_id'] ."');");
			if (tep_db_num_rows($check_query)>0){
				$module->enabled=false;
			}
		}
	  }
      if ( ($module->enabled == true) && ($payment_zone!='') ) {
        $check_flag = false;
		$check_sql = "select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id in(" . tep_db_input($payment_zone) . ") and zone_country_id = '" . $the_zone_id . "' order by zone_id";
        $check_query = tep_db_query($check_sql);
        while ($check = tep_db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->billing['zone_id']) {
            $check_flag = true;
            break;
          }
        }
        if ($check_flag == false) {
          $module->enabled = false;
        }
      }
	}
	
	function tep_check_shipping_module_status(&$module,$payment_zone,$except_zone_list,$except_country_list){
		global $order;
	  if ( ($module->enabled == true) && (($except_zone_list!='' && substr($except_zone_list,0,1)!='M') || ($except_country_list!='' && substr($except_country_list,0,1)!='M'))) {
	  	$add_option='';
		if ($except_zone_list!='' && substr($except_zone_list,0,1)!='M') $add_option.=" geo_zone_id in(" . tep_db_input($except_zone_list) . ") ";
		if ($except_country_list!='' && substr($except_country_list,0,1)!='M') {
			if ($add_option!='') $add_option.=' or ';
			$add_option.=" zone_country_id in(" . tep_db_input($except_country_list) . ") ";
		}
		$check_query=tep_db_query("SELECT zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where  (" . $add_option. ") and zone_country_id='" . (int)$order->delivery['country']['id'] . "' and (zone_id is null or zone_id = '0' or zone_id ='" . (int)$order->delivery['zone_id'] ."');");
		if (tep_db_num_rows($check_query)>0){
			$module->enabled=false;
		}
	  }
      if ( ($module->enabled == true) && ($payment_zone!='') ) {
        $check_flag = false;
		$securepay_zone=trim($payment_zone)!=""?$payment_zone:'0';
        $check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id in(" . tep_db_input($payment_zone) . ") and zone_country_id = '" . (int)$order->delivery['country']['id'] . "' order by zone_id");
        while ($check = tep_db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->delivery['zone_id']) {
            $check_flag = true;
            break;
          }
        }
        if ($check_flag == false) {
          $module->enabled = false;
        }
      }
	}
	
	function replace_content(&$replaced_content,&$template_details){
		$ttotal_cols=1;
		//FOREACH
		//while(list($key,$value)=each($template_details)){
		foreach($template_details as $key => $value) {
			switch(substr($key,0,strpos($key,'_'))){
				case "VALUE":
					$replaced_content=str_replace("{{" . $key . "}}",$value,$replaced_content);
					break;
				case "SECTION":
					if ($value!=1){
						$replaced_content=preg_replace("/\{\{" . $key ."_START\}\}((.|\n)*)\{\{" . $key . "_END\}\}/","",$replaced_content);
					} else {
						$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
					}
					break;
				case "REPEAT":
					$start_pos=strpos($replaced_content,"{{" . $key . "_START}}")+strlen("{{" . $key ."_START}}");
					$end_pos=strpos($replaced_content,"{{" . $key . "_END}}");
					$repeat_content=substr($replaced_content,$start_pos,$end_pos-$start_pos);
					$merged_total_content='<table width="100%">' . "\n";
					$col=0;
					$row=0;
					for ($icnt=0,$n=count($value);$icnt<$n;$icnt++){
						$merged_content='';
						if ($col==0 || $ttotal_cols==1) $merged_content.='<tr>';
						$merged_content.='<td valign="top"' . ($row==0?$tcols_width:''). '>' . $repeat_content;
						reset($value[$icnt]);
						//FOREACH //shipping
						while(list($itemkey,)=each($value[$icnt])){
						//foreach([$icnt] as $itemkey, => $value) {
							$merged_content=str_replace("{{" . $key . "_" . $itemkey . "}}",$value[$icnt][$itemkey],$merged_content);
						}
						$col++;
						if ($col==$ttotal_cols) {
							$col=0;
							$row++;
						}
						$merged_total_content.="\n" . $merged_content;
					}
					$merged_total_content.="</table>";
					//$replaced_content=preg_replace("/\{\{" . $key ."_START\}\}((.|\n)*)\{\{" . $key . "_END\}\}/",$merged_total_content,$replaced_content);
					$replaced_content=substr($replaced_content,0,$start_pos) . $merged_total_content . substr($replaced_content,$end_pos);
					$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
					break;
			}
		}
	}
	
		function tep_check_password_strength($pwd)
	{
            $tot_average        = 0.0; 
            $pwdav_len            = 0.0;                 
            $pwdav_caps        = 0.0;                 
            $pwdav_nums        = 0.0;                                         
            $pwdav_small        = 0.0; 
            $pwdav_puncts        = 0.0;                 
            $total_char_used = 0; 
            if (strlen($pwd)>0) 
            { 
                $p_limit = 5; 
                $pwd_len = strlen($pwd); 
                $nums_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (is_numeric($pwd[$i])) 
                        $nums_cnt++; 
                } 
                if ($nums_cnt>0) 
                    $total_char_used += 10; 
					
                $small_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (ctype_lower($pwd[$i])) 
                    { 
                        $small_cnt++; 
                    } 
                } 
                if ($small_cnt>0) 
                { 
                    $total_char_used += 26; 
                } 
                $caps_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (ctype_upper($pwd[$i])) 
                    { 
                        $caps_cnt++; 
                    } 
                } 
                if ($caps_cnt>0) 
                { 
                    $total_char_used += 26; 
                } 
                $puncts_cnt = 0; 
                for($i=0;$i<$pwd_len;$i++) 
                { 
                    if (ctype_punct($pwd[$i])) 
                    { 
                        $puncts_cnt++; 
                    } 
                } 
                if ($puncts_cnt>0) 
                { 
                    $total_char_used += 31; 
                } 
                // calculation   
				$len_min=ENTRY_PASSWORD_MIN_LENGTH;
				$len_max=16;                                      
                if (($pwd_len>$len_min) and ($pwd_len<$len_max)) 
                { 
                    $pwdav_len += (100 / $p_limit); 
                }                                                         
                // caps 
                $tot_average += $pwdav_len; 
                if (20 <= (($caps_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_caps += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_caps += ($caps_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                $tot_average += $pwdav_caps; 
                // numbers 
                if (10 <= (($nums_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_nums += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_nums += ($nums_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                $tot_average += $pwdav_nums; 
                // small 
                if (30 <= (($small_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_small += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_small += ($small_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                $tot_average += $pwdav_small; 
                // symbols 
                if (10 <= (($puncts_cnt * 100) / $pwd_len)) 
                { 
                    $pwdav_puncts += (100 / $p_limit); 
                } 
                else 
                { 
                    $pwdav_puncts += ($puncts_cnt > 0) ? ((100 / $p_limit) - 10) :  0; 
                } 
                 
                $tot_average += $pwdav_puncts;             
                $charSet = $total_char_used; 
            } 
            $tot_average=round($tot_average, 0); 
		//	echo $tot_average;
			if($tot_average<=40)
				return false;
			else
				return true;
				
	}
	
	
	// products tree structure
	
function tep_get_products_output_tree($parent_id = '0',&$content,$default,$product_category_id=0) {
    global $FSESSION,$selected_name,$login_groups_type;
    if (!is_array($products_category_tree_array)) $products_category_tree_array = array();
	// filte to particular instructor
	$product_where = '';
	if($product_category_id>0)$product_where = " and pc.categories_id='" . tep_db_input($product_category_id) . "'";
	// iterate with nested category
	$products_categories_sql = "select pc.categories_id, pcd.categories_name, pc.parent_id from " . TABLE_CATEGORIES . " pc, " . TABLE_CATEGORIES_DESCRIPTION . " pcd where pc.categories_id = pcd.categories_id and pcd.language_id = '" . (int)$FSESSION->languages_id . "' and pc.parent_id = '" . (int)$parent_id . "'" . $product_where . " order by pc.sort_order, pcd.categories_name";
	//echo $parent_id . ":" . $events_categories_sql;exit;
	$products_categories_query = tep_db_query($products_categories_sql);
	while ($products_categories = tep_db_fetch_array($products_categories_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . write_products_category_space($products_categories['categories_id']) . tep_output_string($products_categories['categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		// select the list of products of particular category
		$products_query=tep_db_query("select pd.products_name,pd.products_id from " . TABLE_PRODUCTS . ' p, ' . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS_TO_CATEGORIES . " pcd where pcd.categories_id='" . (int)$products_categories['categories_id'] . "' " .  " and pd.language_id = " . (int)$FSESSION->languages_id . PRODUCTS_CONDITION_STATUS. " and p.products_id=pcd.products_id and p.products_id=pd.products_id order by pd.products_name");
		while ($products=tep_db_fetch_array($products_query))
		{
			$content .= '<option style="color:#000000" value="' . tep_output_string($products['products_id']) . '"';
			if ($default == $products['products_id']){
				$selected_name=$events['products_name'];
				$content .= ' SELECTED';
			}
			$content .= '>' . tep_output_string($products['products_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
		}    
		tep_get_products_output_tree($products_categories['categories_id'], $content,$default);
		$content.='</optgroup>';
	}
}
	function write_products_category_space($category_id){
	    global $FSESSION,$selected_name,$login_groups_type;
		$sql = "select parent_id,pc.categories_id,categories_name from " . TABLE_CATEGORIES . " pc," . TABLE_CATEGORIES_DESCRIPTION . " pcd where pc.categories_id=pcd.categories_id and pcd.language_id = '" . (int)$FSESSION->languages_id . "' and pc.categories_id=" . (int)$category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_products_category_space($result['parent_id']);
		}else{
			return "";
		}
	}
	// Output a form pull down menu
	function tep_draw_product_select_menu($name, $values, $default = '', $parameters = '', $required = false,$initial_category_id=0,$need_all=true,$initial_parent_id=0) {
		global $selected_name;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= '>';
		if($need_all)
		$field .= '<option style="color:#000000" value="-1">' . TEXT_SELECT . '</option>';
	
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		$content="";
		tep_get_products_output_tree($initial_parent_id,$content,$default,$initial_category_id);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}
	function tep_get_products_array_single($first=''){
		global $FSESSION;
		$product_array=array();
		$product_query=tep_db_query("SELECT p.products_id,pd.products_name from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_id=pd.products_id " . PRODUCTS_CONDITION_STATUS . " and language_id='" . (int)$FSESSION->languages_id. "' order by pd.products_name");
		while($product_result=tep_db_fetch_array($product_query)){
			$product_array[]=array('id'=>$product_result['products_id'],'text'=>$product_result['products_name']);
		}
		return $product_array;
	} 
  function tep_info_image($image, $alt, $width = '', $height = '') {
    if (tep_not_null($image) && (file_exists(DIR_WS_IMAGES . $image)) ) {
      $image = tep_image(DIR_WS_IMAGES . $image, $alt, $width, $height);
    } else {
      $image = $alt;
    }
    return $image;
  }
 function check_restrick(){
   global $FSESSION,$FREQUEST,$customer_group_id;
    if(!$customer_group_id && $FSESSION->customer_id>0) $customer_group_id=get_customer_group_id();
    $check_restrict_customer="and ((restrict_to_customers='' OR ISNULL(restrict_to_customers)) AND (restrict_to_groups='' OR ISNULL(restrict_to_groups)))";     
    if($FSESSION->customer_id>0) $check_restrict_customer=substr($check_restrict_customer,0,-1)." OR (restrict_to_customers like '%". tep_db_input($FSESSION->customer_id) ."%' OR restrict_to_groups like '%". tep_db_input($customer_group_id) ."%'))";    
    $return=false;
    if($FREQUEST->getvalue('products_id')!='' && $FREQUEST->getvalue('products_id','int')>0){
		$check_product_query=tep_db_query("select products_id from ".TABLE_PRODUCTS." where products_id='".$FREQUEST->getvalue('products_id','int')."' ".$check_restrict_customer);		
		
		if(tep_db_num_rows($check_product_query)>0) $return=true;
    }
    return $return;
 }   
 function get_customer_group_id(){
 	global $FSESSION;
 	$customer_group_id="";
 	if($FSESSION->customer_id>0){
 		$customer_group_query=tep_db_query("select customers_groups_id from ".TABLE_CUSTOMERS." where customers_id='".(int)$FSESSION->customer_id."'"); 		
 		if(tep_db_num_rows($customer_group_query)>0) {
 			$customer_group=tep_db_fetch_array($customer_group_query);
 			$customer_group_id=$customer_group['customers_groups_id'];			
 		} 		
 	}
 	return $customer_group_id;
 }
 
 function tep_show_products_price($inital_price,$product_info,$select_quantity=true,$quantity_combo=false){
 	global $currencies,$products_price;
 	$output="<b>" . TEXT_PRICE . ": " .$products_price . "</b>";
 	if ($product_info["products_price_break"]!='Y') return $output;
	$breaks_query=tep_db_query("SELECT quantity,discount_per_item from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" .(int)$product_info["products_id"] . " order by quantity");
	
	if(tep_db_num_rows($breaks_query)<=0) return $output;
	$output="";
	$tax=tep_get_tax_rate($product_info['products_tax_class_id']);
	$select_script="";
	if ($select_quantity){
		$select_script="onMouseOver='javascript:rowOverEffect2(this);' onMouseOut='javascript:rowOutEffect2(this);' onClick='javascript:setQuantity(this,%s)'";
		$output.='<script>var prev;function setQuantity(object,quan){object.className="moduleRowSelected";document.getElementById("qty").value=quan;if(prev && prev!=object) prev.className="moduleRow";prev=object;load_stock_first('. $product_info["products_id"] .');}function rowOverEffect2(object) { if (object.className == "moduleRow") object.className = "moduleRowOver";}function rowOutEffect2(object) {if (object.className == "moduleRowOver") object.className = "moduleRow";}</script><input type="hidden" name="qty" value=1 id="qty">';
	}
	$output.='<table cellpadding="2" width="100%" id="tablePriceBreaks">
				<tr>
					<td class="smallText" align="right"><b>' . TEXT_QUANTITY  . '</b></td>
					<td class="smallText" align="right"><b>' . TEXT_PRICE . '</b></td>
				</tr>
				<tr class="moduleRow" ' . sprintf($select_script,1) . '>
					<td class="smallText" align="right"><b>1</b></td>
					<td class="smallText" align="right"><b>' .$currencies->format(tep_add_tax($product_info["products_price"], $tax)) . '</b></td>
				</tr>';
				
				
	while ($break_result = tep_db_fetch_array($breaks_query)) {
	    $quantity=$break_result['quantity'];
		$price=$currencies->format(tep_add_tax($product_info["products_price"]-$break_result['discount_per_item'], $tax) * $quantity);
		$output.='<tr class="moduleRow" ' . sprintf($select_script,$quantity) . '>
					<td class="smallText" align="right"><b>' . $quantity  . '</b></td>
					<td class="smallText" align="right"><b>' . $price . '</b></td>
				</tr>';
	}
	if ($quantity_combo){
		$price_breaks=tep_get_products_price_breaks($product_info["products_id"]);
		$output.='<tr height="10"><td></td></tr><tr><td class="main" colspan="2" align="right">' . TEXT_QUANTITY . ': ' . tep_draw_pull_down_menu('qty',$price_breaks,1) .'</td></tr>';
	}
	$output.='</table><script>setQuantity(document.getElementById("tablePriceBreaks").rows[1],1)</script>';
	
	return $output;
 }
 
 function tep_get_products_breaks($product_info,$tax_rate){
 	global $currencies;
	
	$breaks_query=tep_db_query("SELECT quantity,discount_per_item from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" .(int)$product_info["products_id"] . " order by quantity");
	if(tep_db_num_rows($breaks_query)<=0) return false;
	$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"]="{enabled:true,prices:{";
	$result=array();
	$icnt=0;
	
	//$result[]=array('QUANTITY'=>1,"PRICE"=>$currencies->format(tep_add_tax($product_info["products_price"],$tax_rate)));
	
	$GLOBALS["JS_START"].="setQuantity('','1');\n";
	//edited 2016 qpb
	//the 
	while ($break_result = tep_db_fetch_array($breaks_query)) {
		//$price=tep_add_tax($product_info["products_price"]-$break_result['discount_per_item'], $tax_rate) * $break_result['quantity'];
		$price=tep_add_tax($break_result['discount_per_item'], $tax_rate);
	    $result[]=array('QUANTITY'=>$break_result['quantity'],"PRICE"=>$currencies->format($price));
		$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"].=$break_result['quantity'] .":" . $price . ",";
				
		$icnt++;
	}
	$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"]=substr($GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_BREAKS"],0,-1) . "}}";
	return $result;
 }
 function tep_get_products_price_breaks($products_id){
 	$price_breaks=false;
	$breaks_query=tep_db_query("SELECT quantity from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" . (int)$products_id . " order by quantity");
	if (tep_db_num_rows($breaks_query)>0){
		$price_breaks=array(array('id'=>1,'text'=>1));
		while($breaks_result=tep_db_fetch_array($breaks_query)){
			$price_breaks[]=array('id'=>$breaks_result["quantity"],'text'=>$breaks_result["quantity"]);
		}
	}
	return $price_breaks;
 }
 function tep_get_products_price_breaks_discount($products_id, $quantity_in_cart){
 	$discount=0;
	$breaks_query=tep_db_query("SELECT quantity, discount_per_item from " . TABLE_PRODUCTS_PRICE_BREAK . " where products_id=" . (int)$products_id . " order by quantity");
	if (tep_db_num_rows($breaks_query)>0){
	while($breaks_result=tep_db_fetch_array($breaks_query)){
        if ($quantity_in_cart >= $breaks_result['quantity']) {
          $discount = $breaks_result['discount_per_item'] * $quantity_in_cart;
        }
		}
	}
   return $discount;
 }
 
function tep_write_payment_response($order_id,$payment_response){
	tep_db_query("insert into ".TABLE_PAYMENT_RESPONSE." (order_id,payment_response) values('" . tep_db_input($order_id) . "','" . tep_db_input($payment_response) . "')");
}
function tep_update_payment_response_code($old_id,$order_id){
	tep_db_query("UPDATE ".TABLE_PAYMENT_RESPONSE." set order_id='" . tep_db_input($order_id) . "' where order_id='" . tep_db_input($old_id) . "'");
}
function tep_join_keys_arr($arr,$sep){
	if (count($arr)<=0) return "";
	$payment_response="";
	reset($arr);
	while( list($key,$value) = each($arr)){
		$payment_response.="$key => " . tep_db_prepare_input($value) . $sep;
	}
	return $payment_response;
}
function tep_get_plain_products_price($products_price){
     global $FSESSION;
	  if (!$FSESSION->is_registered('customer_id')) {
		 $customer_discount = 0;
		 if (defined("GUEST_DISCOUNT")) $customer_discount=(int)GUEST_DISCOUNT;
		 if ($customer_discount >= 0) {
			$products_price = $products_price + $products_price * abs($customer_discount) / 100;
		 } else {
			$products_price = $products_price - $products_price * abs($customer_discount) / 100;
		 }
		 return $products_price;
		 
	  } elseif ($FSESSION->is_registered('customer_id')) {
		 $query = tep_db_query("select g.customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " g inner join  " . TABLE_CUSTOMERS  . " c on g.customers_groups_id = c.customers_groups_id and c.customers_id = '" . (int)$FSESSION->customer_id . "'");
		 $query_result = tep_db_fetch_array($query);
		 $customers_groups_discount = $query_result['customers_groups_discount'];
		 $query = tep_db_query("select customers_discount from " . TABLE_CUSTOMERS . " where customers_id =  '" . (int)$FSESSION->customer_id . "'");
		 $query_result = tep_db_fetch_array($query);
		 $customer_discount = $query_result['customers_discount'];
		 $customer_discount = $customer_discount + $customers_groups_discount;
		 if ($customer_discount >= 0) {
			$products_price = $products_price + $products_price * abs($customer_discount) / 100;
		 } else {
			$products_price = $products_price - $products_price * abs($customer_discount) / 100;
		 }
		return $products_price;
	  }
}
// 
 function get_order_countryname($country_id) {
 	file_put_contents('test1.txt',"select * from " . TABLE_COUNTRIES . " where countries_id = '" . tep_db_input($country_id) . "'\n");
    $country_name_query = tep_db_query("select * from " . TABLE_COUNTRIES . " where countries_id = '" . tep_db_input($country_id) . "'");
    if (!tep_db_num_rows($country_name_query)) {
      return 0;
    }
    else {
      $country_name_row = tep_db_fetch_array($country_name_query);
      return $country_name_row['countries_name'];
    }
  }	
//cartzone fix php4 error
if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}
function tep_check_country_differ($payment=false){
	global $order,$IP_COUNTRY,$USER_BARRED;
	
	$USER_BARED=false;
	if ((BLOCK_DIFFER_COUNTRY_IP!='Yes' && BLOCK_EXCLUDED_COUNTRIES!='Yes') || (BLOCK_DIFFER_COUNTRY_IP!='Yes' && !$payment)) return;
	$IP_COUNTRY=tep_get_ip_country();
	if (BLOCK_DIFFER_COUNTRY_IP!='Yes' || $IP_COUNTRY=="") return;
	if ($IP_COUNTRY!=$order->customer["country"]["iso_code_2"] && $IP_COUNTRY!=$order->customer["country"]["iso_code_3"] && strtolower($IP_COUNTRY)!=strtolower($order->customer["country"]["title"])){
		$USER_BARRED=true;
	}
}
function tep_get_ip_country(){
	if (isset($_SESSION["ip_country"])){
		return $_SESSION["ip_country"];
	}
	$ip=$_SERVER["REMOTE_ADDR"];
	$country="";
	if (defined("GEOIP_LICENSE_KEY") && GEOIP_LICENSE_KEY!=''){
		$query = "http://maxmind.com:8010/a?l=" . GEOIP_LICENSE_KEY . "&i=" . $ip;
		$url = parse_url($query);
		$host = $url["host"];
		$path = $url["path"] . "?" . $url["query"];
		$timeout = 1;
		$fp = @fsockopen ($host, 8010, $errno, $errstr, $timeout);
		if ($fp) {
		  @fputs ($fp, "GET $path HTTP/1.0\nHost: " . $host . "\n\n");
		  while (!feof($fp)) {
			$buf .= fgets($fp, 128);
		  }
		  $lines = split("\n", $buf);
		  $country = $lines[count($lines)-1];
		  fclose($fp);
		} 
		if (strlen($country)>3) $country="";
	} else {
		$result=@file_get_contents("http://www.ippages.com/simple/?ip=" . $ip . "&get=country");
		if (strpos($result,"-")!==false){
			$splt=preg_split("/-/",$result);
			$country=$splt[0];
		}
	}
	$_SESSION["ip_country"]=$country;
	return $country;
	
}
function tep_get_country_title($iso_code){
	$query=tep_db_query("SELECT countries_name from " . TABLE_COUNTRIES . " where countries_iso_code_2='" . tep_db_input( $iso_code). "' or countries_iso_code_3='"  . tep_db_input($iso_code) . "' or lower(countries_name)='" . tep_db_input((strtolower($iso_code))) . "'");
	$result=tep_db_fetch_array($query);
	return $result["countries_name"];
}
function tep_output_differ_check(){
	global $IP_COUNTRY,$USER_BARRED;
	if (!$USER_BARRED) return;
	echo '<tr>
			<td  class="messageStackWarning" style="padding:4px">
			<table cellpadding="2" width="100%">
				<tr>
					<td class="smallText"><img src="images/icons/error.gif" alt="Transaction barred"><b>' . TEXT_TRANSACTION_BARRED . '</b>
				</tr>
				<tr>
					<td class="smallText">' . sprintf(TEXT_TRANSACTION_BARRED_REASON,tep_get_country_title($IP_COUNTRY)) . '
					</td>
				</tr>
			</table>
			</td>
		</tr>
		 ';
}
function tep_check_payment_barred($exclude){
	global $IP_COUNTRY;
	if ($exclude=="" || substr($exclude,0,1)=='M') return false;
	if ($IP_COUNTRY=="") return false;
	if (BLOCK_EXCLUDED_COUNTRIES!='Yes') return false;
	
	$query=tep_db_query("SELECT countries_name from " . TABLE_COUNTRIES . " where countries_iso_code_2='$IP_COUNTRY' or countries_iso_code_3='$IP_COUNTRY' or lower(countries_name)='" . strtolower($IP_COUNTRY) . "' and countries_id in(" . $exclude . ")");
	if (tep_db_num_rows($query)>0) return true;
	return false;
}
 function get_discount_details($orders_id,$product_id){
 global $currencies;
 	$return='';
    $product_query = tep_db_query("select discount_type,discount_text,products_price,final_price,products_tax,products_quantity from " . TABLE_ORDERS_PRODUCTS . " where orders_id='" . (int)$orders_id . "' and products_id='" . (int)$product_id . "'" );
	
	$product_result=tep_db_fetch_array($product_query);
	if($product_result['discount_type']=='C' || $product_result['discount_type']=='S') {
		$product_to_categories_query = tep_db_query("select categories_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$product_id . "'");
		$product_to_categories = tep_db_fetch_array($product_to_categories_query);
		$category = $product_to_categories['categories_id'];
		$fp=$product_result["final_price"];
		$tax=$product_result["products_tax"];
		$qty=$product_result["products_quantity"];
		$price=$product_result['products_price'];
		$product_amount=tep_add_tax(($price * $product_result['products_quantity']),$tax);
		$final_amount=tep_add_tax(($fp*$product_result['products_quantity']),$tax);
		$total=($product_amount-$final_amount);
		
			$return .=TEXT_DISCOUNT_APPLIED . '&nbsp;&nbsp;'. $product_result['discount_text']  . '<br>';
			$return .=TEXT_ORIGINAL_AMOUNT . '&nbsp;&nbsp;'. $currencies->format($product_amount) . '<br>';
			$return .=TEXT_DISCOUNT . '&nbsp;&nbsp;'. $currencies->format($total);
				
	}
	return $return;
 	
 }
 
 function tep_get_post_vars($post_value,$name="",$filter_array=array()){
 	global $POST_HIDDEN;
 	if (count($post_value)<=0) return;
	reset($post_value);
	while(list($key,)=each($post_value)){
		if ($name=="" && in_array($key,$filter_array)) continue;
		if (is_array($post_value[$key])){
			tep_get_post_vars($post_value[$key],($name==''?$key:$name . "[" . $key . "]"));
		} else {
			$POST_HIDDEN.='<input type="hidden" name="' . ($name==''?$key:$name . "[" . $key . "]") . '" value="' . tep_output_string($post_value[$key]) . '">' . "\n";
		}
	}
 }
 
  ############################## unique id
	function tep_create_unique_id ($orders_id, $orders_products_id,  $qty){
	// function to create a 20 character code for use in QR
	// check for database table if not found create
	tep_db_query("CREATE TABLE IF NOT EXISTS `orders_tickets` (
			`orders_tickets_id` int(11) NOT NULL AUTO_INCREMENT,
			`orders_id` int(11) NOT NULL,
			`orders_products_id` int(11) NOT NULL,
			`orders_products_id_index` int(4) NOT NULL,
			`unique_id` text (20) NOT NULL,
			PRIMARY KEY (`orders_tickets_id`)
	) ");
	 /// populate the table 
	 
	 //first check that the ticket has not already been entered - this will happen if the customer relaods the pdf
	 		     $unique_query = tep_db_query("select * from orders_tickets where orders_id='" . (int)$orders_id . "' and orders_products_id = '".(int)$orders_products_id."' and orders_products_id_index = '".(int)$qty."' LIMIT 1" );
				if (tep_db_num_rows($unique_query)>0){
					$result=tep_db_fetch_array($unique_query);
					return $result["unique_id"];
				
				 }else{
	 
	 	//for ($i=0, $n=$qty; $i<$n; $i++) {
		//make up the twenty digit id here use zero padding so
		//   order_id  order_products_id order_products_id_index random filler
		//     5            6                 3                       6
		// lay them out below for clarity = could just be dumped into the array that follows
		
		$orders_id = sprintf('%05d', $orders_id); 
		$orders_products_id = sprintf('%06d', $orders_products_id);
		$orders_products_id_index = sprintf('%03d', $qty);
		$random_filler = mt_rand(100000, 999999);
		
		$unique_id = $orders_id.$orders_products_id.$orders_products_id_index.$random_filler;
	
    	$sql_data_array = array(
								'orders_id' => $orders_id,
								'orders_products_id' => $orders_products_id,
								'orders_products_id_index' => $orders_products_id_index,
								'unique_id' => $unique_id
								);
		tep_db_perform('orders_tickets', $sql_data_array);
				//	}
		return $unique_id;
		}
	}
	
	function tep_get_unique_ids ($order_id){
	     //returns an array of unique numbers
		 //query the table and get the numbers
		     $unique_query = tep_db_query("select * from orders_tickets where orders_id='" . (int)$order_id . "'" );
				if (tep_db_num_rows($unique_query)>0){
				   $response = array();
				   while($unique_result=tep_db_fetch_array($unique_query)){
						$response[]=array('products_id'=>$unique_result["orders_products_id"],'unique_id'=>$unique_result["unique_id"]);
		                                             }
					return $response;
				 }else{
				    return false;
     }
	 }
	 
	function tep_get_order_id_from_unique($unique){
	$query=tep_db_query("SELECT orders_id from orders_tickets where unique_id='" . tep_db_input( $unique). "'");
	$result=tep_db_fetch_array($query);
	return $result["orders_id"];
}
	############################## unique id ends
	
	 function kill_season_queue($order_id){
	  global $FSESSION;
	  tep_db_query("DELETE FROM `coupon_season_queue` where  `order_id` = '".$order_id."'");
		
		return false;
  }
	  
  function update_season_queue($order_id, $order_status){
	  global $FSESSION;
	  //update the flag field to match the order status
	  if(is_int($order_id) && is_int($order_status)){
		   tep_db_query("UPDATE `coupon_season_queue` set `flag` = '".$order_status."' where  `order_id` = '".$order_id."'");		  
	  }
	  // now update  the entries where flag =3 	   
	   	if($order_status==3) {
			
		//how many season tickets to grant
		 $season_query = tep_db_query("select amount, customer_id from `coupon_season_queue`  where  `order_id` = '".$order_id."'");

		$season_count =tep_db_num_rows($season_query);
		if ($season_count > 0 ){
        $season_result = tep_db_fetch_array($season_query);
        $season_amount = $season_result['amount'];

		 
		 //is there any in the account already?

		
        $gv_query = tep_db_query("select amount from " . TABLE_COUPON_GV_CUSTOMER . " where customer_id = '" . $season_result['customer_id'] . "'");
		$gv_count =tep_db_num_rows($gv_query);
		if ($gv_count > 0 ){
        $gv_result = tep_db_fetch_array($gv_query);
        $gv_amount = $gv_result['amount'] + $season_amount;
        $gv_update = tep_db_query("update " . TABLE_COUPON_GV_CUSTOMER . " set amount = '" . $gv_amount . "' where customer_id = '" . $season_result['customer_id'] . "'");}
		
		 else{
		  	$sql_data_array = array(
							'customer_id' => $season_result['customer_id'], 
							'amount' => $season_amount							
							);
    		tep_db_perform(TABLE_COUPON_GV_CUSTOMER, $sql_data_array);
		 }
		 	// now lets remove the queue entry
        	  tep_db_query("DELETE FROM `coupon_season_queue` where `customer_id`='".$season_result['customer_id'] ."' and `order_id` = '".$order_id."'");
			//and note the order
				$sql_data_array = array(
						'orders_id' => $order_id,
						'orders_status_id' =>  $order_status,
						'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
						'customer_notified' => 0,
						'comments' => $season_amount . ' season tickets released',
						'user_added'=>"web"
						);
						
	tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
		}
		}
  }  
  
   #############################################################
    #       Generate Unique Code                                #
    #############################################################
    
    function tep_generate_coupon_code(){
        global $order;
        
        $code_to_test = strtoupper(substr($order->customer['lastname'],0,1)  . substr($order->customer['firstname'],0,1));
        $random =  bin2hex(openssl_random_pseudo_bytes(4));
        $code_to_test .= str_replace('0', '', strtoupper($random));
        
        $coupon_details_raw = "select coupon_code from " . TABLE_COUPONS ." c where coupon_code =  '". $code_to_test . "' ";
		$coupon_details_query = tep_db_query($coupon_details_raw);
		if (tep_db_num_rows($coupon_details_query)>0){
		  tep_generate_coupon_code();
          }else{
        return $code_to_test;
        }
      }
  
  function tep_verify_coupons($order_id=''){
    
          $sql_extra = '';
          
          if (tep_not_null($order_id) && is_numeric($order_id)){
             $sql_extra = "o.orders_id = " . $order_id . " and ";
          }       
          
            $coupon_query=tep_db_query("select    c.uses_per_coupon, c.orders_id, c.coupon_id 
                                       from " . TABLE_COUPONS . " c, 
                                       orders o
                                       where 
                                       c.orders_id  = o.orders_id and
                                       o.orders_status = 3 and 
                                       ".$sql_extra."
                                       c.coupon_active='N' 
                                       ");
                                       
        $coupon=tep_db_fetch_array($coupon_query);
        while ($coupon=tep_db_fetch_array($coupon_query)){
	       	$coupon_count = tep_db_query("select coupon_id from " . TABLE_COUPON_REDEEM_TRACK . "
                                          where coupon_id = '" . tep_db_input($coupon['coupon_id'])."'");
                                             
        if (tep_db_num_rows($coupon_count) < $coupon['uses_per_coupon'] && $coupon['uses_per_coupon'] > 0 ) {
              tep_db_query("update " . TABLE_COUPONS . " set coupon_active = 'Y' where coupon_id = '" . $coupon['coupon_id'] . "'");
            }
        }
} 
  
 
 require("wallet_general.php");
?>